I am facing challenges in completing a unit test for my HttpInterceptor. The interceptor serves as a global error handler and is set to trigger on catchError(httpResponseError). While the interceptor functions perfectly fine on my website, I am struggling to create a successful unit test for the code.
Below is the code snippet for the Interceptor:
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { retry, tap, catchError } from 'rxjs/operators';
import { HttpServiceError } from '../models/httpServiceError.model';
import { LoggingService, LogLevel } from '../services/logging.service';
@Injectable({
providedIn: 'root'
})
export class HttpResponseInterceptorService implements HttpInterceptor{
public logLevel!: LogLevel;
constructor(private readonly loggingService: LoggingService) {
// Intentionally left blank
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
retry(1),
tap(() => console.log('ResponseInterceptor called')),
catchError((error:HttpErrorResponse) => {
console.log('HttpErrorResponse caught')
this.handleHttpError(error);
return throwError(error);
}))
}
// Additional code for handling errors and logging messages
In my testing environment, only the first `console.log` statement actually gets triggered instead of the expected behavior.
Furthermore, here's an excerpt from my spec file:
import { HttpClient, HttpErrorResponse, HttpEvent, HttpHandler, HttpRequest, HttpResponse, HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { fakeAsync, inject, TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { take } from 'rxjs/operators';
import { LoggingService } from '../services/logging.service';
import { HttpResponseInterceptorService } from './httpresponseinterceptor.service';
describe('HttpResponseInterceptorService', () => {
let interceptor: HttpResponseInterceptorService;
let httpMock: HttpTestingController;
let loggingService: LoggingService;
let httpClient: HttpClient;
beforeEach(() => {
// TestBed configuration and injection setup
});
afterEach(() => {
httpMock.verify();
});
// Detailed unit test cases with specific expectations
The tests involving triggering error responses have not been successful so far. All ideas and suggestions are greatly appreciated!
Thank you, Bjarne