Sub topic 13
Testing functional interceptors
This chapter assumes you can write a functional HttpInterceptorFn, know how provideHttpClient works, and have used HttpTestingController to match and flush requests. Here you test an interceptor on its own, with no real backend.
What to test
An interceptor sits between the service and the HTTP backend. It receives a request, usually changes it, and passes it on with next. The behavior worth testing is the change it makes to the outgoing request. The service's own logic does not belong in this test.
A simple interceptor test therefore needs three parts:
- A
TestBedthat registers the interceptor. - A request made through
HttpClient. - An assertion on the request that reaches
HttpTestingController.
Where the interceptor sits
withInterceptors puts the interceptor in the HttpClient pipeline. provideHttpClientTesting replaces the real backend at the end of that pipeline. The testing controller therefore sees each request after the interceptor has changed it.
A first interceptor test
This interceptor clones the request and adds an Authorization header. Requests are immutable, so the interceptor must clone to change one.
import { HttpClient, HttpInterceptorFn, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
export const authInterceptor: HttpInterceptorFn = (req, next) =>
next(req.clone({ setHeaders: { Authorization: 'Bearer test-token' } }));
describe('authInterceptor', () => {
it('adds the Authorization header', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([authInterceptor])),
provideHttpClientTesting(),
],
});
const http = TestBed.inject(HttpClient);
const httpTesting = TestBed.inject(HttpTestingController);
http.get('/api/ping').subscribe();
const req = httpTesting.expectOne('/api/ping');
expect(req.request.headers.get('Authorization')).toBe('Bearer test-token');
req.flush({});
httpTesting.verify();
});
});The test never builds the interceptor by hand. It registers it and lets HttpClient run it, as the application does.
Reading the example
provideHttpClient(withInterceptors([authInterceptor]))registers the interceptor. Put it beforeprovideHttpClientTesting().http.get('/api/ping').subscribe()sends the request. The call needs asubscribe, because the request is cold and nothing is sent until someone subscribes.expectOnereturns aTestRequest. Itsrequestproperty is the request after the interceptor ran, so the header assertion checks the interceptor's output.flush({})answers the request.verify()then confirms that nothing else is pending.
Choosing between two approaches
You can test an interceptor in two ways.
| Approach | How it works | Use it when |
|---|---|---|
| Through `HttpClient` | Register with `withInterceptors`, then use `HttpTestingController` | You want the real pipeline, including interceptor order |
| Directly with `TestBed.runInInjectionContext` | Call the function with a fake request and a fake `next` | The interceptor calls `inject()` and you want to test it in isolation |
The first approach is the default. It also catches mistakes in how the interceptor is registered. Use the second approach only when the setup through HttpClient becomes more work than the interceptor deserves.
Interceptors that depend on a service
Many interceptors call inject() to read a token store. Stub that dependency with a provider, as you did in the stubbing chapter, and the interceptor will use the stub.
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpInterceptorFn, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
@Injectable({ providedIn: 'root' })
export class TokenStore {
token(): string {
return 'real-token';
}
}
export const tokenInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(TokenStore).token();
return next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
};
describe('tokenInterceptor', () => {
it('uses the token from the store', () => {
TestBed.configureTestingModule({
providers: [
{ provide: TokenStore, useValue: { token: () => 'stub-token' } },
provideHttpClient(withInterceptors([tokenInterceptor])),
provideHttpClientTesting(),
],
});
TestBed.inject(HttpClient).get('/api/ping').subscribe();
const httpTesting = TestBed.inject(HttpTestingController);
const req = httpTesting.expectOne('/api/ping');
expect(req.request.headers.get('Authorization')).toBe('Bearer stub-token');
req.flush({});
httpTesting.verify();
});
});Common mistakes
- Asserting on the request your code created instead of
req.requestfrom the controller. Only the second one includes the interceptor's changes. - Registering
provideHttpClientTesting()withoutprovideHttpClient(...), so the interceptor is never attached. - Skipping
verify(), which hides requests the interceptor sent that you did not expect.
Exercise
Write the assertions for an interceptor that adds the header X-App: demo to every request. Say which object you inspect and why you must not inspect the original request.
Show answer
Register the interceptor with provideHttpClient(withInterceptors([appInterceptor])) and provideHttpClientTesting(). Call http.get('/api/ping').subscribe(), then const req = httpTesting.expectOne('/api/ping') and expect(req.request.headers.get('X-App')).toBe('demo'). Inspect req.request, the request the testing backend received. The original request is immutable, and the interceptor sends a clone, so the original never has the header.