Sub topic 16
Testing lifecycle behavior with TestBed
This chapter assumes you can write a basic Jasmine or Jest spec, know how TestBed configures a testing module, and have read the earlier chapters on ngOnChanges, ngOnInit and ngOnDestroy. The examples use Jasmine, the Angular default. Jest's jest.spyOn works the same way.
Who triggers the hooks in a test
In a running app, Angular's change detection calls the hooks. In a test, you control when that happens:
TestBed.createComponent()runs the constructor only. No hook has run yet.- The first
fixture.detectChanges()runsngOnChanges(if inputs are bound) andngOnInit, then the content and view hooks. fixture.destroy()runsngOnDestroy.
Spy on the prototype, not the instance
Angular reads hook methods from the class prototype when it creates the component. If you call spyOn(fixture.componentInstance, 'ngOnInit') after creation, Angular still calls the original method. Install spies on the prototype before createComponent. Jasmine restores them after each spec.
import { TestBed } from '@angular/core/testing';
import { UserCardComponent } from './user-card.component';
describe('UserCardComponent lifecycle', () => {
beforeEach(() => {
TestBed.configureTestingModule({ imports: [UserCardComponent] });
});
it('runs ngOnInit on the first detectChanges, not before', () => {
const initSpy = spyOn(UserCardComponent.prototype, 'ngOnInit');
const fixture = TestBed.createComponent(UserCardComponent);
expect(initSpy).not.toHaveBeenCalled();
fixture.detectChanges();
expect(initSpy).toHaveBeenCalledTimes(1);
});
it('reports input changes through ngOnChanges', () => {
const changesSpy = spyOn(UserCardComponent.prototype, 'ngOnChanges');
const fixture = TestBed.createComponent(UserCardComponent);
fixture.componentRef.setInput('userId', '42');
fixture.detectChanges();
const changes = changesSpy.calls.mostRecent().args[0];
expect(changes['userId'].currentValue).toBe('42');
expect(changes['userId'].firstChange).toBeTrue();
});
it('runs ngOnDestroy when the fixture is destroyed', () => {
const destroySpy = spyOn(UserCardComponent.prototype, 'ngOnDestroy');
const fixture = TestBed.createComponent(UserCardComponent);
fixture.detectChanges();
fixture.destroy();
expect(destroySpy).toHaveBeenCalledTimes(1);
});
});Set inputs with setInput
Assigning fixture.componentInstance.userId = '42' changes the property but does not call ngOnChanges. Angular only builds SimpleChanges when a binding in a parent template updates an input. fixture.componentRef.setInput() goes through the same path as a binding, so ngOnChanges fires on the next detectChanges(). It also marks an OnPush component for checking.
Verify cleanup with fakeAsync
A cleanup test should show that work stops after destruction. Use fakeAsync and tick to move a fake clock forward without waiting. This test uses the ClockComponent from the cleanup chapter.
import { fakeAsync, tick, TestBed } from '@angular/core/testing';
import { ClockComponent } from './clock.component';
describe('ClockComponent cleanup', () => {
it('stops counting after destroy', fakeAsync(() => {
TestBed.configureTestingModule({ imports: [ClockComponent] });
const fixture = TestBed.createComponent(ClockComponent);
fixture.detectChanges();
tick(2000);
expect(fixture.componentInstance.seconds).toBe(2);
fixture.destroy();
tick(3000);
expect(fixture.componentInstance.seconds).toBe(2);
}));
});If ngOnDestroy forgot to unsubscribe, the count would keep rising. fakeAsync would also fail the spec with an error about periodic timers still in the queue.
Common mistakes in lifecycle tests
- Forgetting the first
fixture.detectChanges(), then wondering whyngOnInitnever ran. - Spying on the instance instead of the prototype.
- Assigning inputs directly and expecting
ngOnChanges. - Testing render hooks such as
afterNextRenderwithout callingfixture.detectChanges(). Those callbacks run as part of rendering.
Exercise
A spec calls fixture.componentInstance.userId = '7' and then fixture.detectChanges(), and it expects ngOnChanges to have been called with a userId change. The expectation fails. What is wrong, and how do you fix it?
Show answer
Assigning the property directly bypasses Angular's input binding, so no SimpleChanges object is created and ngOnChanges does not run. Replace the assignment with fixture.componentRef.setInput('userId', '7') and then call fixture.detectChanges(). Also make sure any ngOnChanges spy is installed on UserCardComponent.prototype before createComponent.