Full answer
TestBed builds a small Angular environment around the component for a test. The usual steps:
TestBed.configureTestingModule({ imports: [MyComponent], providers: [...] }). A standalone component goes inimports, notdeclarations.TestBed.createComponent(MyComponent)returns aComponentFixturewithcomponentInstanceandnativeElement.- Set inputs through
fixture.componentRef.setInput('name', value). This works for signal inputs and decorator inputs, and it marks the view for checking, which matters for OnPush components. - Run
fixture.detectChanges()(orawait fixture.whenStable()), then checkfixture.nativeElement.
Faking dependencies. Provide a replacement with { provide: AttendanceService, useValue: fake } or useClass. A fake can be a small object, so the test does not depend on HTTP. For HTTP code use provideHttpClient() with provideHttpClientTesting() and the HttpTestingController.
Good practice:
- Test behaviour seen by the user (text, enabled buttons, emitted events), not private fields.
- Query by role or a stable attribute, not by deep CSS paths. Angular's CDK offers component harnesses for this.
- Prefer one assertion topic per test, and name tests as sentences.
- Do not call
detectChangesinside loops. Trigger events withbutton.click()and then detect.
The Angular 20 CLI generates Jasmine and Karma tests by default. Jest and Vitest can be used instead, and experimental Vitest support was added to the CLI. Zoneless components are tested with the same API.
Run the tests with ng test.
typescript
import { Component, Injectable, computed, inject, input } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
@Injectable({ providedIn: 'root' })
export class PolicyService {
minimumPercent(): number {
return 75;
}
}
@Component({
selector: 'app-attendance-badge',
template: `<span class="badge">{{ label() }}</span>`,
})
export class AttendanceBadgeComponent {
percent = input.required<number>();
private readonly policy = inject(PolicyService);
label = computed(() => (this.percent() >= this.policy.minimumPercent() ? 'Eligible' : 'Short'));
}
describe('AttendanceBadgeComponent', () => {
let fixture: ComponentFixture<AttendanceBadgeComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AttendanceBadgeComponent],
providers: [{ provide: PolicyService, useValue: { minimumPercent: () => 80 } }],
}).compileComponents();
fixture = TestBed.createComponent(AttendanceBadgeComponent);
});
it('shows Eligible when attendance meets the policy', () => {
fixture.componentRef.setInput('percent', 85);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.badge').textContent).toBe('Eligible');
});
it('uses the faked policy limit of 80 rather than the real 75', () => {
fixture.componentRef.setInput('percent', 78);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.badge').textContent).toBe('Short');
});
});Angular 20.3 with Jasmine. Type-checked in strict mode and run with `ng test` (Karma, headless Chrome): both specs pass.
Key points
- Standalone components go in `imports`. Fakes go in `providers`.
- `fixture.componentRef.setInput` sets signal inputs correctly.
- Call `fixture.detectChanges()` after changing data, then assert on the DOM.
- Fake the service with `useValue`. Use `provideHttpClientTesting` for HTTP.
Common mistakes
- Setting `fixture.componentInstance.percent = 80` on a signal input. It is read-only. Use `setInput`.
- Forgetting `detectChanges()` and asserting on an empty DOM.
- Testing private implementation details, which makes tests fail after harmless refactors.
Follow-ups
- How do you test an `output()` event?
- What does `await fixture.whenStable()` wait for?
- How would you test an OnPush component that is updated by a signal?
Tips
- Show `setInput`. It shows you know how signal inputs differ from the older style.
- Say what you fake and why. A test should not depend on the network.
- Mention that CDK harnesses make tests resilient to template changes.
Evaluation rubric
- Configures TestBed correctly for a standalone component.
- Uses setInput and detectChanges.
- Fakes dependencies properly.