Skip to content

Instantly share code, notes, and snippets.

@dirkluijk
Created June 20, 2018 15:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dirkluijk/3a29f5abc7e57d7e6e3b5788f462625c to your computer and use it in GitHub Desktop.
Save dirkluijk/3a29f5abc7e57d7e6e3b5788f462625c to your computer and use it in GitHub Desktop.
Testing Angular interceptors with Spectator
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();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment