Reputation: 87
I struggeling to finish a unit test for my HttpInterceptor. The interceptor works as a global error handler and simply triggers on catchError(httpResponseError). The interceptor is working just fine on my site, but I can't get the unit test to actually test the code.
Here's the code 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);
}))
}
private handleHttpError(error: HttpErrorResponse): Observable<HttpServiceError> {
const requestError = new HttpServiceError();
console.log('Error:', error);
console.log('handleHttpError function called');
requestError.errorNumber = error.status;
requestError.statusMessage = error.statusText;
switch (error.status) {
case 401: {
requestError.friendlyMessage = 'You are not logged in';
break;
}
case 403: {
requestError.friendlyMessage = 'You are not logged in';
break;
}
case 404: {
requestError.friendlyMessage = 'The service failed to respond';
break;
}
case 429: {
requestError.friendlyMessage = 'The service is busy';
break;
}
case 500: {
requestError.friendlyMessage = 'The service is not responding correctly';
break;
}
default: {
requestError.friendlyMessage = 'An error occured retrieving the data';
break;
}
}
this.loggingService.logWithLevel(JSON.stringify(requestError), LogLevel.Information);
return throwError(requestError);
}
}
As you can see, I have a couple of console,logs's in there and only the first is trigger in test.
Here's 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.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpResponseInterceptorService,
multi: true,
},
]
});
loggingService = TestBed.inject(LoggingService);
interceptor = TestBed.inject(HttpResponseInterceptorService);
httpMock = TestBed.inject(HttpTestingController);
httpClient = TestBed.inject(HttpClient);
});
afterEach(() => {
httpMock.verify();
});
it('should be created', () => {
expect(interceptor).toBeTruthy();
});
it('should call loggingService with a friendlyMessage of The service failed to respond (404)', fakeAsync(() => {
spyOn(loggingService,'logWithLevel');
const errorResponse = new HttpErrorResponse({
error: '404 error',
status: 404, statusText: 'Not Found'
});
httpClient.get('/api').subscribe();
let request = httpMock.expectOne("/api");
request.error(new ErrorEvent('404 Error'), errorResponse);
// request.flush('Request failed', {status:404, statusText:'Not Found'});
// request.flush(errorResponse);
expect(loggingService.logWithLevel).toHaveBeenCalled();
}));
});
I've tried with both request.error(new ErrorEvent('404 Error'), errorResponse);
and // request.flush(errorResponse);
: None of the actually triggers the catchError((error:HttpErrorResponse)
code branch.
Good ideas and feedback are very welcomed!
Thanks, Bjarne
Upvotes: 2
Views: 3438
Reputation: 94
In my opinion your problem comes from 'retry(1)'.
You have to call numberOfRetry + 1
times your api if you want to pass in catchError
function.
Maybe you can try that :
let request = httpMock.expectOne("/api");
request.error(new ErrorEvent('404 Error first'), errorResponse);
request = httpMock.expectOne("/api");
request.error(new ErrorEvent('404 Error second'), errorResponse);
Upvotes: 3