I've written an Angular 9 HTTP Interceptor, and I would like to unit test the intercept function in relative isolation. From what I've seen on StackOverflow already, people are suggesting to make fake HTTP requests or return a basic request, which isn't working for me as I use the .pipe method (TypeError: next.handle(...).pipe is not a function)
Here's my intercept function, what would you suggest to unit test this function please?
intercept(request: HttpRequest < unknown >, next: HttpHandler): Observable < HttpEvent < unknown >> {
this.loadingService.show();
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status !== 401) {
this.snackBar.open("There was an error when making your request! " + error.message, 'Okay, I will refresh the page', { duration: 10000 });
}
return throwError(error);
}),
finalize(
() => {
this.loadingService.hide()
}
)
);
}
I was able to solve my issue by adding the following in the providers section of
TestBed.configureTestingModule
By providing the HTTP_INTERCEPTORS
the HttpClientTestingModule
will use the interceptor I have made:
{
provide: HTTP_INTERCEPTORS,
useClass: LoadingInterceptor,
multi: true
},