我有一个用于HTTP请求的拦截器。对于每个http请求微调器都会显示。
我想为此拦截器编写一个单元测试,以检查spinnerServiceSpy.show
和spinnerServiceSpy.hide
是否被正确调用。
export class SpinnerInterceptor implements HttpInterceptor {
requestCount = 0;
constructor(private spinnerService: SpinnerService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.requestCount++;
this.spinnerService.show();
return next.handle(request)
.pipe(
finalize(() => {
this.requestCount--;
if (this.requestCount === 0) {
this.spinnerService.hide();
}
})
);
}
}
如您所见,此函数是从finalize()RxJS运算符调用的。此拦截器的单元测试如下:
describe(`SpinnerInterceptor`, () => {
let httpMock: HttpTestingController;
let service: ApiService;
let interceptor: SpinnerInterceptor;
const spinnerServiceSpy = jasmine.createSpyObj('SpinnerService', ['show', 'hide']);
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
ApiService,
SpinnerInterceptor,
{ provide: SpinnerService, useValue: spinnerServiceSpy },
{ provide: HTTP_INTERCEPTORS, useClass: SpinnerInterceptor, multi: true }
],
});
interceptor = TestBed.get(SpinnerInterceptor);
service = TestBed.get(ApiService);
httpMock = TestBed.get(HttpTestingController);
});
it('should hide spinner', () => {
service.getCountRecords('Faculty')
.pipe(
finalize(() => expect(spinnerServiceSpy.hide).toHaveBeenCalledTimes(1)))
.subscribe(res => {
expect(spinnerServiceSpy.show).toHaveBeenCalledTimes(1);
});
httpMock.expectOne('Faculty/countRecords').flush({});
});
});
但是我收到以下错误Expected spy SpinnerService.hide to have been called once. It was called 0 times.
答案 0 :(得分:0)
尝试:
it('should hide spinner', async done => {
await service.getCountRecords('Faculty').pipe(
take(1),
).toPromise()
.then(res => {
expect(spinnerServiceSpy.hide).toHaveBeenCalledTimes(1);
expect(spinnerServiceSpy.show).toHaveBeenCalledTimes(1);
done();
});
httpMock.expectOne('Faculty/countRecords').flush({});
});