Sub topic 16
Testing lifecycle behavior with TestBed
This chapter assumes you can write a basic Jasmine or Jest test (describe, it, expect) and know the hook order from the earlier chapters. The examples use only matchers that exist in both frameworks. Here you will drive lifecycle hooks from tests, using TestBed and ComponentFixture.
What TestBed does and does not run
TestBed.createComponent() instantiates the component and its template nodes, so the constructor runs. It does not run change detection. Most hooks fire during change detection, so they stay silent until the test asks for it.
| Test step | What Angular runs |
|---|---|
| `TestBed.createComponent(C)` | Constructor, with inputs unset |
| `fixture.componentRef.setInput(...)` | Records the input and marks the component for checking. `ngOnChanges` waits for the next `detectChanges()`. |
| First `fixture.detectChanges()` | `ngOnChanges` (if inputs were set through bindings or `setInput`), `ngOnInit`, `ngDoCheck`, the content hooks, the view hooks |
| Later `fixture.detectChanges()` | `ngOnChanges` for changed inputs, `ngDoCheck`, the checked hooks |
| `fixture.destroy()` | `ngOnDestroy` and `DestroyRef` callbacks |
A component to test
This component records what its hooks do, so a test can assert on plain properties.
import { Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-greeting',
standalone: true,
template: `<p>{{ label }}</p>`,
})
export class GreetingComponent implements OnChanges, OnInit, OnDestroy {
@Input() name = '';
label = '';
initCount = 0;
destroyed = false;
changeLog: string[] = [];
ngOnChanges(changes: SimpleChanges): void {
const change = changes['name'];
if (change) {
this.label = `Hello, ${change.currentValue}`;
this.changeLog.push(`${change.firstChange}:${change.currentValue}`);
}
}
ngOnInit(): void {
this.initCount++;
}
ngOnDestroy(): void {
this.destroyed = true;
}
}Testing initialization, input changes and destruction
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { GreetingComponent } from './greeting.component';
describe('GreetingComponent lifecycle', () => {
let fixture: ComponentFixture<GreetingComponent>;
let component: GreetingComponent;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [GreetingComponent] });
fixture = TestBed.createComponent(GreetingComponent);
component = fixture.componentInstance;
});
it('runs ngOnInit once, on the first detectChanges', () => {
expect(component.initCount).toBe(0);
fixture.detectChanges();
expect(component.initCount).toBe(1);
fixture.detectChanges();
expect(component.initCount).toBe(1);
});
it('calls ngOnChanges when the input is set with setInput', () => {
fixture.componentRef.setInput('name', 'Ada');
fixture.detectChanges();
expect(component.changeLog).toEqual(['true:Ada']);
expect(fixture.nativeElement.textContent).toContain('Hello, Ada');
fixture.componentRef.setInput('name', 'Grace');
fixture.detectChanges();
expect(component.changeLog).toEqual(['true:Ada', 'false:Grace']);
});
it('does not call ngOnChanges when the property is assigned directly', () => {
component.name = 'Ada';
fixture.detectChanges();
expect(component.changeLog).toEqual([]);
expect(component.label).toBe('');
});
it('calls ngOnDestroy when the fixture is destroyed', () => {
fixture.detectChanges();
fixture.destroy();
expect(component.destroyed).toBe(true);
});
});The third test passes, and it shows the most common mistake in lifecycle tests.
setInput is not the only route. You can also create a small host component whose template contains <app-greeting [name]="who" />. Use a host when you want to test the component the way a parent really uses it, including the binding.
Spying on hooks
Avoid spyOn(component, 'ngOnInit') after createComponent. Angular reads hook methods from the class prototype when it registers the component, so an instance-level spy is often never called. Two reliable choices are:
- Assert on effects, as the tests above do (
initCount,label, the DOM). - Spy on the prototype before creating the component:
spyOn(GreetingComponent.prototype, 'ngOnInit')in Jasmine, orjest.spyOn(GreetingComponent.prototype, 'ngOnInit')in Jest.
Effect-based assertions survive refactoring better, because they do not depend on which hook does the work.
Testing view hooks
View hooks run after the template has been created, so a test only needs to call detectChanges(). This test checks FocusInputComponent from the earlier chapter.
import { TestBed } from '@angular/core/testing';
import { FocusInputComponent } from './focus-input.component';
describe('FocusInputComponent', () => {
it('focuses the input in ngAfterViewInit', () => {
TestBed.configureTestingModule({ imports: [FocusInputComponent] });
const fixture = TestBed.createComponent(FocusInputComponent);
fixture.detectChanges();
const input: HTMLInputElement = fixture.nativeElement.querySelector('input');
expect(document.activeElement).toBe(input);
});
});TestBed attaches the fixture's root element to the document, which is why document.activeElement can see it.
Testing cleanup with fakeAsync
Leaks are a lifecycle bug that is easy to miss by hand. fakeAsync replaces real timers with a virtual clock, so you can run three seconds of interval instantly and check that nothing runs after destruction. This test uses TickerComponent, which cleans up with takeUntilDestroyed.
import { TestBed, fakeAsync, tick } from '@angular/core/testing';
import { TickerComponent } from './ticker.component';
describe('TickerComponent cleanup', () => {
beforeEach(() => {
TestBed.configureTestingModule({ imports: [TickerComponent] });
});
it('stops ticking after the component is destroyed', fakeAsync(() => {
const fixture = TestBed.createComponent(TickerComponent);
fixture.detectChanges();
tick(3000);
expect(fixture.componentInstance.ticks).toBe(3);
fixture.destroy();
tick(3000);
expect(fixture.componentInstance.ticks).toBe(3);
}));
});This works as a leak detector for two reasons. fakeAsync throws an error such as 1 periodic timer(s) still in the queue if a timer is still pending when the test ends. If you delete the cleanup from the component, this test fails.
The same test works for ClockComponent, which unsubscribes in ngOnDestroy. The test checks behavior and does not care which cleanup mechanism the component uses.
Testing render hooks
afterNextRender and afterRender belong to the application's render cycle, not to a single component check. fixture.detectChanges() is usually enough to flush them. If a callback has not run when you assert, add await fixture.whenStable() to an async test. The exact behavior has changed between Angular versions, so confirm it in your version.
The callbacks are registered from an injection context. For MeasureComponent that context is the constructor, so you do not need extra setup. Server-side rendering skips these hooks, and a test environment such as jsdom or a real browser runs them. A render hook that works in your tests can still be skipped on the server. Test the server path with an SSR-specific test, not with TestBed alone.
Testing the error case
Fixtures run change detection with a second "no changes" pass by default. That pass is the same check that throws ExpressionChangedAfterItHasBeenCheckedError in development, so a test can catch the bug.
import { AfterViewInit, Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
@Component({
selector: 'app-bad',
standalone: true,
template: `<p>{{ value }}</p>`,
})
class BadComponent implements AfterViewInit {
value = 'before';
ngAfterViewInit(): void {
this.value = 'after';
}
}
describe('BadComponent', () => {
it('reports ExpressionChangedAfterItHasBeenChecked', () => {
TestBed.configureTestingModule({ imports: [BadComponent] });
const fixture = TestBed.createComponent(BadComponent);
expect(() => fixture.detectChanges()).toThrowError(/NG0100|ExpressionChanged/);
});
});Do not call detectChanges(false) to silence this error in a test. That turns off the check and hides a bug that will show up in the application.
Testing hook order between parent and child
To test interleaving, give both components a shared logging service and compare the log.
import { AfterViewInit, Component, Injectable, OnInit, inject } from '@angular/core';
import { TestBed } from '@angular/core/testing';
@Injectable({ providedIn: 'root' })
class HookLog {
readonly entries: string[] = [];
}
@Component({ selector: 'app-child', standalone: true, template: `<span>child</span>` })
class ChildComponent implements OnInit, AfterViewInit {
private log = inject(HookLog);
ngOnInit(): void { this.log.entries.push('child:init'); }
ngAfterViewInit(): void { this.log.entries.push('child:viewInit'); }
}
@Component({
selector: 'app-host',
standalone: true,
imports: [ChildComponent],
template: `<app-child />`,
})
class HostComponent implements OnInit, AfterViewInit {
private log = inject(HookLog);
ngOnInit(): void { this.log.entries.push('host:init'); }
ngAfterViewInit(): void { this.log.entries.push('host:viewInit'); }
}
describe('parent and child order', () => {
it('initializes the parent first and finishes its view last', () => {
TestBed.configureTestingModule({ imports: [HostComponent] });
const fixture = TestBed.createComponent(HostComponent);
fixture.detectChanges();
expect(TestBed.inject(HookLog).entries).toEqual([
'host:init',
'child:init',
'child:viewInit',
'host:viewInit',
]);
});
});TestBed creates a fresh injector for every test, so HookLog starts empty each time.
Common testing mistakes
- Expecting
ngOnInitright aftercreateComponent. It needs the firstdetectChanges(). - Assigning inputs directly instead of using
setInput, then wondering whyngOnChangesis silent. - Calling
detectChanges()inbeforeEachand then trying to set the initial inputs. The first pass has already run, songOnInitsaw the old values. - Asserting on a destroyed fixture's DOM. After
destroy(), the view is gone, so check component state or side effects instead. - Using real timers for cleanup tests. They make the test slow and can leave timers running in other tests.
Exercise
A test sets fixture.componentInstance.name = 'Ada', calls fixture.detectChanges(), and expects ngOnChanges to have recorded the change. It records nothing. Why, and how do you fix the test?
Show answer
Angular calls ngOnChanges only when it updates an input through a binding. Assigning the property directly bypasses that mechanism, so no SimpleChanges object is created. Replace the assignment with fixture.componentRef.setInput('name', 'Ada'), then call fixture.detectChanges(). Alternatively, test through a host component that binds [name] in its template.
Exercise
You write ClockComponent tests with fakeAsync. You call fixture.detectChanges(), tick(2000), and then end the test without calling fixture.destroy(). What happens, and why is that useful?
Show answer
fakeAsync throws an error saying a periodic timer is still in the queue, because the interval subscription is still active. This shows that something must stop the timer. Add fixture.destroy() at the end of the test, or call discardPeriodicTasks() if you do not care about cleanup in that particular test.