← Back to Angular, page 2

angular-0032 · Medium mid

How do you unit test an Angular component with TestBed, including signal inputs and a faked service?

Configure TestBed with the standalone component in imports and fakes in providers, create the fixture, set inputs with fixture.componentRef.setInput, run change detection, and assert on the rendered DOM. Replace real services with simple fake objects so the test checks one unit.

Full answer

TestBed builds a small Angular environment around the component for a test. The usual steps:

  1. TestBed.configureTestingModule({ imports: [MyComponent], providers: [...] }). A standalone component goes in imports, not declarations.
  2. TestBed.createComponent(MyComponent) returns a ComponentFixture with componentInstance and nativeElement.
  3. 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.
  4. Run fixture.detectChanges() (or await fixture.whenStable()), then check fixture.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 detectChanges inside loops. Trigger events with button.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.