Sub topic 14
Common pitfalls and keeping tests maintainable
This chapter assumes you can write a basic service test with TestBed, provideHttpClientTesting and HttpTestingController. It covers the mistakes that most often make HTTP tests pass when they shouldn't, fail for confusing reasons, or become costly to maintain.
Pitfalls that hide failures
Assertions that never run
An assertion inside a subscribe callback only runs if the callback is called. If you forget to flush a response, the callback never fires and the test passes without checking anything.
it('looks fine but checks nothing', () => {
service.getUser(1).subscribe((user) => expect(user.name).toBe('Ada'));
// No flush: the callback never runs.
});Capture the result in a variable and assert after the flush call, as in the earlier examples. Also keep httpTesting.verify() in afterEach. It fails the test above because the request was never answered.
Forgetting to subscribe
HttpClient returns a cold Observable, which sends nothing until someone subscribes. If you call service.getUser(1) and then expectOne, the test fails with "Expected one matching request... found none". The service is not broken. Subscribe first, or convert with firstValueFrom as shown earlier.
Matching the wrong URL
expectOne('/api/users') compares against the full URL with query string. A request to /api/users?page=2 does not match. Use expectOne({ method: 'GET', url: '/api/users?page=2' }), or match on a predicate function when only part of the URL matters.
Pitfalls in setup
- Provider order. Put
provideHttpClient()beforeprovideHttpClientTesting(). If the order is reversed, the real backend can replace the testing backend. - Leaking state between tests. Configure
TestBedinbeforeEach, not at the top of thedescribeblock.TestBedresets between tests, and a service you inject once at file level keeps pointing at a stale injector. - Several matching requests.
expectOnethrows if two requests match. This is useful, because it exposes duplicate calls. With retries, callexpectOneonce per attempt, in order.
Keeping tests maintainable
Test behavior, not wiring
Avoid replacing HttpClient with a hand-written spy that returns of(...). Such a test would pass even if your service used the wrong method or URL. HttpTestingController keeps the real HttpClient code path, including interceptors, and lets you assert on the request itself.
Stub your own services with useValue providers, as in the TokenStore example. Leave Angular's HttpClient alone.
Share setup, not state
Put repeated configuration in a small helper that returns fresh objects each time it is called.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { UserService } from './user.service';
function setup() {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
return {
service: TestBed.inject(UserService),
httpTesting: TestBed.inject(HttpTestingController),
};
}
describe('UserService', () => {
afterEach(() => TestBed.inject(HttpTestingController).verify());
it('requests a user by id', () => {
const { service, httpTesting } = setup();
let name: string | undefined;
service.getUser(1).subscribe((user) => (name = user.name));
httpTesting.expectOne('/api/users/1').flush({ id: 1, name: 'Ada' });
expect(name).toBe('Ada');
});
});The helper keeps each test independent and avoids let variables shared across the whole file.
Keep each test small
Each test should cover one behavior: one success, one error status, one retry count. A test named "retries and then reports the error" is easier to diagnose than one that checks five things. Do not assert on private fields or on how many times an internal method ran. Those assertions break whenever you refactor, even when behavior is unchanged.
Avoid timers and real waits
Do not use setTimeout or real delays to wait for a response. flush is synchronous, so the result is available on the next line. If a service uses retry with a delay, control time with fakeAsync and tick instead of waiting.
Exercise
A test calls service.listUsers(2) and then httpTesting.expectOne('/api/users'). The test fails with "Expected one matching request for criteria... found none". Give two possible causes and a fix for each.
Show answer
First, the request URL includes the query string, so the actual URL is /api/users?page=2 and does not match the string. Fix it with expectOne({ method: 'GET', url: '/api/users?page=2' }). Second, nothing subscribed to the Observable, so no request was sent. Fix it by calling .subscribe() on service.listUsers(2) before expectOne.