Sub topic 14
Testing components that use resources
This chapter shows how to test components built on resource, rxResource and httpResource. It assumes you can write Jasmine-style specs with TestBed, and that you know the resource status signals and the UserComponent from earlier chapters. The examples use Jasmine (spyOn, jasmine.Spy). In Vitest, use vi.spyOn and mockResolvedValue. The structure is the same.
What makes resources different to test
A resource does not start loading when you create it. Angular schedules the loader from inside the reactive graph, so a test has to let that scheduling run. A test that creates a component and immediately asserts on the result sees no request yet, or a resource still in loading.
Three tools cover almost every case:
| Tool | Purpose |
|---|---|
| `TestBed.tick()` | Runs pending effects and change detection, so loaders start and aborts happen. Added in Angular 20. In Angular 19, use `TestBed.flushEffects()`. |
| `await fixture.whenStable()` | Waits until pending work finishes. A running resource loader counts as pending work. |
| `fixture.detectChanges()` | Renders the new signal values into the DOM. |
The usual order is: change an input, call TestBed.tick(), resolve the data source, await fixture.whenStable(), call fixture.detectChanges(), then assert.
Testing a fetch-based resource
The UserComponent from the first chapter calls the global fetch inside its loader. The simplest seam is to replace fetch with a spy that returns real Response objects. Real Response objects keep res.ok and res.json() behaving as they do in production.
import { TestBed } from '@angular/core/testing';
import { UserComponent } from './user.component';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { status });
}
describe('UserComponent', () => {
let fetchSpy: jasmine.Spy;
beforeEach(() => {
fetchSpy = spyOn(globalThis, 'fetch');
});
it('renders the user name after the load finishes', async () => {
fetchSpy.and.resolveTo(jsonResponse({ id: 1, name: 'Ada' }));
const fixture = TestBed.createComponent(UserComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).not.toContain('Ada');
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Ada');
expect(fetchSpy.calls.mostRecent().args[0]).toBe('/api/users/1');
});
it('renders the error branch when the server answers 500', async () => {
fetchSpy.and.resolveTo(jsonResponse({}, 500));
const fixture = TestBed.createComponent(UserComponent);
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Could not load the user.');
expect(fixture.componentInstance.user.status()).toBe('error');
});
});The second test works because the loader throws new Error('HTTP 500') when res.ok is false. The resource catches it, and user.error() becomes truthy. Your test did not need a try/catch.
spyOn replaces fetch for one spec and Jasmine restores it afterwards. If you use a different runner, restore the original fetch yourself.
Testing reactive params and cancellation
To test that a signal change triggers a new load, set the signal, tick, and inspect the spy.
it('loads again when userId changes', async () => {
fetchSpy.and.callFake(async (url: string) =>
jsonResponse({ id: url.endsWith('/2') ? 2 : 1, name: url.endsWith('/2') ? 'Grace' : 'Ada' }),
);
const fixture = TestBed.createComponent(UserComponent);
fixture.detectChanges();
await fixture.whenStable();
fixture.componentInstance.userId.set(2);
TestBed.tick();
await fixture.whenStable();
fixture.detectChanges();
expect(fetchSpy).toHaveBeenCalledTimes(2);
expect(fetchSpy.calls.mostRecent().args[0]).toBe('/api/users/2');
expect(fixture.nativeElement.textContent).toContain('Grace');
});To verify cancellation, hold the first request open with a promise you control. Change the params, then check that the AbortSignal the loader received is aborted.
it('aborts the superseded request', async () => {
let release!: (r: Response) => void;
const pending = new Promise<Response>((resolve) => (release = resolve));
fetchSpy.and.returnValues(pending, Promise.resolve(jsonResponse({ id: 2, name: 'Grace' })));
const fixture = TestBed.createComponent(UserComponent);
fixture.detectChanges();
TestBed.tick();
const firstSignal = (fetchSpy.calls.argsFor(0)[1] as RequestInit).signal as AbortSignal;
expect(firstSignal.aborted).toBeFalse();
fixture.componentInstance.userId.set(2);
TestBed.tick();
expect(firstSignal.aborted).toBeTrue();
release(jsonResponse({ id: 1, name: 'Ada' }));
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Grace');
});The last assertion matters most. The late answer for user 1 must not overwrite the value for user 2. That is the bug abortSignal and the resource's internal request tracking exist to prevent.
Testing httpResource and rxResource with HttpTestingController
httpResource sends its request through HttpClient. That means you do not spy on fetch. You use the standard HTTP testing providers and HttpTestingController, the same way you would for a service.
import { TestBed } from '@angular/core/testing';
import { HttpErrorResponse, provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { UserHttpComponent } from './user-http.component';
describe('UserHttpComponent', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('requests the user and shows the name', async () => {
const fixture = TestBed.createComponent(UserHttpComponent);
fixture.detectChanges();
TestBed.tick();
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');
});
it('exposes an HttpErrorResponse on failure', async () => {
const fixture = TestBed.createComponent(UserHttpComponent);
fixture.detectChanges();
TestBed.tick();
http.expectOne('/api/users/1').flush('nope', { status: 404, statusText: 'Not Found' });
await fixture.whenStable();
const user = fixture.componentInstance.user;
expect(user.status()).toBe('error');
expect(user.error()).toBeInstanceOf(HttpErrorResponse);
});
});Two details to remember:
TestBed.tick()must run beforeexpectOne. Without it the request has not been sent, and the matcher fails with a message saying no matching request was found.http.verify()inafterEachcatches requests you forgot to answer, including extra requests caused by a signal that changed more often than you expected.
rxResource tests look the same when the stream uses HttpClient, as in UserRxComponent. If the stream comes from a service, provide a fake service that returns of(...), throwError(...) or a Subject you control. A Subject lets you test the loading state, because the resource stays in loading until you call next.
TestBed.configureTestingModule({
providers: [{ provide: UserService, useValue: { load: () => subject.asObservable() } }],
});Testing dependent resources
For the posts resource that waits on user, assert the order of requests. While the user is loading, params returns undefined, so no posts request may be made.
it('does not request posts before the user has loaded', async () => {
const fixture = TestBed.createComponent(UserPostsComponent);
fixture.detectChanges();
TestBed.tick();
const urls = fetchSpy.calls.allArgs().map((args) => args[0]);
expect(urls).toEqual(['/api/users/1']);
await fixture.whenStable();
TestBed.tick();
await fixture.whenStable();
expect(fetchSpy.calls.mostRecent().args[0]).toBe('/api/users/1/posts');
});Here fetchSpy should answer user URLs with a user and post URLs with an array, using callFake as in the earlier example. The second tick and whenStable pair is needed because the posts resource only starts after the user value arrives. One round of waiting is not enough for a two-step chain.
Testing local writes and reloads
reload() and update() are plain method calls, so test them through the component's public methods from the TodosComponent example.
- For
reload(), assert that the spy call count goes from 1 to 2 aftertick(). - For
update(), assert the rendered count changes and the spy call count does not.
it('adds a todo locally without a request', async () => {
fetchSpy.and.resolveTo(jsonResponse([{ id: 1, title: 'A' }]));
const fixture = TestBed.createComponent(TodosComponent);
fixture.detectChanges();
await fixture.whenStable();
fixture.componentInstance.addLocal();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('2 todos');
expect(fetchSpy).toHaveBeenCalledTimes(1);
});Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| `expectOne` finds no request | The loader has not been scheduled yet | Call `TestBed.tick()` first |
| DOM still shows the old state | Signals updated but the view was not refreshed | Call `fixture.detectChanges()` after `whenStable()` |
| `TestBed.tick is not a function` | Angular version before 20 | Use `TestBed.flushEffects()` |
| `NullInjectorError` for `HttpClient` | Missing providers | Add `provideHttpClient()` and `provideHttpClientTesting()` |
| Spec passes but request count is wrong | Too many signal writes before ticking | Assert the call count, and add `http.verify()` |
| Test hangs on `whenStable` | A fake promise or `Subject` never resolves | Resolve, complete, or error the source before waiting |
Exercise
In a spec for UserHttpComponent, you call fixture.detectChanges() and then http.expectOne('/api/users/1'). The test fails because no request was found. What is missing, and what happens in Angular 19?
Show answer
The loader has not been scheduled yet, so call TestBed.tick() between detectChanges() and expectOne. In Angular 19, TestBed.tick() does not exist, so call TestBed.flushEffects() instead.
Exercise
You want to prove that a slow response for user 1 cannot overwrite the data for user 2 after the user changes userId. Describe how to set up fetch and what you assert.
Show answer
Make the first fetch call return a promise you control and the second return a resolved response for user 2. Set userId to 2 and call TestBed.tick(). Assert that the AbortSignal passed to the first call is aborted. Then resolve the first promise with user 1 data, wait with whenStable(), call detectChanges(), and assert the DOM shows user 2's name.
Exercise
Why does the dependent-resource test need two rounds of tick() and whenStable()?
Show answer
The posts resource only receives defined params after the user resource has a value. The first round lets the user load finish. The second round lets the posts loader start and complete.