Sub topic 14
Testing components that use httpResource
This chapter assumes you can write a basic Angular component test with TestBed. It also assumes you know the httpResource basics from earlier chapters: the request function, value(), isLoading() and error().
The testing approach
Don't mock httpResource. It sends requests through HttpClient, so you replace the HTTP backend and keep the real resource. Angular's testing backend records every request and lets you answer each one by hand. The test then checks what the template shows.
Configure the testing backend
Provide provideHttpClient() first, then provideHttpClientTesting(). The second provider swaps the real network for the testing backend, so it must come after the first.
Test the success path
The test below uses the UserComponent from the earlier chapter. It works with Jasmine or Jest.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { UserComponent } from './user.component';
describe('UserComponent', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('shows the user name after the response arrives', async () => {
const fixture = TestBed.createComponent(UserComponent);
fixture.detectChanges();
const req = http.expectOne('/api/users/1');
expect(req.request.method).toBe('GET');
req.flush({ id: 1, name: 'Ada' });
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Ada');
});
});Three details matter here:
- The resource sends its request when change detection first runs. Call
fixture.detectChanges()beforeexpectOne, or the controller finds no request. flushcompletes the request, but the resource updates its signals asynchronously. Wait withawait fixture.whenStable(), then calldetectChanges()again so the template re-renders.http.verify()inafterEachfails the test if a request was never answered or an unexpected one was sent.
Test reactive requests and errors
A signal change should produce a new request. Click the button, then assert on the new URL.
it('requests the next user when the button is clicked', async () => {
const fixture = TestBed.createComponent(UserComponent);
fixture.detectChanges();
http.expectOne('/api/users/1').flush({ id: 1, name: 'Ada' });
await fixture.whenStable();
fixture.nativeElement.querySelector('button').click();
fixture.detectChanges();
http.expectOne('/api/users/2').flush({ id: 2, name: 'Grace' });
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Grace');
});
it('shows an error message when the request fails', async () => {
const fixture = TestBed.createComponent(UserComponent);
fixture.detectChanges();
http
.expectOne('/api/users/1')
.flush('Server error', { status: 500, statusText: 'Server Error' });
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Could not load the user.');
});Add these tests inside the same describe block. An idle resource is easy to test. Leave the signal in the state that makes the request function return undefined, then call http.expectNone('/api/products').
Common mistakes
| Symptom | Likely cause |
|---|---|
| `expectOne` finds no matching request | No `detectChanges()` or `TestBed.tick()` yet, or the URL string differs |
| Template still shows the loading state | Missing `await fixture.whenStable()` or a second `detectChanges()` after `flush` |
| `NullInjectorError` for `HttpClient` | `provideHttpClient()` is missing from the test providers |
| Real network calls in tests | `provideHttpClientTesting()` is missing or listed before `provideHttpClient()` |
Exercise
Write the one-line assertion that proves a SearchComponent sends no request while its query signal is an empty string. Which controller method do you use, and why is it better than checking the DOM?
Show answer
Use http.expectNone('/api/products'). The request function returns undefined for an empty query, so the resource stays idle and no request reaches the testing backend. expectNone fails if a request to that URL was sent. A DOM check could pass even when a wasted request went out.