Sub topic 5
Fixtures and change detection
This chapter assumes you can write a basic Vitest test and create a component with TestBed.createComponent. It also assumes you know what signals are. Here you will learn why a freshly created component shows nothing useful until you run change detection, and how to control when that happens.
What a fixture is
TestBed.createComponent returns a ComponentFixture. The fixture wraps the component instance and its host element. These are its most used members:
| Member | What it gives you |
|---|---|
| `componentInstance` | The component class instance |
| `componentRef` | The `ComponentRef`, used for `setInput` |
| `nativeElement` | The host DOM element |
| `debugElement` | A wrapper with query and event helpers |
| `detectChanges()` | Runs change detection once |
| `whenStable()` | A promise that resolves when pending async work is done |
Change detection is not automatic
Change detection is the step where Angular evaluates template bindings and updates the DOM. In a test, creating the component does not run that step. You choose when it runs.
The following test uses the CounterComponent from the earlier chapter. It checks the DOM at each step.
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
import { CounterComponent } from './counter.component';
describe('CounterComponent change detection', () => {
it('updates the DOM only when change detection runs', () => {
const fixture = TestBed.createComponent(CounterComponent);
const root: HTMLElement = fixture.nativeElement;
const readText = () =>
root.querySelector('[data-testid="count"]')?.textContent ?? '';
expect(readText()).not.toContain('Count: 0');
fixture.detectChanges();
expect(readText()).toContain('Count: 0');
root.querySelector('button')!.click();
expect(readText()).toContain('Count: 0');
fixture.detectChanges();
expect(readText()).toContain('Count: 1');
});
});Three things happen here:
- Before the first
detectChanges(), the template's bindings have not been evaluated, so the text is not yetCount: 0. - The first
detectChanges()also runsngOnInitand renders the initial state. - The click changes the signal immediately, but the DOM still shows the old text until the next change detection pass.
Common errors
- Stale DOM. You act on the component and assert on the DOM without calling
detectChanges(). The assertion sees the previous render. CalldetectChanges()after every action whose result you want to read from the DOM. - Setting inputs too late. Call
fixture.componentRef.setInput(...)before the firstdetectChanges()when the component reads the input at startup. Setting it later is fine, but it needs anotherdetectChanges(). - Asserting on the instance instead of the DOM. Checking
componentInstanceis fine for logic. It cannot show that the template displays the value.
Waiting for async work
When a component starts asynchronous work, such as a resolved promise, await fixture.whenStable() waits for the pending work to finish. Then call detectChanges() to render the result. For timers, use the fake timers shown in a later chapter, because whenStable() does not speed up a real setTimeout.
Exercise
A test clicks a button that increments a signal, then immediately reads the text of the element that displays the signal. The text still shows the old value. What is missing, and where does it go?
Show answer
The test needs a call to fixture.detectChanges() after the click and before reading the text. The click updates the signal, but the DOM is only updated when change detection runs.