Full answer
Test setup:
- Provide fakes at the DI level:
{ provide: GradeService, useValue: fake }. A plain object withjasmine.createSpyObjor a small class is enough. Do not mock the component's own methods. - Set inputs through
fixture.componentRef.setInput('name', value). This works with signal inputs, and it triggers change detection like a real parent. Assigning to the property does not work for signal inputs. - Read signals by calling them. Assert on the rendered DOM for behaviour that users see, and on signal values for logic.
Effects: an effect runs during change detection, not at the moment you set a signal. In tests call fixture.detectChanges() (or TestBed.tick(), which replaced TestBed.flushEffects() in v20) and then assert. A root effect created in a service needs TestBed.tick(). If the effect sets another signal, flush again. Prefer testing the visible result over testing that the effect ran.
Time: use fakeAsync and tick(ms) for setTimeout, debounceTime, and timer. flush() runs all pending timers. discardPeriodicTasks() stops interval. For real Promises use await fixture.whenStable(), or flushMicrotasks(). In zoneless apps and for new code, Jasmine's clock (jasmine.clock().install()) or async and await with whenStable can replace fakeAsync, since fakeAsync depends on zone.js.
HTTP: use provideHttpClientTesting() and HttpTestingController rather than spies on HttpClient, and call verify() after each test.
Habits that keep tests stable:
- One behaviour per test, with names that read as a sentence.
- Avoid testing private fields or implementation (call counts of internal methods).
- Reset state: each test gets a fresh
TestBed, so do not share mutable fixtures between tests. - Keep mocks honest: type them (
Pick<GradeService, 'load'>) so that a changed signature breaks the test at compile time. - Do not assert on timing that depends on the real clock.
// file: grade-badge.component.ts
import { Component, computed, effect, inject, input, signal } from '@angular/core';
export class GradeService {
passMark(): number {
return 40;
}
save(_marks: number): void {}
}
@Component({
selector: 'app-grade-badge',
template: `<p data-test="label">{{ label() }}</p>`,
})
export class GradeBadgeComponent {
private readonly grades = inject(GradeService);
readonly marks = input.required<number>();
readonly saved = signal<number | null>(null);
readonly label = computed(() => (this.marks() >= this.grades.passMark() ? 'Pass' : 'Fail'));
constructor() {
effect((onCleanup) => {
const value = this.marks();
const timer = setTimeout(() => {
this.grades.save(value);
this.saved.set(value);
}, 500);
onCleanup(() => clearTimeout(timer));
});
}
}
// file: grade-badge.component.spec.ts
import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { GradeBadgeComponent, GradeService } from './grade-badge.component';
describe('GradeBadgeComponent', () => {
let fixture: ComponentFixture<GradeBadgeComponent>;
let grades: jasmine.SpyObj<Pick<GradeService, 'passMark' | 'save'>>;
beforeEach(() => {
grades = jasmine.createSpyObj('GradeService', ['passMark', 'save']);
grades.passMark.and.returnValue(40);
TestBed.configureTestingModule({ providers: [{ provide: GradeService, useValue: grades }] });
fixture = TestBed.createComponent(GradeBadgeComponent);
});
function label(): string {
return fixture.nativeElement.querySelector('[data-test="label"]').textContent.trim();
}
it('shows Pass at or above the pass mark', () => {
fixture.componentRef.setInput('marks', 40);
fixture.detectChanges();
expect(label()).toBe('Pass');
});
it('shows Fail below the pass mark and updates when the input changes', () => {
fixture.componentRef.setInput('marks', 39);
fixture.detectChanges();
expect(label()).toBe('Fail');
fixture.componentRef.setInput('marks', 80);
fixture.detectChanges();
expect(label()).toBe('Pass');
});
it('saves after a pause and cancels the earlier save when the input changes', fakeAsync(() => {
fixture.componentRef.setInput('marks', 50);
fixture.detectChanges();
tick(300);
fixture.componentRef.setInput('marks', 60);
fixture.detectChanges();
tick(499);
expect(grades.save).not.toHaveBeenCalled();
tick(1);
expect(grades.save).toHaveBeenCalledOnceWith(60);
expect(fixture.componentInstance.saved()).toBe(60);
}));
it('uses the mock pass mark', () => {
grades.passMark.and.returnValue(75);
fixture.componentRef.setInput('marks', 70);
fixture.detectChanges();
expect(label()).toBe('Fail');
TestBed.tick(); // flushes pending root effects, none are left here
});
});Angular 20.3. The spec was run in headless Chrome with `ng test` and all four tests pass.
Key points
- Provide fakes through DI. Type them against the real service.
- `setInput` for signal inputs. `fixture.detectChanges()` or `TestBed.tick()` to flush effects.
- `fakeAsync` with `tick` for timers. HTTP with `HttpTestingController`.
- Assert on visible behaviour. Do not test private details.
Common mistakes
- Assigning to a signal input property directly in the test, which fails.
- Asserting right after `signal.set` without flushing the effect.
- Forgetting `discardPeriodicTasks` or `flush`, leaving timers pending in `fakeAsync`.
Follow-ups
- How would you test a component in a zoneless app?
- How would you test a `resource` that loads from an API?
- How do you decide between a unit test and an integration test?
Tips
- Mention the v20 change from `flushEffects` to `tick`.
- Talk about typing mocks. It shows maintenance thinking.
- Describe what you do not test.
Evaluation rubric
- Uses setInput, DI fakes, and effect flushing correctly.
- Controls time and HTTP properly.
- Shows good testing habits.