我最近将Angular5项目升级到了Angular6,而我不得不更改的一件事就是使用了HttpClient,并引入了水龙头和水管技术。
我的代码如下:
public getCountryData(id: string): Country[] {
const url = `${this.config.apiUrl}/${id}`;
return this.http.get<CountryData>(url, this.noCacheOptions).pipe(
tap(res => {
res = this.convertToCountryArray(res);
return res;
}),
catchError(error => this.handleError(error))
);
}
我正在编写测试以涵盖我的API调用,我需要测试一个成功的get和一个错误,因此我编写了以下测试(前言-我是编写这些单元测试的新手,所以怀疑它是否可以做得更好,任何建议都值得赞赏!):
it('should call getCountryData, inject([HttpTestingController, CountryDataService, ConfigService],
(httpMock: HttpTestingController, dataService: CountryDataService, configService: ConfigService) => {
expect(CountryDataService).toBeTruthy();
const id = 'cfc78ed9-4e771215efdd64b1';
dataService.getCountryData(id).subscribe((event: any) => {
switch (event.type) {
case HttpEventType.Response:
expect(event.body).toEqual(mockCountryList);
}
}, (err) => {
expect(err).toBeTruthy();
});
const mockReq = httpMock.expectOne(`${configService.apiUrl}/${id}`);
expect(mockReq.cancelled).toBeFalsy();
expect(mockReq.request.responseType).toEqual('json');
try {
mockReq.flush(new Error(), { status: 404, statusText: 'Bad Request' });
} catch (error) {
expect(error).toBeTruthy();
}
httpMock.verify();
})
);
当我查看代码覆盖率时,我可以看到并非所有分支都被测试覆盖。但是我不确定要进行哪些更改才能正确覆盖此内容。关于我需要更改的任何指示或建议都很棒!
谢谢!
答案 0 :(得分:0)
所以我很快发现了解决方法。只是在其他人觉得有用的情况下发布。我将api的正面和负面测试分为两个单元测试,如下所示:
it('should call getCountryData with success', () => {
const id = 'cfc78ed9-4e771215efdd64b1';
dataService.getCountryData(id).subscribe((event: HttpEvent<any>) => {
switch (event.type) {
case HttpEventType.Response:
expect(event.body).toEqual(mockCountryData);
}
});
const mockReq = httpMock.expectOne(`${configService.apiUrl}/${id}`);
expect(mockReq.cancelled).toBeFalsy();
expect(mockReq.request.responseType).toEqual('json');
mockReq.flush(mockCountryData);
httpMock.verify();
});
it('should call getCountryData with failure', () => {
const id = 'cfc78ed9-4e771215efdd64b1';
dataService.getCountryData(id).subscribe((event: HttpEvent<any>) => { },
(err) => {
expect(err).toBeTruthy();
});
const mockReq = httpMock.expectOne(`${configService.apiUrl}/${id}`);
expect(mockReq.cancelled).toBeFalsy();
expect(mockReq.request.responseType).toEqual('json');
mockReq.flush({ errorType: 2,
errorDetails: [{ errorKey: 'errorKey', errorCode: '1001', errorMessage: 'errorMessage' }],
errorIdentifier: 'cfc78ed9-4e771215efdd64b1' },
{ status: 404, statusText: 'Bad Request' });
httpMock.verify();
});
主要区别在于,一个刷新成功对象,一个刷新错误。