我想用HttpClientTestingModule
. 在我将 rxjs 添加retry(2)
到 HTTP 调用之前,这可以正常工作。然后,测试明显抱怨发现了一个意外的请求:
预计没有打开的请求,找到 1
但是现在,我不知道如何使用以下命令来期待两个请求HttpTestingController
:
服务.ts
@Injectable()
export class Service {
constructor(private http: HttpClient) { }
get() {
return this.http.get<any>('URL')
.pipe(
retry(2),
catchError(error => of(null))
)
}
}
服务规范.ts
describe('Service', () => {
let httpTestingController: HttpTestingController;
let service: Service;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [Service],
imports: [HttpClientTestingModule]
});
httpTestingController = TestBed.get(HttpTestingController);
service = TestBed.get(Service);
});
afterEach(() => {
httpTestingController.verify();
});
it('should handle 404 with retry', () => {
service.get().subscribe((data: any) => {
expect(data).toBe(null);
});
expectErrorResponse(404);
});
function expectErrorResponse(status: number) {
const requests = httpTestingController.match('URL');
// fails -> finds only one request
expect(requests.length).toBe(2);
requests.forEach(req => req.flush('error', {status, statusText: 'Not Found'}));
}
});
如果我删除expect(requests.length).toBe(2)
,测试将失败并显示之前的错误消息。
运行示例
你可以试试这个Stackblitz