[英]Angular Unit Test for Http Error Interceptor mot working
我有以下 http 錯誤攔截器:
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(private util: UtilService,
private matomoService: MatomoService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
catchError((error: HttpErrorResponse) => {
let data: any = {};
if (error.error instanceof ErrorEvent) {
// Client side error
data = 'error'
this.util.alerts$.next(data);
this.matomoService.eventTracking('error', 'client_error', data.description);
} else {
// Server side error
data = 'error';
this.util.alerts$.next(data);
this.matomoService.eventTracking('error', 'api_error', data.description);
}
console.log(error);
return throwError(error.message);
})
);
}
}
我的單元測試如下:
describe('HttpInterceptorService', () => {
let injector: TestBed;
let httpMock: HttpTestingController;
let matomoService: MatomoService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [HttpErrorInterceptor,
UtilService,
MatomoService,
SomeThemeService,
{
provide: HTTP_INTERCEPTORS,
useClass: HttpErrorInterceptor,
multi: true
}
],
imports: [RouterTestingModule,
HttpClientTestingModule]
});
injector = getTestBed();
matomoService = injector.get(MatomoService);
httpMock = injector.get(HttpTestingController);
});
fit('should call matomo tracking for errors', () => {
const ldapApiService = injector.get(LdapApiService);
const matomoSpy = spyOn(matomoService, 'eventTracking');
ldapApiService.getLDAPUsers('https://some-dummy-url').subscribe(res => {
expect(res).toBeTruthy();
});
const httpReq = httpMock.expectOne('https://some-dummy-url');
expect(matomoSpy).toHaveBeenCalledTimes(1);
});
});
這失敗並出現錯誤Expected spy eventTracking to have been called once. It was called 0 times.
Expected spy eventTracking to have been called once. It was called 0 times.
我正在從https://medium.com/@dev.s4522/how-to-write-unit-test-cases-for-angular-http-interceptor-7595cb3a8843幫助編寫這個單元測試。 你能幫助為什么沒有調用 matomoSpy 或者我們如何測試這個攔截器。
您必須像這樣刷新請求:
httpReq.flush();
此外,您的期望必須在訂閱中。 要確保調用訂閱中的代碼,您必須像這樣使用done
:
fit('should call matomo tracking for errors', (done) => {
const ldapApiService = injector.get(LdapApiService);
const matomoSpy = spyOn(matomoService, 'eventTracking');
ldapApiService.getLDAPUsers('https://some-dummy-url').subscribe(res => {
expect(res).toBeTruthy();
expect(matomoSpy).toHaveBeenCalledTimes(1);
done();
});
const httpReq = httpMock.expectOne('https://some-dummy-url');
httpReq.flush();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.