Sub topic 14
Common pitfalls and keeping tests maintainable
This chapter assumes you can write the tests from the earlier chapters: a TestBed setup with provideHttpClient() and provideHttpClientTesting(), expectOne, flush and verify. It covers the mistakes that make HTTP tests pass when they should fail, and how to structure the tests so they stay cheap to change.
Tests that pass for the wrong reason
The most damaging failure in a service test is a test that cannot fail. Three causes account for most of these.
Forgetting `verify`
HttpTestingController records every request the service makes. Without verify(), a request that nobody answered is never reported. Put the call in afterEach so that it runs for every test:
afterEach(() => {
httpTesting.verify();
});verify() throws if any request is still open, whether it was never matched or never flushed. It protects you in both directions. Code that sends a request you did not expect fails the test. A request you expected but never answered fails the test too.
Assertions inside `subscribe` that never run
An assertion inside a subscribe callback runs only if the Observable emits. If you forget to flush, the callback never fires and the test reports success:
it('looks like it checks the name', () => {
service.getUser(1).subscribe((user) => {
expect(user.name).toBe('Grace'); // never executes
});
httpTesting.expectOne('/api/users/1'); // no flush
});With verify() in afterEach, this test fails because the request is open. Without it, the test passes. The more robust pattern is to capture the value, flush, and then assert outside the callback:
it('returns the user from the response body', () => {
let result: User | undefined;
service.getUser(1).subscribe((user) => (result = user));
httpTesting.expectOne('/api/users/1').flush({ id: 1, name: 'Ada' });
expect(result).toEqual({ id: 1, name: 'Ada' });
});If result stays undefined, the toEqual assertion fails. The test cannot pass silently.
Forgetting to subscribe
HttpClient methods return cold Observables. Nothing is sent until someone subscribes. If you call service.getUser(1) and never subscribe, expectOne throws "Expected one matching request... found none". The error message points at the request, but the real mistake is in the call before it. When expectOne finds nothing, check that the code under test actually subscribed. A common case is an async pipe or toSignal that only exists in a component, and not in the service you are testing.
Matching problems
expectOne accepts a string, a { method, url } object, a HttpRequest, or a predicate function. A string matches against urlWithParams, so the query string is part of the match.
| Symptom | Cause | Fix |
|---|---|---|
| "Expected one matching request for criteria ... found none" | The URL string differs from `urlWithParams`, for example the query string is missing. | Include the query string, or use a predicate on `req.url`. |
| "Expected one matching request ... found 2" | The code sent two matching requests, for example a retry or a double subscribe. | Use `match()` to get an array, or fix the duplicate subscription. |
| "Cannot flush a request that was already completed" | You called `flush` or `error` twice on the same `TestRequest`. | Match a new request for each response. |
| "Cannot flush a cancelled request" | The code unsubscribed before you flushed, for example a `switchMap` that replaced it. | Assert on the cancellation with `req.cancelled`, or flush the later request. |
| `verify` reports a cancelled request | A request was cancelled and never answered. | Call `verify({ ignoreCancelled: true })` when cancellation is expected. |
When the exact URL does not matter, match on part of it with a predicate:
const req = httpTesting.expectOne(
(r) => r.method === 'GET' && r.url === '/api/users' && r.params.get('page') === '2',
);
req.flush([]);For tests that assert nothing is sent, use expectNone. This is useful for caching code: the second call should be served from memory.
httpTesting.expectNone('/api/users/1');Setup pitfalls
Provider order and interceptors
provideHttpClient(...) must come with provideHttpClientTesting() in the same provider list, and the testing provider replaces the real backend. Interceptors go inside provideHttpClient(withInterceptors([...])). Put your own interceptors there and not in provideHttpClientTesting. If requests reach the network or HttpTestingController sees nothing, check that both providers are present.
Configuring after injecting
TestBed.configureTestingModule must run before the first TestBed.inject. Once the injector exists, Angular throws "Cannot configure the test module when the test module has already been instantiated". This usually appears when a describe-level variable calls TestBed.inject at declaration time. Do all injection in beforeEach or inside the test.
State that leaks between tests
TestBed creates a fresh injector for each test, so a providedIn: 'root' service starts clean every time. State leaks only when you share something outside the injector: a module-level array used as a stub, a mutated constant of fixture data, or a global spy. Create stubs and fixtures inside beforeEach or inside a factory function, and never mutate shared constants.
Timers in retry logic
retry(2) has no delay, so the three-request test from the retry chapter runs synchronously. If production code uses retry({ delay: 1000 }) or timer, the second request is not sent until time passes. Wrap the test in fakeAsync and call tick(1000) before the next expectOne. Otherwise expectOne finds nothing and the test fails with a confusing message.
Over-mocking
It is tempting to replace HttpClient with a stub such as { get: () => of(user) }. That test passes whatever URL, parameters or headers the service sends. It checks only that your code handles a canned value. HttpTestingController sits one layer lower: your service and the real HttpClient, interceptors included, run unchanged, and only the network is replaced. Prefer it for anything that touches HTTP.
Use provider stubs for the other direction, dependencies that are not HTTP. A TokenStore or a Logger is a good candidate. The rule of thumb is to stub at the edge of the unit, and not inside it.
Also avoid asserting on private details. A test that checks service['cache'].size breaks when you rename the cache, even though behavior is unchanged. Assert on what a caller can observe: the emitted values, the requests sent, the errors surfaced.
Keeping tests maintainable
Tests that repeat TestBed configuration in every it become expensive when a constructor gains a dependency. Centralize the setup in a function:
import { TestBed } from '@angular/core/testing';
import { HttpErrorResponse, provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
TestRequest,
provideHttpClientTesting,
} from '@angular/common/http/testing';
function setup() {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
return {
service: TestBed.inject(UserService),
httpTesting: TestBed.inject(HttpTestingController),
};
}
function failWith(req: TestRequest, status: number): void {
req.flush('error', { status, statusText: 'Error' });
}
describe('UserService errors', () => {
afterEach(() => {
TestBed.inject(HttpTestingController).verify();
});
it('reports the status code of a failed request', () => {
const { service, httpTesting } = setup();
let error: HttpErrorResponse | undefined;
service.getUser(1).subscribe({ error: (e) => (error = e) });
failWith(httpTesting.expectOne('/api/users/1'), 503);
expect(error?.status).toBe(503);
});
});The setup function returns what each test needs, so tests do not share mutable variables. The failWith helper names the intent and hides the statusText boilerplate. afterEach reads the controller from TestBed itself, which works because the injector is the same one setup used.
Some habits keep a suite readable over time:
- Name tests after behavior, such as "returns an empty list when the server sends none", and not after methods, such as "listUsers works".
- Test one behavior per
it. A test that checks the request, the success path and the error path fails with a message that does not say which one broke. - Keep fixtures small and local. A
Userwith two fields is easier to read than a 40-line JSON file, and it fits theUserinterface the service already uses. - Assert on the request in one place and on the result in another. The request check says what the service sent. The result check says what it did with the answer.
- Delete tests that duplicate the framework. You do not need a test proving that
HttpClient.getissues aGET; test that your service asks for the right URL.
A debugging path for failing HTTP tests
Exercise
A test calls service.listUsers(1).subscribe(users => expect(users.length).toBe(3)), then httpTesting.expectOne('/api/users?page=1'), and never calls flush. The suite has no afterEach with verify(). The test passes. Explain why, and name two changes that would make it fail correctly.
Show answer
The assertion sits inside the subscribe callback, which runs only when the Observable emits. Because the request was never flushed, nothing is emitted and the assertion never executes. Without verify(), the open request goes unreported. Fix it by adding httpTesting.verify() in afterEach (which fails on the unanswered request) and by flushing the request, capturing the result in a variable, and asserting on that variable after the flush.
Exercise
A search service uses switchMap to cancel an earlier request when the user types again. Your test sends two searches, then flushes the first request, and gets "Cannot flush a cancelled request". What is happening, and how should the test be written?
Show answer
The second search unsubscribed from the first, which cancelled it, and a cancelled request cannot be flushed. Match both requests, assert that the first has cancelled set to true, and flush only the second one. If verify() also complains about the cancelled request, call verify({ ignoreCancelled: true }).