Sub topic 8
Checking what your service sent
This chapter assumes you can already configure TestBed with provideHttpClient() and provideHttpClientTesting(), and that you know how HttpTestingController captures requests. Here you will check the contents of each captured request: its method, URL, query parameters, headers and body.
Why assert on the request
A service test usually has two halves. One half checks what the service does with a response. The other half checks what it sent. If getUser calls the wrong URL or listUsers forgets the page parameter, the real server would reject the call or return the wrong data. A fake response would hide that bug, so the test has to inspect the request itself.
expectOne returns a TestRequest. Its request property is the actual HttpRequest object, and you read from it.
| What to check | Where to read it |
|---|---|
| HTTP method | `req.request.method` |
| URL with query string | the argument to `expectOne`, or `req.request.urlWithParams` |
| Query parameters | `req.request.params.get('name')` |
| Headers | `req.request.headers.get('Name')` |
| Body | `req.request.body` |
Matching by method and URL
A string argument matches the full URL, including the query string. An object argument also lets you require a method:
it('sends the page number as a query parameter', () => {
service.listUsers(2).subscribe();
const req = httpTesting.expectOne({ method: 'GET', url: '/api/users?page=2' });
expect(req.request.params.get('page')).toBe('2');
req.flush([]);
});expectOne throws if zero requests match or if more than one does. That makes the match itself an assertion. Because the URL must match exactly, the test above already proves that page=2 was sent. The params.get line checks the same thing in a form that is easier to read.
Checking headers and body
Requests that send data need more checks. The next example tests a PUT with a JSON body and a custom header. It defines a small service so that it runs on its own:
import { HttpClient, provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { Injectable, inject } from '@angular/core';
import { TestBed } from '@angular/core/testing';
@Injectable({ providedIn: 'root' })
class UserApi {
private readonly http = inject(HttpClient);
rename(id: number, name: string) {
return this.http.put(
`/api/users/${id}`,
{ name },
{ headers: { 'X-Source': 'web' } },
);
}
}
describe('UserApi.rename', () => {
it('sends a PUT with the new name and a custom header', () => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
const api = TestBed.inject(UserApi);
const httpTesting = TestBed.inject(HttpTestingController);
api.rename(7, 'Grace').subscribe();
const req = httpTesting.expectOne('/api/users/7');
expect(req.request.method).toBe('PUT');
expect(req.request.body).toEqual({ name: 'Grace' });
expect(req.request.headers.get('X-Source')).toBe('web');
req.flush({});
httpTesting.verify();
});
});Use toEqual for bodies. It compares by value, so it passes when the service builds a new but equal object. toBe would compare references and fail.
Matching with a function
Sometimes the exact URL is not what you care about. For example, the query string may contain several parameters in an order you don't want to test. In that case expectOne also accepts a predicate:
const req = httpTesting.expectOne(
(r) => r.method === 'GET' && r.url === '/api/users' && r.params.get('page') === '2',
);In this form r.url has no query string, because the parameters are in r.params. Prefer the string or object form when it is enough. The predicate form says less about what failed when it doesn't match.
Keep the checks focused
Assert on the parts of the request that your service is responsible for. Don't copy every header the browser adds, and don't assert on values that the code under test never sets. A test that restates the whole request breaks on harmless changes, and then people stop trusting it.
Exercise
A test calls service.listUsers(3).subscribe() and then httpTesting.expectOne('/api/users'). The test fails with "Expected one matching request for criteria ... found none" even though the service sends the request. Why, and how do you fix it?
Show answer
A string passed to expectOne is matched against the full URL including the query string, so the real URL /api/users?page=3 doesn't match /api/users. Use expectOne('/api/users?page=3'), or expectOne({ method: 'GET', url: '/api/users?page=3' }). A predicate such as r => r.url === '/api/users' also works, because r.url excludes the query string.