Sub topic 8
Checking what your service sent
This chapter assumes you can write a basic Angular service with HttpClient, and that you have the provideHttpClient() and provideHttpClientTesting() setup from the previous chapters. You should also know what HttpTestingController.expectOne does at a basic level. Here you will use the captured request to check everything your service put on the wire.
Why assert on the request
A service that calls HttpClient has two outputs: the Observable it returns, and the request it sends. A bug in the request often stays hidden when you only check the result. If the service sends GET /api/user/1 instead of /api/users/1, a test that flushes a canned response for any request still passes. The real server would answer 404.
With HttpTestingController, the request is data you can inspect. You check these parts:
- The HTTP method.
- The URL, including the query string.
- The query parameters.
- The headers.
- The body.
What `expectOne` gives you
expectOne returns a TestRequest. It has two parts you will use:
req.requestis theHttpRequestyour service built. It holdsmethod,url,urlWithParams,params,headers,body,responseTypeandwithCredentials.req.flush(...)andreq.error(...)answer the request, as covered in the next chapters.
The request is recorded only after the service subscribes to the Observable. HttpClient Observables are cold. If your test calls service.getUser(1) and never subscribes, nothing is sent, and expectOne fails with "Expected one matching request" and zero found.
A service to test
The UserService from the earlier chapters only reads data. To cover headers and bodies, this chapter adds a second service.
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
export interface User {
id: number;
name: string;
}
@Injectable({ providedIn: 'root' })
export class UserWriter {
private readonly http = inject(HttpClient);
createUser(name: string): Observable<User> {
return this.http.post<User>(
'/api/users',
{ name },
{ headers: { 'X-Client': 'web' } },
);
}
searchUsers(term: string, limit: number): Observable<User[]> {
return this.http.get<User[]>('/api/users/search', {
params: { q: term, limit },
});
}
}Test setup
The setup is the one from the earlier chapter, with afterEach calling verify().
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
describe('UserWriter', () => {
let service: UserWriter;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
service = TestBed.inject(UserWriter);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTesting.verify();
});
// tests from the sections below go here
});Matching by URL
The simplest form of expectOne takes a string. The string is compared with the request's urlWithParams, which is the URL plus the query string. It is not compared with url. This matters when your service uses the params option:
it('matches the full URL including the query string', () => {
service.searchUsers('ada', 5).subscribe();
// 'url' would be '/api/users/search'; urlWithParams adds the query string
const req = httpTesting.expectOne('/api/users/search?q=ada&limit=5');
expect(req.request.url).toBe('/api/users/search');
req.flush([]);
});This works but ties the test to parameter order. If someone reorders the keys in the service, the string no longer matches, even though the request means the same thing. The next section shows how to avoid that.
Matching by method and URL
Passing an object matches on method and full URL together. Use it when the same URL is used with different verbs.
it('sends a POST to /api/users', () => {
service.createUser('Ada').subscribe();
const req = httpTesting.expectOne({ method: 'POST', url: '/api/users' });
expect(req.request.method).toBe('POST');
req.flush({ id: 1, name: 'Ada' });
});The expect on req.request.method repeats what expectOne already checked. It is harmless, and it makes the intent visible to the reader. If you leave it out, the test still fails when the method is wrong, because expectOne finds no match.
Checking the body and headers
After expectOne returns, read the request directly. The body is the object you passed to post. It has not been serialized to JSON, so compare it with toEqual.
it('posts the name in the body with the client header', () => {
service.createUser('Ada').subscribe();
const req = httpTesting.expectOne({ method: 'POST', url: '/api/users' });
expect(req.request.body).toEqual({ name: 'Ada' });
expect(req.request.headers.get('X-Client')).toBe('web');
expect(req.request.headers.has('Authorization')).toBe(false);
req.flush({ id: 1, name: 'Ada' });
});headers.get returns null when the header is absent. Header names are case-insensitive, so get('x-client') also works.
Checking query parameters without depending on order
req.request.params is an HttpParams object. Reading from it is more stable than comparing a URL string.
it('sends the search term and limit as query parameters', () => {
service.searchUsers('ada', 5).subscribe();
const req = httpTesting.expectOne(
(r) => r.method === 'GET' && r.url === '/api/users/search',
);
expect(req.request.params.get('q')).toBe('ada');
expect(req.request.params.get('limit')).toBe('5');
req.flush([]);
});Two details here:
- The matcher is a function. It receives the
HttpRequestand returns a boolean. Because it comparesr.url, which has no query string, the test does not care about parameter order. params.getreturns strings. The number5that the service passed becomes'5'.
The matching methods
| Method | What it does | When it fails |
|---|---|---|
| `expectOne(match)` | Returns the single matching pending request and marks it handled | Zero matches, or more than one |
| `match(match)` | Returns an array of all matching requests, possibly empty, and marks them handled | Never fails by itself |
| `expectNone(match)` | Asserts that no request matches | At least one match |
| `verify()` | Asserts that no pending request remains unhandled | Any unhandled request |
The match argument accepts a URL string, a { method, url } object, or a predicate function. Use match when the count is itself the thing under test. For example, a service that must send one request per item:
it('sends one search per term', () => {
service.searchUsers('a', 1).subscribe();
service.searchUsers('b', 1).subscribe();
const reqs = httpTesting.match((r) => r.url === '/api/users/search');
expect(reqs.length).toBe(2);
reqs.forEach((r) => r.flush([]));
});Requests returned by match are removed from the pending list, but you still need to answer them with flush or the service's Observable never emits.
Confirming that nothing was sent
expectNone is useful for caching or guard logic. For example, a service might skip the request when the search term is empty.
it('does not call the server for an empty term', () => {
// Suppose a guarded service skips empty terms; here we assert on a path
// that should never be hit.
httpTesting.expectNone('/api/users/search?q=&limit=5');
});Run expectNone after the code under test has run and subscribed. Before that, it passes for any request, because nothing has been sent yet.
Common mistakes
- Forgetting to subscribe. No subscription means no request, and
expectOnefails. - Matching a string against
urlmentally. A string URL is compared withurlWithParams. If the service usesparams, include the query string or use a predicate. - Asserting on the serialized body. The body is the original JavaScript object (or
FormData,Blob, and so on), not a JSON string. - Asserting only after
flush. It still works, sincereq.requeststays available. But assert first, then flush, so a failure points at the request and not at what the service did with the response. - Over-specifying. Do not check headers or parameters that the test is not about. A test that pins every detail breaks on harmless changes.
Exercise
A service calls this.http.get('/api/items', { params: { sort: 'name', page: 1 } }). Your test uses httpTesting.expectOne('/api/items') and fails with "Expected one matching request for criteria ... found none". Why, and what are two ways to fix the test?
Show answer
A string argument is compared with urlWithParams, which here is /api/items?sort=name&page=1, so /api/items matches nothing. Fix 1: pass the full URL string, '/api/items?sort=name&page=1', which depends on parameter order. Fix 2: use a predicate such as expectOne((r) => r.url === '/api/items') and then check req.request.params.get('sort') and req.request.params.get('page') (the values are the strings 'name' and '1').
Exercise
Write the assertions for a deleteUser(id) method that should send DELETE /api/users/7 with no body and no Authorization header. Which TestRequest properties do you read?
Show answer
Use const req = httpTesting.expectOne({ method: 'DELETE', url: '/api/users/7' });, then expect(req.request.body).toBeNull(); and expect(req.request.headers.has('Authorization')).toBe(false);, then req.flush(null);. The properties read are request.body and request.headers. The method and URL are already checked by the expectOne match.