Sub topic 14
Testing components that use httpResource
This chapter assumes you can write Angular component tests with TestBed, you know signals, and you have read the earlier chapters on httpResource, request functions and parse. The examples use plain describe, it and expect, so they work with Jasmine or Vitest. Where the two differ, the text says so.
Test at the HTTP boundary
An httpResource sends its requests through HttpClient. So you don't mock the resource. You replace the HTTP backend and let the real resource run against it. This tests what matters: which URL the component requests, how it reacts to a response, and what it does when a signal changes.
Angular provides this backend in provideHttpClientTesting. Together with HttpTestingController, it lets a test inspect each outgoing request and decide how to answer it.
Setup
Provide provideHttpClient() and then provideHttpClientTesting(), in that order. The testing provider must come second so it overrides the real backend. Call verify() after each test to fail on requests nobody handled.
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();
});
});The tests below go inside this describe block. They use the UserComponent from the earlier chapter, with its userId signal and user resource.
The request-then-flush pattern
A resource does not send its request when you construct the component. The request function runs inside an effect, and effects run during change detection. So the sequence in a test is:
- Create the component and call
fixture.detectChanges(). - Find the request with
http.expectOne(...)and check its method and URL. - Call
flush(...)on it to deliver a response. - Wait for the resource to settle, then call
detectChanges()again and assert on the DOM.
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');
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Loading');
req.flush({ id: 1, name: 'Ada' });
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Ada');
expect(fixture.nativeElement.textContent).not.toContain('Loading');
});The order of the last steps matters. The resource writes its result after a microtask, so the value is not in the signal the instant flush returns. await fixture.whenStable() waits for that.
If expectOne reports that no request matched right after the first detectChanges(), the resource's effect has not run yet. Call TestBed.tick() (Angular 20 and later) to run pending effects. On Angular 19 the equivalent is TestBed.flushEffects().
Matching requests
expectOne accepts a URL string, a HttpRequest matcher object, or a predicate function. A URL string matches against the URL including query parameters, so a request built from a request object with params needs a predicate or the full string.
| Method | Use it to |
|---|---|
| `expectOne(urlOrFn)` | Require exactly one matching open request and return it |
| `expectNone(urlOrFn)` | Assert that no matching request is open |
| `match(urlOrFn)` | Get all matching requests, possibly none |
| `verify()` | Fail if any request is still open |
| `flush(body, opts)` | Answer a request with a body and optional status |
| `error(event)` | Simulate a network failure |
Idle requests and request objects
The search component from the earlier chapter returns undefined for an empty query. A test should prove that no request leaves the component until the user types something, and then check the query parameters.
it('sends no request for an empty query, then searches', async () => {
const fixture = TestBed.createComponent(SearchComponent);
fixture.detectChanges();
http.expectNone('/api/products');
fixture.componentInstance.query.set('lamp');
fixture.detectChanges();
const req = http.expectOne(
(r) => r.url === '/api/products' && r.params.get('q') === 'lamp',
);
expect(req.request.params.get('limit')).toBe('10');
req.flush([{ id: 7, title: 'Desk lamp' }]);
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Desk lamp');
});req.url holds the path without the query string, and req.params holds the parameters. That is why the predicate checks them separately.
Errors
Flush a non-2xx status to test the error state. Angular's HttpClient turns that into an HttpErrorResponse, which the resource stores in error().
it('shows an error message when the server fails', async () => {
const fixture = TestBed.createComponent(UserComponent);
fixture.detectChanges();
http
.expectOne('/api/users/1')
.flush('Server broke', { status: 500, statusText: 'Server Error' });
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Could not load the user.');
expect(fixture.componentInstance.user.status()).toBe('error');
});To simulate a lost connection instead of an error status, call req.error(new ProgressEvent('error')). The resource ends up in the same error status, but the error has status 0.
Signal changes and cancellation
You can test the cancellation behavior from the earlier chapter directly. Change the signal while the first request is still open, and the first request is cancelled and a second one is sent.
it('cancels the outdated request when userId changes', () => {
const fixture = TestBed.createComponent(UserComponent);
fixture.detectChanges();
const first = http.expectOne('/api/users/1');
fixture.componentInstance.userId.set(2);
fixture.detectChanges();
TestBed.tick();
expect(first.cancelled).toBe(true);
http.expectOne('/api/users/2').flush({ id: 2, name: 'Grace' });
http.verify({ ignoreCancelled: true });
});A cancelled request stays in the controller's open list. A plain verify() would fail on it, so pass ignoreCancelled: true in tests like this one. Also note that flush on a cancelled request throws, so never flush first after the change.
Testing the resource without a component
If a resource lives in a factory function such as createUserResource, you don't need a component. Run the factory in an injection context, drive its inputs with signals, and assert on the resource directly. This is the fastest way to test parse.
import { ApplicationRef, signal } from '@angular/core';
import { createUserResource } from './user-resource';
it('puts the resource in the error state for a bad payload', async () => {
const id = signal(1);
const res = TestBed.runInInjectionContext(() => createUserResource(id));
TestBed.tick();
http.expectOne('/api/users/1').flush({ id: 'not-a-number', name: 'Ada' });
await TestBed.inject(ApplicationRef).whenStable();
expect(res.status()).toBe('error');
expect(res.error()).toBeTruthy();
});The server answered with status 200, yet the resource ends in error, because parseUser threw. This test would catch a regression in the parser that a component test might miss.
Testing interceptors
Because the resource uses HttpClient, your interceptors apply to it. To test one, register it in the test providers and inspect the request headers.
import { HttpInterceptorFn } from '@angular/common/http';
import { withInterceptors } from '@angular/common/http';
const authInterceptor: HttpInterceptorFn = (req, next) =>
next(req.clone({ setHeaders: { Authorization: 'Bearer test-token' } }));
it('sends the auth header through the interceptor', () => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([authInterceptor])),
provideHttpClientTesting(),
],
});
const controller = TestBed.inject(HttpTestingController);
const fixture = TestBed.createComponent(UserComponent);
fixture.detectChanges();
const req = controller.expectOne('/api/users/1');
expect(req.request.headers.get('Authorization')).toBe('Bearer test-token');
req.flush({ id: 1, name: 'Ada' });
});In a real project, import your own interceptor instead of defining one in the test file.
Common mistakes
- Awaiting before flushing. The test hangs, because the open request keeps the app unstable.
- Asserting right after
flush. The DOM has not changed yet. Wait for stability, then calldetectChanges(). - Forgetting
provideHttpClient(). Without it,httpResourcethrows a missing-provider error before any test logic runs. - Reversed provider order. If
provideHttpClientTesting()comes first, the real backend replaces it and the test makes real network calls. - Plain
verify()after a cancellation test. It fails on the cancelled request. UseignoreCancelled. - Matching a URL string when the request has
params. Use a predicate and checkreq.params.
Exercise
A test creates a component, calls fixture.detectChanges(), then runs await fixture.whenStable() and only afterwards calls http.expectOne('/api/users/1').flush(...). The test times out. Why, and how do you fix it?
Show answer
The resource's request is still pending when whenStable() is awaited, and a pending request counts as unfinished work, so the promise cannot resolve until the response is delivered. The flush never runs because the test is stuck waiting. Fix it by getting the request with expectOne and calling flush first, then await fixture.whenStable(), then fixture.detectChanges() and the assertions.
Exercise
You test that changing a signal cancels an in-flight request. Your afterEach calls http.verify() and fails even though the second request was flushed. What do you change?
Show answer
The first request was cancelled but is still listed as open in the controller. Call http.verify({ ignoreCancelled: true }), and do not call flush on the cancelled request.