Sub topic 10
Testing OnPush Components
This chapter covers how to write unit tests for components that use ChangeDetectionStrategy.OnPush. It assumes you can write basic Angular tests with TestBed and Jasmine or Jest, that you have read the earlier chapters on OnPush triggers, immutable inputs, the async pipe, ChangeDetectorRef and signals, and that you know fakeAsync and tick at a basic level. The examples use the components from those chapters.
Why OnPush changes how you test
A test that passes against a Default component can fail against the same component with OnPush, even though the component code is correct. The cause is the test, not the component.
A ComponentFixture wraps your component in a host view that uses Default change detection. Calling fixture.detectChanges() checks that host view. The OnPush component inside it is only refreshed if Angular has marked it for checking. In a running app, that marking comes from input reference changes, events, the async pipe, markForCheck or signals. In a test, you have to produce one of those triggers on purpose.
If you only assign a property on fixture.componentInstance and call detectChanges(), nothing marks the component. The view stays stale. A test that models real triggers is more useful than one that forces a refresh, because it also checks that the component notifies Angular correctly.
The first detectChanges always renders
A newly created component starts out marked for checking. The first fixture.detectChanges() renders it, whatever its strategy. The problem appears on the second call.
import { TestBed } from '@angular/core/testing';
import { UserCardComponent } from './user-card.component';
describe('UserCardComponent (direct assignment)', () => {
it('stays stale after a second direct assignment', () => {
const fixture = TestBed.createComponent(UserCardComponent);
fixture.componentInstance.user = { name: 'Ada' };
fixture.detectChanges(); // first pass: renders "Ada"
expect(fixture.nativeElement.textContent).toContain('Ada');
fixture.componentInstance.user = { name: 'Grace' };
fixture.detectChanges(); // nothing marked the view, so no refresh
expect(fixture.nativeElement.textContent).toContain('Ada');
});
});The test passes, but it asserts the stale value. Nobody wants that assertion in a real suite. It exists to show the behavior. In a real test you would not assign inputs this way.
Setting inputs with setInput
fixture.componentRef.setInput(name, value) sets an input the same way a parent template binding does, and marks the OnPush view for checking. This is the correct way to drive inputs in a component test.
import { TestBed } from '@angular/core/testing';
import { UserCardComponent } from './user-card.component';
describe('UserCardComponent', () => {
it('updates when the input changes', () => {
const fixture = TestBed.createComponent(UserCardComponent);
fixture.componentRef.setInput('user', { name: 'Ada' });
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Ada');
fixture.componentRef.setInput('user', { name: 'Grace' });
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Grace');
});
});setInput has three advantages over direct assignment:
- It works with signal inputs (
input()andinput.required()), which are read-only and cannot be assigned at all. - It works with aliased inputs, because you pass the public input name.
- It fails loudly if the name is not an input of the component, which catches typos.
The required input user is also set before the first detectChanges(). Rendering a component whose required input has no value is a common source of confusing errors in tests.
Testing through a host component
setInput tests the child in isolation. It does not test what the parent does to produce a new input, such as mutating an object or replacing it. A small host component defined in the spec file covers that case. It also reproduces the mutation pitfall from the reference equality chapter.
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { User, UserCardComponent } from './user-card.component';
@Component({
selector: 'app-test-host',
imports: [UserCardComponent],
template: `<app-user-card [user]="user" />`,
})
class TestHostComponent {
user: User = { name: 'Ada' };
}
describe('UserCardComponent inside a host', () => {
it('ignores mutation but reacts to replacement', () => {
const fixture = TestBed.createComponent(TestHostComponent);
fixture.detectChanges();
const text = () => fixture.nativeElement.querySelector('p').textContent;
expect(text()).toContain('Ada');
fixture.componentInstance.user.name = 'Grace'; // same reference
fixture.detectChanges();
expect(text()).toContain('Ada');
fixture.componentInstance.user = { ...fixture.componentInstance.user }; // new reference
fixture.detectChanges();
expect(text()).toContain('Grace');
});
});The host uses Default detection, so each detectChanges() re-evaluates the [user] binding. The binding passes the same reference after mutation, so the child is skipped. After the spread copy, the reference differs and the child is checked.
A test like this is worth writing when a bug in the parent would be costly. For example, a parent might copy state in a reducer or a service. The host test shows whether that code produces a new reference.
Testing the async pipe
The async pipe marks the component for checking when the Observable emits. To test it, you need to control time and run change detection after each emission. fakeAsync with tick does both.
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { ClockTicksComponent } from './clock-ticks.component';
describe('ClockTicksComponent', () => {
it('shows each emitted value', fakeAsync(() => {
const fixture = TestBed.createComponent(ClockTicksComponent);
fixture.detectChanges(); // subscribes through the async pipe
tick(0); // timer(0, 1000) emits 0
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Seconds elapsed: 0');
tick(1000); // emits 1
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Seconds elapsed: 1');
fixture.destroy(); // unsubscribes, clearing the periodic timer
}));
});Three details matter here:
- The
tickcalls advance the fake clock. Without them the timer never fires. - Each
detectChanges()after atickis needed because the async pipe only marks the view. It does not render it. In a running app a later change detection pass renders it. In a test you are that pass. fixture.destroy()runsngOnDestroyon the pipe, which unsubscribes. Without it,fakeAsyncfails with an error about periodic timers still in the queue. You can also calldiscardPeriodicTasks().
For components that take an Observable from a service, replace the service with a Subject or BehaviorSubject in the test. Then call subject.next(value) followed by fixture.detectChanges(). You do not need fakeAsync when no timers are involved.
Testing markForCheck
A component that subscribes manually and calls markForCheck() is tested the same way. The test advances time, then runs change detection.
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { CounterComponent } from './counter.component';
describe('CounterComponent', () => {
it('increments the view once per second', fakeAsync(() => {
const fixture = TestBed.createComponent(CounterComponent);
fixture.detectChanges(); // runs ngOnInit and starts the interval
expect(fixture.nativeElement.textContent).toContain('Count: 0');
tick(1000);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Count: 1');
tick(2000);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Count: 3');
fixture.destroy(); // takeUntilDestroyed ends the interval
}));
});This test is the one that catches a forgotten markForCheck(). If you remove that line from the component, the count field still changes, but the second assertion fails because the view is never marked. A test that checks only fixture.componentInstance.count would pass and miss the bug. Always assert on the rendered DOM for OnPush components.
Testing signals
Reading a signal in a template tells Angular when the view needs refreshing. In a test, both an event handler and a direct set or update call work.
import { TestBed } from '@angular/core/testing';
import { SignalCounterComponent } from './signal-counter.component';
describe('SignalCounterComponent', () => {
it('renders after a click', () => {
const fixture = TestBed.createComponent(SignalCounterComponent);
fixture.detectChanges();
fixture.nativeElement.querySelector('button').click();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Count: 1');
});
it('renders after the signal is set directly', () => {
const fixture = TestBed.createComponent(SignalCounterComponent);
fixture.detectChanges();
fixture.componentInstance.count.set(5);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Count: 5');
});
});The second test is the difference from plain fields. Assigning a plain property directly would leave the view stale. Setting a signal that the template reads does not. This is the behavior you want to lock in, so keep the second test if the component relies on signals instead of events.
Choosing a way to trigger an update
| Situation | What to do in the test | Why |
|---|---|---|
| Test one component's inputs | `componentRef.setInput()` then `detectChanges()` | Marks the view, works with signal inputs |
| Test how a parent produces inputs | Host component, then mutate or replace and `detectChanges()` | Exercises the real binding and the reference check |
| Observable with async pipe | Emit or `tick`, then `detectChanges()` | The pipe marks the view, the test runs the pass |
| Manual subscription | Emit or `tick`, then `detectChanges()` | Proves the component calls `markForCheck()` |
| Signal state | `set`, `update`, or a DOM event, then `detectChanges()` | The template read registers the dependency |
| User interaction | Dispatch a DOM event, then `detectChanges()` | Events inside the component mark it |
Common mistakes in OnPush tests
- Assigning inputs directly after the first render. The first render works, then later assertions fail or, worse, quietly assert stale text. Use
setInput. - Skipping the final
detectChanges(). An emission or atickchanges the model. It does not update the DOM. Run change detection before asserting. - Asserting on fields instead of the DOM. A forgotten
markForCheck()is invisible to a test that only readscomponentInstance. - Leaving subscriptions and timers alive in
fakeAsync. Destroy the fixture or calldiscardPeriodicTasks(). - Relying on
autoDetectChanges()to fix staleness. It runs change detection automatically, but an unmarked OnPush view is still skipped, so the stale behavior stays. - Mutating shared fixtures between tests. Create objects inside each test or in
beforeEach. A mutated shared object makes reference-equality tests order-dependent.
Exercises
Exercise
A test creates UserCardComponent, calls fixture.detectChanges(), then runs fixture.componentInstance.user = { name: 'Linus' } and fixture.detectChanges() again. It expects to see "Linus" but still sees the old name. Why, and what is the minimal fix?
Show answer
The component uses OnPush and the fixture's host view is not marked dirty by a direct property assignment, so the second detectChanges() skips the component's view. Replace the assignment with fixture.componentRef.setInput('user', { name: 'Linus' }), which marks the view for checking, then call detectChanges().
Exercise
You test CounterComponent, which increments count from a manual subscription. The test calls tick(1000) and asserts fixture.componentInstance.count === 1. It passes even after someone deletes this.cdr.markForCheck(). How do you change the test so it catches that regression?
Show answer
Call fixture.detectChanges() after tick(1000) and assert on the rendered text, for example expect(fixture.nativeElement.textContent).toContain('Count: 1'). Without markForCheck() the OnPush view is not refreshed, so the DOM assertion fails. Finish with fixture.destroy() so the interval is cleaned up.
Exercise
In a host-component test, you set host.user.name = 'Grace' and call fixture.detectChanges(). The child still shows "Ada". Is this a bug in the test, and what does this behavior demonstrate?
Show answer
It is not a bug in the test. The host binding passes the same object reference, so the OnPush child is not checked. This is the expected behavior and shows why OnPush inputs need immutable updates. Assigning a copy such as host.user = { ...host.user, name: 'Grace' } produces a new reference and the child updates.