Sub topic 12
Testing an interceptor with HttpTestingController
This chapter assumes you can write a functional interceptor, register it with withInterceptors, and use TestBed with a basic Jasmine or Jest spec. It also assumes you know what inject() does inside an interceptor.
Why test through HttpClient
An interceptor is a function that runs inside the HttpClient pipeline. Calling it directly means building HttpRequest objects and a fake next yourself, and you would also have to supply an injection context. A simpler approach is to register the real interceptor, make a real HttpClient call, and let a fake backend capture the request.
HttpTestingController is that fake backend. It records every request that leaves the interceptor chain. Your test can then inspect each request and decide how to answer it.
The pieces
provideHttpClient(withInterceptors([...]))registers the interceptor under test.provideHttpClientTesting()replaces the real network layer with the testing backend. Put it afterprovideHttpClient.HttpTestingControlleris the handle you use to find pending requests.expectOne(url)returns aTestRequestand fails if there are zero or several matches.flush(body)completes the request with a response.verify()fails if any request was left unanswered or unexpected.
A first test
This test checks that the authorization interceptor adds the header. It stubs AuthService so no real token logic runs.
import { TestBed } from '@angular/core/testing';
import { HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { authInterceptor } from './auth.interceptor';
import { AuthService } from './auth.service';
describe('authInterceptor', () => {
it('adds the Authorization header', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([authInterceptor])),
provideHttpClientTesting(),
{ provide: AuthService, useValue: { getToken: () => 'abc' } },
],
});
const http = TestBed.inject(HttpClient);
const controller = TestBed.inject(HttpTestingController);
http.get('/api/data').subscribe();
const req = controller.expectOne('/api/data');
expect(req.request.headers.get('Authorization')).toBe('Bearer abc');
req.flush({});
controller.verify();
});
});The steps are:
- Configure
TestBedwith the interceptor, the testing backend, and a stub for the injected service. - Call
http.get(...).subscribe(). Nothing is sent until you subscribe. - Use
expectOneto get the request as it looks after the interceptor ran. - Assert on
req.request, which is the cloned request with the new header. - Call
flushto complete the request, thenverifyto confirm nothing else is pending.
Because the stub is provided in TestBed, inject(AuthService) inside the interceptor resolves to it. You do not need runInInjectionContext when you test through HttpClient.
Testing the other branches
One test per behavior is enough. For the auth interceptor, add a second spec where getToken returns null. Then assert that req.request.headers.has('Authorization') is false. Without it, a change that always sends Bearer null would pass.
You can also test responses and errors. Use req.flush('Denied', { status: 401, statusText: 'Unauthorized' }) to simulate a server error. Use req.error(new ProgressEvent('error')) to simulate a network failure, which produces an HttpErrorResponse with status 0. Then check what the subscriber's error callback receives.
Common mistakes
- Forgetting
subscribe(). The request is never issued, soexpectOnethrows. - Listing
provideHttpClientTesting()withoutprovideHttpClient(...). The interceptor then never runs. - Asserting on the URL passed to
http.getinstead of onreq.request. Only the second shows what the interceptor changed.
Exercise
You wrote an interceptor that adds an X-App-Version header to every request. Your test calls http.get('/api/items').subscribe(), then controller.expectOne('/api/items'), and checks the header on req.request. The test passes, but later the interceptor is changed to send a second request to /api/log. Which call in the test would have caught this, and why?
Show answer
controller.verify(). It fails if any request was made that the test did not match with expectOne or similar. Here the extra /api/log request stays unmatched, so verify() reports it.