Sub topic 11
Catching stray requests with verify
This chapter assumes you can write a basic Angular unit test, you know how HttpClient returns cold Observables, and you have set up provideHttpClient() and provideHttpClientTesting() as shown in the earlier chapters. You should also know how expectOne and flush work.
Why a passing test can still be wrong
HttpTestingController records every request your code makes. It does not complain when a request is never answered, and it does not complain when your code sends a request you did not expect. Consider this test:
it('loads a user', () => {
service.getUser(1).subscribe();
// No expectOne, no flush, no assertions.
});This test passes. The request was recorded, nobody looked at it, and Jasmine saw no failed expectation. A test like this proves nothing about the service.
verify() closes that gap. It checks that every recorded request was matched by an expectOne, match or expectNone call, and it also checks that none of them was cancelled or left open. If any request is left over, verify() throws an error that lists the unmatched requests.
What verify checks
verify() fails when there is at least one request that your test never matched. This covers two situations:
- A request your test did not expect. The service sent a request to a URL or with a method you never passed to
expectOneormatch. - A request your test matched but never answered. In Angular's current implementation, a request taken by
expectOneis removed from the list of open requests at the moment it is matched. So an unanswered but matched request does not triggerverify()by itself. See the callout below.
By default verify() ignores requests that were cancelled, for example because the subscriber unsubscribed. You can pass { ignoreCancelled: true } to say so explicitly. Without that option, a cancelled request that was never matched is still reported.
The standard pattern: verify in afterEach
Put the call in afterEach so every test in the file is checked without extra effort:
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
describe('UserService', () => {
let service: UserService;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
service = TestBed.inject(UserService);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTesting.verify();
});
it('requests a user by id and returns the response body', () => {
let result: User | undefined;
service.getUser(1).subscribe((user) => (result = user));
const req = httpTesting.expectOne('/api/users/1');
expect(req.request.method).toBe('GET');
req.flush({ id: 1, name: 'Ada' });
expect(result).toEqual({ id: 1, name: 'Ada' });
});
});Because afterEach runs after each test body, a failure from verify() is reported against the test that caused it. The error message names the outstanding request, for example Expected no open requests, found 1: GET /api/users/2.
A stray request in practice
Suppose someone changes getUser to also prefetch the user's profile:
getUser(id: number): Observable<User> {
this.http.get(`/api/users/${id}/profile`).subscribe();
return this.http.get<User>(`/api/users/${id}`);
}The existing test still calls expectOne('/api/users/1'), flushes it, and checks the result. Every assertion passes. Without verify(), the extra call to /api/users/1/profile goes unnoticed. With verify(), the test fails with a message about one open request to the profile URL. You then decide: either the extra call is a bug, or it is intended and the test needs to match it.
Stray requests are not only about extra calls
Stray requests also come from timing. Observables returned by HttpClient are cold, which means the request is sent only on subscribe. If your test forgets to subscribe, no request exists, and expectOne fails with "Expected one matching request... found none". That failure is the opposite of a stray request but has the same cause: the test and the code disagree about what is sent.
A different case is asynchronous code that sends a request after your test finished. If a service sends a request inside a setTimeout, a debounceTime pipeline or a resolved Promise, the request may arrive after verify() has already run. The test then passes while the request is silently dropped or, worse, leaks into the next test. Use fakeAsync with tick(), or await the promise, before you call expectOne.
import { fakeAsync, tick } from '@angular/core/testing';
it('sends the search request after the debounce', fakeAsync(() => {
service.search('ang').subscribe();
httpTesting.expectNone('/api/search?q=ang');
tick(300);
httpTesting.expectOne('/api/search?q=ang').flush([]);
}));This example assumes a search method that debounces by 300 ms before calling HttpClient. The expectNone call proves that nothing was sent early, and tick(300) moves the fake clock forward so the delayed request is issued.
Matching more than one request
When a method legitimately sends several requests, expectOne throws if more than one matches. Use match to get every matching request as an array. match also removes the matched requests from the open list, so verify() will not report them.
it('loads two pages and merges the result', () => {
let count = 0;
service.loadPages([1, 2]).subscribe((users) => (count = users.length));
const requests = httpTesting.match((req) => req.url === '/api/users');
expect(requests.length).toBe(2);
requests[0].flush([{ id: 1, name: 'Ada' }]);
requests[1].flush([{ id: 2, name: 'Grace' }]);
expect(count).toBe(2);
});Here loadPages is an assumed method that issues one request per page. If you wrote expect(requests.length).toBe(2) and the service sent three, the assertion fails first. Checking the length of match results is how you assert an exact number of calls.
Asserting that nothing was sent
expectNone checks that no request matches a URL, a method-and-URL object or a predicate function. It is the right tool when a guard clause should prevent a call, for example when a cache already holds the value.
it('does not call the server when the user is cached', () => {
service.getCachedUser(1).subscribe();
service.getCachedUser(1).subscribe();
httpTesting.expectOne('/api/users/1').flush({ id: 1, name: 'Ada' });
httpTesting.expectNone('/api/users/1');
});getCachedUser is again an assumed method. The first expectOne takes the single request, and expectNone confirms that the second call did not produce another one. Later in the test, afterEach runs verify() as a final guard.
Calling verify inside a test
You are not limited to afterEach. Calling verify() in the middle of a test is useful when you want to check a stage of a longer scenario:
it('sends nothing until the user clicks save', () => {
service.draft({ id: 1, name: 'Ada' });
httpTesting.verify();
service.save().subscribe();
httpTesting.expectOne({ method: 'PUT', url: '/api/users/1' }).flush({});
});Here the first verify() fails if draft sent anything. Note that draft and save are assumed methods for this example. Use mid-test checks sparingly. A long test with several stages is often easier to read when split into separate tests.
When verify reports a failure
Read the error message first. It lists each open request with its method and URL, which usually tells you which line of production code issued it. Then decide which of these cases applies:
| Symptom | Likely cause | Fix |
|---|---|---|
| Extra request listed that you never expected | The service or an interceptor sends an additional call | Match it with `expectOne` or `match`, or remove the call if it is a bug |
| Request listed that you thought you handled | The URL or method in `expectOne` differs, such as a query string or trailing slash | Compare the string exactly, or use the object form with `method` and `url` |
| `verify()` passes but the result is wrong | You never flushed the matched request | Call `flush` and assert on the subscription result |
| Request from the previous test appears | A test left an asynchronous task running | Flush timers with `tick`, `flush` or `await` before the test ends |
Keeping verify useful
- Keep
verify()inafterEachfor every spec file that injectsHttpTestingController. A file without it silently accepts stray requests. - Prefer
expectOnewith an object, such as{ method: 'GET', url: '/api/users' }, over a bare URL string. A bare string matches any method, so aPOSTto the same URL would be taken by a test written for aGET. - Do not catch and ignore errors thrown by
verify(). A failure is evidence of a real mismatch between the test and the code. - When a dependency such as an interceptor legitimately issues background calls, handle them in a shared helper instead of loosening
verify(). For example, a helper function can callhttpTesting.match('/api/telemetry')and flush the results.
Summary of the tools
| Method | What it does | Typical use |
|---|---|---|
| `expectOne(matcher)` | Returns the single matching request, throws on zero or several | Normal success and error tests |
| `match(matcher)` | Returns every matching request as an array, possibly empty | Methods that send several requests |
| `expectNone(matcher)` | Throws if any request matches | Proving that a call was skipped |
| `verify()` | Throws if any request was never matched | Final check in `afterEach` |
Exercise
A test subscribes to service.getUser(1), calls httpTesting.expectOne('/api/users/1'), and asserts req.request.method is 'GET', but never calls flush. The spec file has httpTesting.verify() in afterEach. Does the test pass, and what should you add so the test proves the service returns data?
Show answer
The test passes, because expectOne removed the request from the open list and verify() only reports requests that were never matched. To prove the service returns data, call req.flush({ id: 1, name: 'Ada' }) and assert on the value received in the subscribe callback.
Exercise
A method refresh() sends GET /api/items and, as a side effect, POST /api/audit. A test uses expectOne('/api/items') and flushes it. With verify() in afterEach, what happens, and how can you change the test to cover both calls?
Show answer
The test fails in afterEach because the POST /api/audit request is still open. Add httpTesting.expectOne({ method: 'POST', url: '/api/audit' }).flush({}) to match and answer the second call, or remove the audit call if it should not exist.