javascript - 如何在角度单元测试中对服务进行单元测试?
问题描述
我的服务中有如下功能,
exportPayGapDetails(filterObject: PayGapDetailFilter): void {
const url = `${this.payGapDetailExportUrls[filterObject.type]}`;
this.http
.post<PollInitResponse>(
`/adpi/rest/v2/sb/pe/v1/export/1/getStatusValue/222`,
{}
)
.subscribe(
res => {
if (res) {
this.pollingServiceService.pollRequest(
`/adpi/rest/v2/sb/pe/v1/export/1/status`,
this.ReadytoDownload.bind(this),
this.PollCondition.bind(this)
);
} else {
this.showToastMessage('error found);
}
},
() => {
this.showToastMessage('error found'
);
}
);
}
我的测试用例,
it('should call gender pay gap details init api when we pass type as GENDER_GAP on Export', fakeAsync(() => {
spyOn(pollingService, 'pollRequest').and.callThrough();
payGapDetailsService.exportPayGapDetails(filterDetailObject);
// pollingService.pollSubscriptions.unsubscribe();
tick();
const req = http.expectOne(
request =>
request.method === 'POST' &&
request.url === '/adpi/rest/v2/sb/pe/v1/export/1/getStatusValue/222'
);
req.flush(exportInitSucessResponse);
http.verify();
}));
当我运行时它会抛出错误,
Error: Expected no open requests, found 1: GET /adpi/rest/v2/sb/pe/v1/export/1/status
我知道它与 this.pollingServiceService.pollRequest( 这个函数有关,但我不知道如何解决它。谁能给我建议帮助。谢谢。
解决方案
尝试使用 HttpTestingController 模拟此请求:
it('should call gender pay gap details init api when we pass type as GENDER_GAP on Export', fakeAsync(() => {
spyOn(pollingService, 'pollRequest').and.callThrough();
payGapDetailsService.exportPayGapDetails(filterDetailObject);
httpMock = TestBed.get(HttpTestingController);
tick();
const request = httpMock.expectOne('/adpi/rest/v2/sb/pe/v1/export/1/getStatusValue/222');
expect(request.request.method).toEqual('POST');
req.flush(exportInitSucessResponse);
http.verify();
}));
推荐阅读
- python - pytz.exceptions.UnknownTimeZoneError:“亚洲/加尔各答”
- google-cloud-functions - Firebase 日志错误 FAILED_PRECONDITION 代码 9
- reactjs - 如何在反应中正确导出包含多个类的组件
- sql-server - DBeaver 恢复 SQL Server .bak 文件
- java - 如何根据 firebase 中的 id 更新另一个用户余额?
- r - R list.files:一些正则表达式只返回一个文件
- php - 修改数组合并
- android - 是否可以将在 android-x 中创建的库添加为我的项目中尚未迁移到 android-x 的模块?
- javascript - 如何使用 botframework 网络聊天一个接一个地发送 2 个事件?
- android - 如何从我的应用程序将信用卡添加到 Google Pay?