Sub topic 3
Testing HTTP Calls
Assume you know TypeScript, standalone Angular components, dependency injection, and basic Vitest syntax. This chapter focuses on boundaries: HTTP, time, DOM abstractions, and test selection.
Testing HTTP calls
Use HttpTestingController to intercept requests without contacting a server. Configure both the real HTTP provider and its testing replacement:
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
const service = TestBed.inject(UserService);
const http = TestBed.inject(HttpTestingController);
let users: string[] | undefined;
service.list().subscribe((value) => (users = value));
const request = http.expectOne('/api/users');
expect(request.request.method).toBe('GET');
request.flush(['Ada', 'Grace']);
expect(users).toEqual(['Ada', 'Grace']);
http.verify();expectOne checks the request. flush supplies its response. verify catches requests that the test forgot to handle.
Async code and fake timers
For code using setTimeout, replace real time with Vitest’s fake timers:
vi.useFakeTimers();
component.onInput('angular');
vi.advanceTimersByTime(300);
expect(onSearched).toHaveBeenCalledWith('angular');
vi.useRealTimers();Restore real timers in afterEach, even when a test fails. For promises and observables, prefer their normal completion tools or Angular’s async testing utilities.
Using component harnesses
A component harness is a test API that hides DOM details behind actions such as setValue() or click(). Angular Material provides harnesses for its components. Use a harness when markup may change but the user-facing behavior should remain stable. Direct DOM queries are simpler for small local components.
What to test and what to leave out
Test behavior a user or dependent component can observe: rendered states, input changes, emitted outputs, service calls, errors, and loading transitions. Leave out private fields, framework internals, exact markup structure, and implementation-only helper calls. A test that survives a harmless template refactor is usually better.
Coverage and CI
Run coverage with the Angular CLI:
ng test --coverageIn continuous integration (CI), run the same command in a clean install and fail on test failures. Treat coverage as a signal for untested behavior, not as a target achieved by adding meaningless assertions.
Running tests in a real browser
Node-based tests are fast, but browser execution can reveal issues involving layout, browser APIs, or event behavior. Enable the browser mode supported by your Angular and Vitest setup, then run a small set of integration-focused tests there. Keep most unit tests in the faster default environment.
Exercise
Why should an HTTP test call http.verify() after flushing its expected request?
Show answer
It confirms that no unexpected or unhandled HTTP requests remain.