My unit test for my HttpInterceptor is unfortunately not working and I have no idea how to solve this right now
Example => error.interceptor.ts
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError((response) => this.handleError(response)),
);
}
private handleError(response: HttpErrorResponse): Observable<HttpEvent<any>> {
if (response.status === 500 || response.status === 501) {
console.log('Error');
}
return throwError(() => response);
}
}
Unit-Test => error.interceptor.spec.ts
let errorInterceptor: ErrorInterceptor;
beforeEach(() => {
errorInterceptor = new ErrorInterceptor(
);
});
it.each([500, 501])('should ...', (statusCode) => {
const response = new HttpErrorResponse({ status: (statusCode) });
const request = new HttpRequest('GET', '/fakeUrl');
const mockHandler = { handle: jest.fn(() => throwError(() => response )) };
const result = errorInterceptor.intercept(request, mockHandler);
result.subscribe({
next: () => fail('error'),
error: (err) => expect(err).toBeTruthy(),
});
});
This test works. But if I change toBeTruthy to toBeFalsy the test works also :-(
Either the error is in result.subscribe or my beforeEach() is not correct.