Sub topic 12
Testing Zoneless Components
This chapter assumes you can write standalone components, use signal and computed, and run basic TestBed tests. It also assumes you know that a zoneless app has no Zone.js to tell Angular when asynchronous work finishes. The goal is to write tests that wait for Angular's scheduled change detection instead of forcing it by hand.
Why tests change in a zoneless app
In a zone-based test, fixture.detectChanges() ran change detection when you called it. Zone.js also made fixture.whenStable() wait for timers, promises and other zone-tracked work.
Without zones, the application schedules change detection itself. It does this when a signal read in a template changes, when markForCheck() is called, when a listener in the template runs, and in a few other cases. Tests should follow the same path. If a test calls detectChanges() after every change, it can pass even when the real app would never update the view.
The practical rule is this: change state the way the user or the app would, then await fixture.whenStable(), then assert.
Enabling zoneless mode in tests
Add provideZonelessChangeDetection() to the TestBed providers. The test should use the same mode as the production app.
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { Counter } from './counter';
describe('Counter', () => {
it('updates the view after a click', async () => {
TestBed.configureTestingModule({
providers: [provideZonelessChangeDetection()],
});
const fixture = TestBed.createComponent(Counter);
await fixture.whenStable();
fixture.nativeElement.querySelector('button').click();
await fixture.whenStable();
expect(fixture.nativeElement.textContent).toContain('Clicked 1 times');
});
});The test does four things in order:
- It configures zoneless mode before creating the component.
- It awaits
whenStable()once so the first render finishes. - It clicks the button. The click runs a template listener, which notifies Angular that a check is needed. The listener also changes a signal that the template reads.
- It awaits
whenStable()again, then asserts on the DOM.
The component under test is the Counter from earlier in this tutorial. It uses OnPush and a signal named count.
If your test suite loads zone.js as a polyfill, remove it from the test target in angular.json, just as you did for build. Otherwise the tests would run in a different environment than the app.
What `whenStable()` waits for
fixture.whenStable() returns a promise that resolves when Angular considers the application stable. Stable means two things:
- No change detection is scheduled and waiting to run.
- No pending tasks are registered.
Pending tasks come from PendingTasks (covered in the previous chapter) and from some Angular features, such as HttpClient requests and router navigations, which register tasks internally. Plain setTimeout and setInterval calls are not tracked. Awaiting whenStable() will not wait for a timer you started yourself.
| Situation | Does `whenStable()` wait? |
|---|---|
| Scheduled change detection after a signal change | Yes |
| Work wrapped in `PendingTasks.run()` | Yes |
| Router navigation in progress | Yes |
| A bare `setTimeout` in your component | No |
| A bare `fetch` call without `PendingTasks` | No |
For untracked timers, use the test framework's fake timers and advance them explicitly, then await stability.
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { LegacyTimer } from './legacy-timer';
describe('LegacyTimer', () => {
beforeEach(() => {
jasmine.clock().install();
TestBed.configureTestingModule({
providers: [provideZonelessChangeDetection()],
});
});
afterEach(() => jasmine.clock().uninstall());
it('shows elapsed seconds', async () => {
const fixture = TestBed.createComponent(LegacyTimer);
await fixture.whenStable();
jasmine.clock().tick(3000);
await fixture.whenStable();
expect(fixture.nativeElement.textContent).toContain('Seconds: 3');
});
});This works because LegacyTimer calls markForCheck() inside its interval callback. Without that call, the DOM would still show Seconds: 0, and the test would fail. That failure is useful: it shows the same bug the real app would have.
Why `detectChanges()` can hide bugs
fixture.detectChanges() still exists and still runs change detection. In zoneless mode, though, calling it manually works against the point of the test. It runs a check the application did not schedule.
Consider a component with a plain field and OnPush:
import { ChangeDetectionStrategy, Component } from '@angular/core';
@Component({
selector: 'app-broken',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ label }}</p>`,
})
export class Broken {
protected label = 'before';
rename() {
this.label = 'after';
}
}A test that calls component.rename() directly and then fixture.detectChanges() may see the update in some configurations. In a real zoneless app, nothing would notify Angular after rename() runs from, say, a timer. The test passes while the app is broken.
Angular's test fixture also changes behavior in zoneless mode. If you call fixture.detectChanges() on a zoneless fixture, the check runs, but the fixture's autoDetect behavior is already on. For that reason, prefer await fixture.whenStable().
Setting inputs in tests
With signal inputs, set them through the fixture's component reference, not by assigning to the component instance.
import { Component, input } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `<p>Hello, {{ name() }}</p>`,
})
export class Greeting {
readonly name = input.required<string>();
}
describe('Greeting', () => {
it('renders the name input', async () => {
TestBed.configureTestingModule({
providers: [provideZonelessChangeDetection()],
});
const fixture = TestBed.createComponent(Greeting);
fixture.componentRef.setInput('name', 'Ada');
await fixture.whenStable();
expect(fixture.nativeElement.textContent).toContain('Hello, Ada');
});
});setInput() goes through the same path Angular uses for template bindings, so it marks the view for checking. Assigning fixture.componentInstance.name = ... does not work for signal inputs, because the input is a read-only function.
Testing code that uses `PendingTasks`
When a service wraps its work in PendingTasks.run(), a test can await the result and stability together.
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { DataLoader } from './data-loader';
describe('DataLoader', () => {
it('keeps the app unstable while loading', async () => {
TestBed.configureTestingModule({
providers: [provideZonelessChangeDetection()],
});
const loader = TestBed.inject(DataLoader);
spyOn(window, 'fetch').and.resolveTo(
new Response(JSON.stringify({ ok: true })),
);
const result = await loader.load('/api/status');
expect(result).toEqual({ ok: true });
});
});Here the DataLoader service is the one from the previous chapter. The test awaits the returned promise directly. For components that start such a load, await fixture.whenStable() instead, and it will wait until the task finishes.
Common errors
- Assertion sees old content. The state change did not notify Angular. Check that the field is a signal, that
markForCheck()is called, or that the change comes from a template listener. - Test hangs or times out. A pending task never completes, for example a
PendingTasks.run()around a promise that never settles. Check that every started task finishes. - Test passes but the app fails. The test used
detectChanges()and hid a missing notification. Remove the manual call and awaitwhenStable(). ExpressionChangedAfterItHasBeenCheckederrors. Zoneless mode keeps this dev-mode check. A signal or field changed during rendering. Move the change out of the template path or into an effect or lifecycle hook that runs before the check.- Zone.js still loaded. If a test polyfill still imports
zone.js, the suite does not reflect the zoneless app. Remove it fromangular.jsonand any test setup file.
A flow to follow
Exercises
Exercise
A test creates a component with OnPush and a plain field total. The test sets component.total = 5, awaits fixture.whenStable(), and expects the DOM to show 5. The assertion fails. Why, and how do you fix the component?
Show answer
Setting a plain field does not notify Angular, so no change detection is scheduled and the view keeps the old value. Fix the component by making total a signal and setting it with total.set(5), or by calling markForCheck() after the change. The test should then pass without calling detectChanges().
Exercise
Why does await fixture.whenStable() not wait for a setTimeout of 500 ms that a component starts on its own? What can a test do instead?
Show answer
Without Zone.js, Angular does not track plain timers, so they do not count as pending work. The test can install fake timers, advance them by 500 ms, and then await whenStable(). Alternatively, the component can wrap the work in PendingTasks.run() so Angular tracks it.
Exercise
How should a test set a required signal input named title on a component created with TestBed.createComponent?
Show answer
Call fixture.componentRef.setInput('title', 'value'), then await fixture.whenStable(). Assigning to the instance property does not work because a signal input is read-only.