Sub topic 10
Testing OnPush components
This chapter assumes you can write Angular components with inputs and outputs, and that you have used TestBed for basic component tests. It covers why OnPush components behave differently in tests and how to write tests that match what happens in a running app.
Why OnPush changes how you test
A component that uses ChangeDetectionStrategy.OnPush is checked only when something marks it dirty. In an app, an input receiving a new reference, an event in its template, an async pipe emission, or a signal change does that.
A test fixture is different. TestBed.createComponent creates the component, and you decide when change detection runs by calling fixture.detectChanges(). For an OnPush component, the first call renders the view. Later calls do nothing unless the component has been marked for checking.
That produces a common failure. You assign a property directly on the component instance, call detectChanges() again, and the DOM does not change. The component is not broken. The test never gave Angular a reason to check it.
Setting inputs with setInput
The reliable way to pass inputs in a test is componentRef.setInput. It goes through the same path as a template binding, so it marks an OnPush component for checking.
import { TestBed } from '@angular/core/testing';
import { UserCardComponent } from './user-card.component';
describe('UserCardComponent', () => {
it('renders the user name', () => {
const fixture = TestBed.createComponent(UserCardComponent);
fixture.componentRef.setInput('user', { name: 'Ada' });
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Ada');
});
});The test sets the input first and then calls detectChanges(). The view renders Ada.
setInput also works with @Input({ required: true }). If you call detectChanges() before setting a required input, the component renders with undefined, and a template such as user.name throws an error.
Testing an input update
To test that a component reacts to a new input value, call setInput again with a new reference, then run change detection.
it('updates when the input reference changes', () => {
const fixture = TestBed.createComponent(UserCardComponent);
fixture.componentRef.setInput('user', { name: 'Ada' });
fixture.detectChanges();
fixture.componentRef.setInput('user', { name: 'Grace' });
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Grace');
});This second test also documents the contract of the component. It is a good place to check that the component depends on references, not on mutation.
Testing through a host component
setInput tests the component in isolation. To test how a parent passes data down, use a small host component. This matches production behavior, because the parent's template binding does the reference check.
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { User, UserCardComponent } from './user-card.component';
@Component({
imports: [UserCardComponent],
template: `<app-user-card [user]="user" />`,
})
class HostComponent {
user: User = { name: 'Ada' };
}
describe('UserCardComponent in a host', () => {
it('stays stale after mutation and updates after replacement', () => {
const fixture = TestBed.createComponent(HostComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Ada');
fixture.componentInstance.user.name = 'Grace';
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Ada');
fixture.componentInstance.user = { name: 'Grace' };
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Grace');
});
});The host uses default change detection, so it is checked on every detectChanges() call. The child is OnPush, so it follows the reference rule. The test asserts both the stale result after mutation and the fresh result after replacement.
Testing asynchronous updates
For a component that uses the async pipe, markForCheck, or signals, the test has to let the asynchronous source emit, then run change detection. A common pattern uses fakeAsync and tick.
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { ClockTicksComponent } from './clock-ticks.component';
describe('ClockTicksComponent', () => {
it('shows elapsed seconds', fakeAsync(() => {
const fixture = TestBed.createComponent(ClockTicksComponent);
fixture.detectChanges();
tick(0);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('0');
tick(2000);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('2');
fixture.destroy();
}));
});The async pipe marks the component for checking when a value arrives. The call to detectChanges() after tick then renders it. Destroying the fixture at the end unsubscribes the pipe, which stops the repeating timer so fakeAsync does not report pending timers.
Checklist for reliable tests
- Set inputs with
componentRef.setInput, not by assigning to the instance. - Call
detectChanges()once after the setup so the first render happens. - Replace objects with new references when you simulate a parent update.
- Advance asynchronous sources with
tickorawait fixture.whenStable()before asserting. - Use a host component when you want to verify the parent-to-child binding.
Exercise
A test creates an OnPush UserCardComponent, calls fixture.detectChanges(), then runs fixture.componentInstance.user = { name: 'Grace' } and fixture.detectChanges() again. The DOM still shows the old name. Why, and how do you fix the test?
Show answer
Assigning directly to the component instance does not mark the OnPush component for checking, so the second detectChanges() skips its view. Replace the assignment with fixture.componentRef.setInput('user', { name: 'Grace' }) and then call fixture.detectChanges(). Alternatively, bind the input through a host component and replace the host's object reference.
Exercise
In the host component test, why does the child keep showing Ada after user.name = 'Grace', even though the host's detectChanges() ran?
Show answer
The host's binding passes the same object reference, so the OnPush child sees no input change and is not checked. The mutation changed the object's contents but not its reference. Only assigning a new object makes the binding report a change.