我正在为一个服务编写单元测试用例,其中一个function1在for循环中调用另一个function2。 Function2调用http.get('API')。 function2的测试用例工作正常,但Function1的测试用例给出错误:“错误:预期一个匹配的条件请求”按功能匹配:“,找到2个请求。”
我的代码是服务如下: -
getReport(Id: string) {
const url = `${environment.PATH}/reports/${Id}`;
const options: {
responseType: 'blob'
} = {
responseType: 'blob'
};
return this.http.get(url, options)
.map(
(res) => {
// return new Blob([res], { type: 'application/vnd.ms-excel'});
return new Blob([res], {
type: 'vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
});
}
getReports(Ids: string[] = []) {
const Links: string[] = [];
for (let i = 0; i < Ids.length; i++) {
this.getReport(Ids[i]).toPromise()
.then(
(res) => {
const ext = Ids[i];
saveAs(res, ext + '.xlsx');
});
}
}
测试用例如下:
it('getReport should return excel report', inject([HttpClient, HttpTestingController],
(http: HttpClient, httpMock: HttpTestingController) => {
const reportService = getTestBed().get(Service);
reportService.getReport('id').map(
res => {
expect(res).toBeTruthy();
return Observable.of(res);
}
)
.subscribe();
const req = httpMock.expectOne(req => req.url.includes('url'));
// Assert that the request is a GET.
expect(req.request.method).toEqual('GET');
// Respond with mock data, causing Observable to resolve.
// Subscribe callback asserts that correct data was returned.
req.flush(new Blob);
// Finally, assert that there are no outstanding requests.
httpMock.verify();
}));
it('getReports should call getReport to each ID', inject([HttpClient, HttpTestingController],
(http: HttpClient, httpMock: HttpTestingController) => {
const reportService = getTestBed().get(Service);
spyOn(reportService, 'getReport').and.callThrough();
const sessList = ['id2'];
reportService.getReports(sessList);
for (let i = 0; i < sessList.length; i++) {
reportService.getReport(sessList[i]).map(
res => {
expect(res).toBeTruthy();
return Observable.of(res);
}
)
.subscribe();
const req = httpMock.expectOne(req => req.url.includes('url'));
expect(req.request.method).toEqual('GET');
req.flush(new Blob);
}
}));