Mocking HTTP responses with interceptors

Last updated 6 months ago
import { HttpErrorResponse, HttpRequest, HttpResponse } from '@angular/common/http';
import { Router } from '@angular/router';
import { createService, createSpyObject } from '@netbasal/spectator';
import { of, throwError } from 'rxjs';
import { RedirectInterceptor } from './redirect-interceptor.service';
import anything = jasmine.anything;
describe('RedirectInterceptorService', () => {
const spectator = createService({
service: RedirectInterceptor,
mocks: [Router]
});
const dummyRequest = createSpyObject(HttpRequest);
const interceptWithError = (error: Error) => {
spectator.service.intercept(dummyRequest, {
handle: () => throwError(error)
}).subscribe(
() => fail('Should fail'),
e => expect(e).toBe(error)
);
};
const interceptWithResponse = (response: HttpResponse<any>) => {
spectator.service.intercept(dummyRequest, {
handle: () => of(response)
}).subscribe();
};
it('should redirect when unauthorized or forbidden', () => {
[401, 403].forEach(status => {
interceptWithError(new HttpErrorResponse({ status }));
expect(spectator.get<Router>(Router).navigate).toHaveBeenCalledWith(['unauthorized'], anything());
});
});
it('should not redirect for other HTTP errors', () => {
[500].forEach(status => {
interceptWithError(new HttpErrorResponse({ status }));
expect(spectator.get<Router>(Router).navigate).not.toHaveBeenCalled();
});
});
it('should not redirect when OK', () => {
[200].forEach(status => {
interceptWithResponse(new HttpResponse<any>({ status }));
expect(spectator.get<Router>(Router).navigate).not.toHaveBeenCalled();
});
});
it('should not redirect for other error', () => {
interceptWithError(new Error('some error'));
expect(spectator.get<Router>(Router).navigate).not.toHaveBeenCalled();
});
});

Credit: Dirk Luijk.