Sub topic 9
Answering requests with flush
This chapter assumes you can write a basic Angular service that uses HttpClient, and that you have already configured TestBed with provideHttpClient() and provideHttpClientTesting(). You should also have used HttpTestingController.expectOne to capture a pending request. Here you will learn how to answer that request.
What flush does
With the testing backend, a call such as http.get(...) produces a request that nobody answers. The Observable stays pending until your test responds. The TestRequest object returned by expectOne has a flush method for this. It hands a response to the code that subscribed.
flush is synchronous. By the time it returns, the next and complete callbacks (or the error callback) of the subscriber have already run. You can therefore assert on the next line, and a plain it callback needs no fakeAsync, done, or await.
The signature
flush(body, opts?: { headers?, status?, statusText? })bodyis the payload the server would send. It can be an object, array, string, number, boolean,null,Blob, orArrayBuffer.statusdefaults to200.statusTextdefaults to'OK'.headersis either a plain object such as{ 'X-Total-Count': '42' }or anHttpHeadersinstance.
The status code decides which channel the subscriber sees. A status from 200 to 299 produces an HttpResponse and a next notification. Any other status produces an HttpErrorResponse and an error notification. Error cases are covered in the next chapter. Here you will use the success side.
Flushing a body
The simplest case is the one you have already seen. The default HttpClient call returns only the body, so the subscriber receives exactly what you flush.
it('delivers the flushed body to the subscriber', () => {
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' });
});Angular does not validate the body against User. The generic parameter on http.get<User> is a compile-time promise, and flush accepts any shape. If your service maps or transforms the body, a test that flushes a differently shaped object will fail on the transformation. It will not fail on the type.
Setting status and headers
Some services read more than the body. If you call http.post with { observe: 'response' }, the subscriber receives the whole HttpResponse, so the status and headers matter. The next example is self-contained and uses HttpClient directly.
import { HttpClient, HttpResponse, provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
describe('flush options', () => {
let http: HttpClient;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
http = TestBed.inject(HttpClient);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTesting.verify();
});
it('exposes the status and headers of a created resource', () => {
let response: HttpResponse<{ id: number }> | undefined;
http
.post<{ id: number }>('/api/users', { name: 'Ada' }, { observe: 'response' })
.subscribe((r) => (response = r));
httpTesting.expectOne('/api/users').flush(
{ id: 3 },
{
status: 201,
statusText: 'Created',
headers: { Location: '/api/users/3' },
},
);
expect(response?.status).toBe(201);
expect(response?.headers.get('Location')).toBe('/api/users/3');
expect(response?.body).toEqual({ id: 3 });
});
});Note that 201 is still a success. It reaches next, not error.
Empty bodies
A DELETE often returns 204 No Content. Flush null and set the status explicitly. If you leave the status at its default, your test claims the server answered 200, which is a different contract.
it('completes when the server answers 204', () => {
let completed = false;
http.delete<void>('/api/users/1').subscribe({ complete: () => (completed = true) });
httpTesting
.expectOne({ method: 'DELETE', url: '/api/users/1' })
.flush(null, { status: 204, statusText: 'No Content' });
expect(completed).toBe(true);
});Matching the response type
HttpClient requests carry a responseType: json (the default), text, blob, or arraybuffer. The testing backend checks your flushed body against it.
| Request `responseType` | Body you can flush | What happens otherwise |
|---|---|---|
| `json` | Object, array, string, number, boolean, `null` | `Blob` and `ArrayBuffer` bodies throw |
| `text` | String | Objects, `Blob`, and `ArrayBuffer` throw |
| `blob` | `Blob` (strings and `ArrayBuffer` are converted) | Objects throw |
| `arraybuffer` | `ArrayBuffer` (strings are converted) | Objects throw |
When you see an error saying that automatic conversion to a response type is not supported, the cause is a body that does not fit the request. The usual mistake is flushing an object for a request made with responseType: 'text'. The fix is to flush a string. If your service parses JSON itself, the test should flush a JSON string.
Flushing several requests
A service sometimes sends several requests to one URL, for example one per item in a list. expectOne fails when more than one request matches, so it cannot be used here. Use match, which returns every matching request as an array and removes them from the pending list. You then flush each one.
it('answers every pending request', () => {
const results: number[] = [];
http.get<number>('/api/count').subscribe((n) => results.push(n));
http.get<number>('/api/count').subscribe((n) => results.push(n));
const requests = httpTesting.match('/api/count');
expect(requests.length).toBe(2);
requests[0].flush(10);
requests[1].flush(20);
expect(results).toEqual([10, 20]);
});Because each flush is synchronous, you can also flush the second request first to test that your code handles out-of-order responses.
Cancelled requests
If the subscriber unsubscribes before you flush, HttpClient cancels the request. The TestRequest records this in its cancelled property, and flush then throws. This helps you test code that abandons a request, such as a switchMap that replaces an in-flight search.
it('marks a request as cancelled after unsubscribe', () => {
const subscription = http.get('/api/slow').subscribe();
const req = httpTesting.expectOne('/api/slow');
subscription.unsubscribe();
expect(req.cancelled).toBe(true);
expect(() => req.flush({})).toThrow();
});A cancelled request still counts as handled once you have captured it with expectOne, so verify() does not complain about it.
Operators that wait
flush runs the subscriber synchronously, but operators in your service chain may not. debounceTime, delay, and timer schedule work on the clock. If your service pipes the response through one of them, the result will not arrive until time advances. Wrap the test in fakeAsync and call tick with the right number of milliseconds after the flush.
Common mistakes
- Forgetting to flush. The test passes if it asserts nothing about the result, and
verify()still passes because you captured the request. Always assert on the subscriber's outcome. - Flushing the wrong shape. The compiler cannot catch it. If the service reads
response.items, flush an object withitems. - Using the default status for an error.
flush('Not found')is a success with a string body. To simulate failure, set a non-2xxstatus. - Using
expectOnefor repeated URLs. Switch tomatchwhen several requests are expected. - Skipping
statusText. The default is'OK', so a404flushed withoutstatusTextcarries a misleading'OK'. Set both values when the text matters.
Exercise
A service method calls this.http.get<string>('/api/version', { responseType: 'text' as 'json' }) and exposes the result. Your test calls flush({ version: '1.2' }) and the test throws an error about unsupported conversion. What is wrong, and what should the test flush instead?
Show answer
The request was made with a text response type, so the testing backend only accepts a string body. Flushing an object cannot be converted to text. Flush a string such as '1.2'. In the test, assert that the subscriber receives '1.2'. If the service really needs structured data, change the service to request JSON instead of adjusting the test.
Exercise
You wrote httpTesting.expectOne('/api/users/1').flush('Not found'); and your error handler never ran. Why, and how do you fix the test?
Show answer
The default status is 200, so the response is a success with the string body 'Not found' and goes to next. To trigger the error handler, pass a non-2xx status: flush('Not found', { status: 404, statusText: 'Not Found' }).