Unit Testing Components with TestBed and Vitest

Angular 16 min min read Updated: Nov 16, 2026 Intermediate
Unit Testing Components with TestBed and Vitest
Intermediate Topic 1 of 3

Why Test?

  • Find bugs before users do
  • Change code with confidence
  • Tests describe how the code should behave
Test runner: Angular CLI projects since v21 use Vitest by default, while older projects use Jasmine and Karma. The test API (describe, it, expect) is almost the same, so these examples work for both. Differences are mostly in mocks (vi.fn() in Vitest and jasmine.createSpy() in Jasmine).
bash g test # run tests in watch mode ng test --no-watch # run once (useful for CI) ng test --code-coverage

A Component to Test

typescript @Component({ selector: 'app-counter', template: ` <h2>{{ label() }}</h2> <p data-testid="value">{{ count() }}</p> <button data-testid="inc" (click)="inc()">+</button> <button data-testid="dec" (click)="dec()" [disabled]="count() === 0">-</button> `, }) export class Counter { label = input('Counter'); count = signal(0); inc() { this.count.update(c => c + 1); } dec() { this.count.update(c => c - 1); } }

The Test File

typescript import { ComponentFixture, TestBed } from '@angular/core/testing'; import { Counter } from './counter'; describe('Counter', () => { let fixture: ComponentFixture<Counter>; let el: HTMLElement; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [Counter] }).compileComponents(); fixture = TestBed.createComponent(Counter); el = fixture.nativeElement; await fixture.whenStable(); }); const text = (id: string) => el.querySelector(`[data-testid="${id}"]`)!.textContent!.trim(); const click = (id: string) => (el.querySelector(`[data-testid="${id}"]`) as HTMLButtonElement).click(); it('should create', () => { expect(fixture.componentInstance).toBeTruthy(); }); it('starts at 0 and shows the default label', () => { expect(text('value')).toBe('0'); expect(el.querySelector('h2')!.textContent).toContain('Counter'); }); it('increments when + is clicked', async () => { click('inc'); click('inc'); await fixture.whenStable(); // let Angular update the screen expect(text('value')).toBe('2'); }); it('disables the minus button at 0', () => { const btn = el.querySelector('[data-testid="dec"]') as HTMLButtonElement; expect(btn.disabled).toBe(true); }); it('uses a custom label from input()', async () => { fixture.componentRef.setInput('label', 'Likes'); // the way to set signal inputs await fixture.whenStable(); expect(el.querySelector('h2')!.textContent).toContain('Likes'); }); });
Update the view: After changing state, wait for the screen to update with await fixture.whenStable() (works in zoneless and zone-based apps) or call fixture.detectChanges() in older style tests.

Mock a Service

typescript describe('UserList', () => { const fakeService = { getUsers: vi.fn().mockReturnValue(of([{ id: 1, name: 'Ann' }, { id: 2, name: 'Bob' }])), }; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [UserList], providers: [{ provide: UserService, useValue: fakeService }], }).compileComponents(); }); it('shows users from the service', async () => { const fixture = TestBed.createComponent(UserList); await fixture.whenStable(); const rows = fixture.nativeElement.querySelectorAll('li'); expect(rows.length).toBe(2); expect(rows[0].textContent).toContain('Ann'); expect(fakeService.getUsers).toHaveBeenCalledTimes(1); }); });

Test an Output

typescript it('emits when saved', () => { const fixture = TestBed.createComponent(EditForm); const spy = vi.fn(); fixture.componentInstance.saved.subscribe(spy); // output() supports subscribe fixture.componentInstance.save(); expect(spy).toHaveBeenCalledWith(expect.objectContaining({ name: 'Ann' })); });

Routing and Router in Tests

typescript providers: [provideRouter([])] // minimal router for components with routerLink

Good Habits

  • Test behavior (what the user sees), not private details
  • Use data-testid attributes for stable selectors
  • One idea per test with a clear name
  • Do not call real APIs; mock services
  • Keep tests fast and independent

Conclusion

Use TestBed to create a component, setInput to give inputs, click real buttons, wait with whenStable and mock services with test doubles. Vitest is the default runner in new CLI projects.

Quick Summary: TestBed + createComponent + setInput + click + whenStable + mocks.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators