Sub topic 14
Testing components that use resources
This chapter assumes you can write a basic Angular component test with TestBed, and that you know resource, params, and loader from the earlier chapters. The examples use the global describe, it, and expect functions, so they work with Jasmine, Jest, or Vitest.
What makes resources different to test
A resource starts its loader from an effect, not from a method you call. Setting a signal does not start a request immediately. The request starts when Angular next runs change detection or effects. A test therefore has to do two things:
- Trigger the reactive flush with
fixture.detectChanges()orTestBed.tick(). - Wait for the loader to finish with
await fixture.whenStable().
A resource registers its running loader as a pending task, so whenStable() resolves only after the load settles.
Stubbing fetch for a resource
When the loader uses fetch, replace globalThis.fetch in the test and restore it afterwards. This test uses the UserComponent from the first resource example.
import { TestBed } from '@angular/core/testing';
import { UserComponent } from './user.component';
describe('UserComponent', () => {
const realFetch = globalThis.fetch;
let urls: string[];
function stubFetch(status: number, body: unknown) {
urls = [];
globalThis.fetch = (async (input: RequestInfo | URL) => {
urls.push(String(input));
return new Response(JSON.stringify(body), { status });
}) as typeof fetch;
}
afterEach(() => {
globalThis.fetch = realFetch;
});
it('renders the loaded user', async () => {
stubFetch(200, { id: 1, name: 'Ada' });
const fixture = TestBed.createComponent(UserComponent);
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Ada');
});
it('renders the error message on HTTP 500', async () => {
stubFetch(500, {});
const fixture = TestBed.createComponent(UserComponent);
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Could not load the user.');
});
it('reloads when the params signal changes', async () => {
stubFetch(200, { id: 1, name: 'Ada' });
const fixture = TestBed.createComponent(UserComponent);
fixture.detectChanges();
await fixture.whenStable();
fixture.componentInstance.userId.set(2);
fixture.detectChanges();
await fixture.whenStable();
expect(urls).toEqual(['/api/users/1', '/api/users/2']);
});
});Call detectChanges() a second time after whenStable(). The first call starts the load, and the second renders the settled state.
Testing httpResource
httpResource goes through HttpClient, so you can use Angular's testing backend instead of a stub. Provide provideHttpClient() and provideHttpClientTesting(), then answer requests by hand.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { UserHttpComponent } from './user-http.component';
describe('UserHttpComponent', () => {
it('shows the user after the request is answered', async () => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
const http = TestBed.inject(HttpTestingController);
const fixture = TestBed.createComponent(UserHttpComponent);
fixture.detectChanges();
TestBed.tick();
http.expectOne('/api/users/1').flush({ id: 1, name: 'Ada' });
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Ada');
http.verify();
});
});expectOne fails if the request was never issued. This makes it a direct check that your params logic works. Use http.verify() at the end to catch unexpected extra requests.
Common mistakes
- Asserting right after
detectChanges()withoutawait fixture.whenStable(). The DOM still shows the unloaded state. - Forgetting to restore
fetch, so a stub leaks into other test files. - Resolving a stub with a plain object. The loader calls
res.okandres.json(), so return a realResponse. - Testing the loading text on the first render. Whether
isLoading()is already true then depends on effect timing, so assert on settled states.
Exercise
A test sets component.userId.set(2) and immediately checks that fetch was called with /api/users/2, but the check fails. What two steps are missing?
Show answer
The test must first trigger the reactive flush with fixture.detectChanges() (or TestBed.tick()), so the effect runs the loader. It must then await fixture.whenStable() so the loader finishes before asserting.