Reputation: 2128
I have an Angular (6) HttpInterceptor like with this intercept method:
intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
if (this.translationService.currentLang) {
req = req.clone({
setHeaders: {
'Accept-Language': this.translationService.currentLang
}
});
}
return next.handle(req);
}
How can I get this to unit test with jasmine and check that the returned request contains the new header? I know I can get the parameter with
let next = jasmine.createSpyObj('httpHandler', ['handle']);
next.handle.calls.mostRecent();
But how can I validate that the header is set?
Upvotes: 1
Views: 3232
Reputation: 3247
Here is what I used to test some interceptor:
describe(`interceptor: yourinterceptor`, () => { // CHANGE HERE
let httpMock: HttpTestingController;
let injector: TestBed;
function createTestModule(providers: Provider[] = []) {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule, RouterTestingModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: YOUR_INTERCEPTOR, // CHANGE HERE
multi: true
},
...providers
]
});
injector = getTestBed();
httpMock = injector.get(HttpTestingController);
}
beforeEach(() => {
// empty
});
afterEach(() => {
httpMock.verify();
});
describe('request with headers', () => {
beforeEach(() => {
createTestModule();
});
it('should make the request with headers', inject([HttpClient], (http: HttpClient) => {
http.get('/dummy').subscribe();
const httpRequest: TestRequest = httpMock.expectOne('/dummy');
expect(httpRequest.request.headers.has("YOUR_HEADER")).toBeTruthy(); // CHANGE HERE
}));
});
});
Upvotes: 2