Sub topic 5
Fixtures and change detection
This chapter assumes you can write a basic Vitest test, create a component with TestBed.createComponent, and read Angular signals in templates. It covers what a ComponentFixture gives you and when the DOM updates in a test.
What a fixture is
TestBed.createComponent(Type) returns a ComponentFixture. The fixture wraps the component instance, its host element, and the change detector that renders it. These members are the ones you will use most:
| Member | What it gives you |
|---|---|
| `componentInstance` | The component class instance. |
| `nativeElement` | The host DOM element, typed as `any`. |
| `debugElement` | Angular's wrapper around the host, with `query` and `triggerEventHandler`. |
| `componentRef` | The `ComponentRef`, used for `setInput`. |
| `detectChanges()` | Runs change detection once, synchronously. |
| `autoDetectChanges()` | Turns on automatic change detection for the fixture. |
| `whenStable()` | Returns a promise that resolves when pending async work has settled. |
The fixture is a test tool. Your application never creates one.
Change detection does not run by itself
Creating a component does not render its bindings. Angular evaluates template bindings during change detection, and by default a fixture does not run change detection until you ask. Until your first detectChanges() call, the DOM does not reflect the component's state. The first call also runs lifecycle hooks such as ngOnInit.
This is deliberate. It lets you configure the component, for example with setInput, before the first render. It also lets you assert on state between renders.
The standard rhythm: act, detect, assert
Most component tests follow one pattern. You do something, call detectChanges(), then read the DOM. Here is the counter from the previous chapter, with a render before and after the click.
import { Component, input, output, signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
@Component({
selector: 'app-counter',
template: `
<p data-testid="count">Count: {{ count() }}</p>
<button type="button" (click)="increment()">Add</button>
`,
})
export class CounterComponent {
readonly step = input(1);
readonly changed = output<number>();
protected readonly count = signal(0);
increment() {
this.count.update((c) => c + this.step());
this.changed.emit(this.count());
}
}
describe('CounterComponent rendering', () => {
it('renders the initial count, then the updated count', () => {
const fixture = TestBed.createComponent(CounterComponent);
fixture.detectChanges();
const read = () =>
fixture.nativeElement.querySelector('[data-testid="count"]').textContent;
expect(read()).toContain('Count: 0');
fixture.nativeElement.querySelector('button').click();
expect(read()).toContain('Count: 0');
fixture.detectChanges();
expect(read()).toContain('Count: 1');
});
});The second assertion shows the point of this section. The click already ran increment() and changed the signal. The DOM still says Count: 0 because nothing has refreshed the template yet. In a running application, Angular schedules that refresh for you. In a fixture, you trigger it.
Wrapping the query in a read helper means you query the DOM again after each render. That is safer than holding on to an element reference, because Angular can replace elements, for example inside @if and @for blocks.
Why the first call matters
Call detectChanges() once, as late as possible in your setup, after everything the first render depends on is in place. Two things go wrong if you call it too early:
- Setting an input after the first render still works with
setInput, but you now test an update path when you meant to test initial rendering. - Lifecycle hooks such as
ngOnInithave already read the default values. IfngOnInitreads an input, it will not see a value you set afterwards.
A common structure is a small factory function that creates the fixture, applies inputs, and renders once.
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
import { CounterComponent } from './counter.component';
function render(step: number) {
const fixture = TestBed.createComponent(CounterComponent);
fixture.componentRef.setInput('step', step);
fixture.detectChanges();
return fixture;
}
describe('CounterComponent step', () => {
it('adds the configured step', () => {
const fixture = render(10);
fixture.nativeElement.querySelector('button').click();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Count: 10');
});
});Automatic change detection
fixture.autoDetectChanges() makes the fixture refresh the view whenever Angular would normally do so, so you do not call detectChanges() after every action. You can also turn it on for every fixture in a test with the ComponentFixtureAutoDetect provider.
Automatic mode is convenient, but explicit calls are usually the better default for these reasons:
- You can assert on the in-between state, as the counter test did.
- Each render happens at a line you can see, so a failing test is easier to trace.
- Behavior does not change depending on whether the project runs with zone.js or in zoneless mode.
In zoneless mode, Angular schedules change detection when a signal read by a template changes, and fixtures follow that behavior. The practical rule is the same in both modes: after an action, either call detectChanges() or await fixture.whenStable(), then assert.
Waiting for asynchronous work
detectChanges() is synchronous. It cannot wait for a promise. When the component updates state after an async step, wait for the work first, then render. Use whenStable() for that.
import { Component, signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
@Component({
selector: 'app-greeting',
template: `<p>{{ message() }}</p>`,
})
export class GreetingComponent {
protected readonly message = signal('Loading...');
constructor() {
Promise.resolve('Hello').then((value) => this.message.set(value));
}
}
describe('GreetingComponent', () => {
it('shows the loaded message after async work settles', async () => {
const fixture = TestBed.createComponent(GreetingComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Loading...');
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Hello');
});
});The test function is async because it uses await. Vitest handles async tests by waiting for the returned promise. If you forget await, the test finishes before the assertion runs, and a failure inside the unawaited call may surface in a later test or not at all.
whenStable() waits for work that Angular tracks. A bare setTimeout is not always tracked. Timers are covered in the async and fake timers chapter.
OnPush components
A component with changeDetection: ChangeDetectionStrategy.OnPush is refreshed only when one of its inputs changes, an event fires in its template, a signal it reads changes, or it is marked dirty explicitly. This matters in tests because the fixture's detectChanges() respects it.
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
@Component({
selector: 'app-badge',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<span>{{ label() }}</span>`,
})
export class BadgeComponent {
readonly label = input('new');
}
describe('BadgeComponent', () => {
it('updates when the input changes through setInput', () => {
const fixture = TestBed.createComponent(BadgeComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('new');
fixture.componentRef.setInput('label', 'sale');
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('sale');
});
});setInput marks the component as needing a refresh, so the second detectChanges() renders it. The tempting alternative is to assign a plain field on componentInstance and call detectChanges(). For a component that reads a plain, non-signal field, that does not update the DOM after the first render. The component is OnPush and nothing told Angular it changed. This also applies to your own code. If a test passes only when you add a manual detectChanges() call, check whether the component updates state in a way an OnPush component would not notice.
Errors you will meet
detectChanges() runs a second verification pass by default. If a binding's value changes between the two passes, Angular throws ExpressionChangedAfterItHasBeenCheckedError. The usual cause is a template that reads a value that a lifecycle hook or getter changes as a side effect.
Other symptoms and their usual causes:
- The DOM shows stale text: you changed state but did not call
detectChanges(), or the component is OnPush and was not marked dirty. querySelectorreturnsnull: the firstdetectChanges()has not run yet, or the element is inside an@ifblock whose condition is false.- An assertion passes, then the test fails later in another test: an async step was not awaited. Add
awaitorawait fixture.whenStable().
Exercise
A test clicks a button that calls count.update(c => c + 1) on a signal rendered in the template, then immediately reads the DOM and still sees the old number. The component uses the default change detection strategy. What is missing, and why does the app work without it?
Show answer
The test must call fixture.detectChanges() after the click and before reading the DOM. A fixture does not refresh the template on its own. In the running app, Angular schedules change detection after the event, so the DOM updates without any extra step.
Exercise
A component is OnPush and renders {{ title }}, a plain field. A test calls fixture.detectChanges(), sets fixture.componentInstance.title = 'B', and calls fixture.detectChanges() again. The DOM still shows the first title. Give two ways to make the test reflect the change without hacks.
Show answer
Make title an input() and set it with fixture.componentRef.setInput('title', 'B') before the second detectChanges(), or make title a signal that the template reads, and update it with set. Both notify Angular that the OnPush component needs a refresh. Plain field assignment does not.