Created
June 20, 2018 15:09
-
-
Save dirkluijk/3a29f5abc7e57d7e6e3b5788f462625c to your computer and use it in GitHub Desktop.
Testing Angular interceptors with Spectator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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