我有以下http错误拦截器:
output .= '<option '.($row->id==$fetch_state_db ?'selected="selected"':''' ).' value="'.$row->id.'">'.$row->region.'</option>';
}
我的单元测试如下:
@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);
});
});
我正在https://medium.com/@dev.s4522/how-to-write-unit-test-cases-for-angular-http-interceptor-7595cb3a8843的帮助下编写此单元测试。您能否帮忙为什么未调用matomoSpy或我们如何测试此拦截器?
答案 0 :(得分:0)
您必须像这样刷新请求:
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();
});