[英]Angular unit test Spinner Interceptor
我有一個 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.
Expected spy SpinnerService.hide to have been called once. It was called 0 times.
嘗試:
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({});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.