Sub topic 9
Answering requests with flush
This chapter assumes you can write a basic Angular service with HttpClient, that you know how to subscribe to an Observable, and that your TestBed already uses provideHttpClient() and provideHttpClientTesting(). Here you will learn how flush supplies the response that your service is waiting for.
Why a request waits
With provideHttpClientTesting(), no request reaches the network. When your service subscribes, the request goes to HttpTestingController and stays pending. The subscriber receives nothing until the test answers the request. expectOne finds the pending request. The flush method on the returned TestRequest then completes it.
A successful response
Subscribe first, because the request is sent only on subscription. Then match the request and flush a body.
it('returns the body passed to flush', () => {
let result: User | undefined;
let completed = false;
service.getUser(1).subscribe({
next: (user) => (result = user),
complete: () => (completed = true),
});
httpTesting.expectOne('/api/users/1').flush({ id: 1, name: 'Ada' });
expect(result).toEqual({ id: 1, name: 'Ada' });
expect(completed).toBeTrue();
});The body is delivered synchronously. A plain it callback needs no async, fakeAsync or done. After the flush, the Observable completes, which the completed flag confirms.
What flush accepts
The first argument is the body. It can be an object, an array, a string, a Blob, an ArrayBuffer or null. The optional second argument sets the status, the status text and the headers.
| Call | Result |
|---|---|
| `flush({ id: 1, name: 'Ada' })` | Status 200, body delivered to `next` |
| `flush([])` | Status 200 with an empty array |
| `flush(null)` | Status 200 with no body |
| `flush('Not found', { status: 404, statusText: 'Not Found' })` | `HttpErrorResponse` delivered to `error` |
| `flush(body, { headers: { 'X-Total': '42' } })` | Status 200 with a response header |
The default status is 200. Any status outside 200 to 299 makes the Observable error, as it would with a real server.
it('turns a non-2xx flush into an error', () => {
let status: number | undefined;
service.getUser(99).subscribe({
error: (e: HttpErrorResponse) => (status = e.status),
});
httpTesting
.expectOne('/api/users/99')
.flush('Not found', { status: 404, statusText: 'Not Found' });
expect(status).toBe(404);
});Flushing in sequence
Each retry sends a new request, so you flush each one separately. In the retry test from the plan, expectOne is called three times and the final call supplies the good body. Answer requests in the order your code sends them.
Flushing with promises
If your test uses await, convert the Observable first and flush before you await.
it('works with promises through firstValueFrom', async () => {
const promise = firstValueFrom(service.getUser(1));
httpTesting.expectOne('/api/users/1').flush({ id: 1, name: 'Ada' });
expect(await promise).toEqual({ id: 1, name: 'Ada' });
});Awaiting before the flush hangs the test, because nothing ever answers the request.
Common mistakes
- Calling
expectOnebeforesubscribe. No request exists yet, so the match fails. - Flushing a body of the wrong shape. TypeScript does not check it, so the assertion on the result is what catches the mistake.
- Forgetting
verify()inafterEach. An unanswered request then passes silently. - Expecting a 404 to arrive in
next. It arrives inerror.
Exercise
A test subscribes to service.listUsers(1), calls httpTesting.expectOne('/api/users?page=1').flush([], { status: 500, statusText: 'Server Error' }), and then asserts that the next callback received []. Why does the assertion fail, and how would you fix the test?
Show answer
A flush with status 500 produces an HttpErrorResponse, so the Observable calls error and never calls next. To fix it, either flush with the default 200 status to test the success path, or pass an error callback and assert on e.status to test the failure path.