Sub topic 2
Fixtures and Change Detection
Assume you know basic TypeScript, standalone Angular components, dependency injection, signals, and the Angular CLI.
ComponentFixture and Change Detection
A ComponentFixture is the test wrapper around a component instance and its rendered DOM. Create one with TestBed, then call detectChanges() to run Angular's change-detection cycle.
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
import { CounterComponent } from './counter.component';
describe('CounterComponent', () => {
it('updates the rendered count', () => {
const fixture = TestBed.createComponent(CounterComponent);
fixture.detectChanges();
fixture.componentInstance.increment();
fixture.detectChanges();
const text = fixture.nativeElement
.querySelector('[data-testid="count"]').textContent;
expect(text).toContain('Count: 1');
});
});The component instance and the DOM do not always update at the same moment. After changing state, call detectChanges() before making DOM assertions.
Querying the DOM and Triggering Events
Use fixture.nativeElement for DOM queries. Prefer stable attributes such as data-testid when the exact styling or element structure is not part of the behavior under test.
Trigger a user action with element.click(), then run change detection and check the result. Testing the DOM this way verifies the component's template and event binding together.
Testing Inputs and Outputs
Set signal inputs through the component reference:
fixture.componentRef.setInput('step', 5);Subscribe to an output before triggering the action:
const onChanged = vi.fn();
fixture.componentInstance.changed.subscribe(onChanged);After clicking the button and calling detectChanges(), assert both the visible result and the emitted value. This checks the component's public behavior rather than its private signal.
Replacing Dependencies with Mocks
Configure a replacement provider before creating the component:
TestBed.configureTestingModule({
providers: [
{ provide: UserService, useValue: { list: vi.fn(() => of(['Ada'])) } },
],
});A mock isolates the component from network calls and makes the test deterministic. Use vi.fn() when you need to control a return value or verify call counts. Use vi.spyOn() when you want to observe or temporarily replace a method on an existing object.
Exercise
Why should a test call fixture.detectChanges() after changing component state?
Show answer
It runs Angular's change-detection cycle so the fixture's DOM reflects the new state.