Sub topic 1
How Vitest Fits into an Angular Project
Angular’s unit-test builder can use Vitest as its test runner. The runner discovers specs, executes describe and it blocks, and reports Vitest matchers such as toEqual and toHaveBeenCalled. Angular still provides the testing environment through TestBed.
Prerequisites
You should know basic TypeScript, standalone Angular components, templates, dependency injection, and the input() and output() functions. You also need Node.js, npm, and the Angular CLI.
The project’s test target selects Vitest through angular.json:
{
"test": {
"builder": "@angular/build:unit-test",
"options": {
"runner": "vitest"
}
}
}Run the tests from the project directory:
ng testThe CLI compiles the application, starts the configured test runner, and watches for file changes. Use a one-time run in automation when your Angular CLI version supports the corresponding --watch=false option:
ng test --watch=falseThe relationship between the tools is:
Anatomy of a Vitest Test
A Vitest test usually has a suite, a test case, and assertions. describe groups related cases. it states one behavior. expect compares an actual value with a matcher.
import { describe, expect, it } from 'vitest';
describe('calculator', () => {
it('adds two numbers', () => {
expect(2 + 3).toBe(5);
});
});Keep each test focused on behavior that a user or another component depends on. Avoid testing private implementation details unless they represent an important contract.
Creating Components with TestBed
TestBed is Angular’s test injector and component factory. createComponent returns a ComponentFixture, which contains the component instance and its rendered DOM.
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { describe, expect, it } from 'vitest';
@Component({
standalone: true,
template: '<p data-testid="message">Hello</p>',
})
class GreetingComponent {}
describe('GreetingComponent', () => {
it('renders its message', () => {
const fixture = TestBed.createComponent(GreetingComponent);
fixture.detectChanges();
const message = fixture.nativeElement.querySelector(
'[data-testid="message"]',
);
expect(message.textContent).toBe('Hello');
});
});detectChanges() runs Angular’s change detection and updates the template. Later chapters use the fixture to set inputs, trigger events, and inspect rendered output.
Exercise
Which tool creates an Angular component fixture, and which tool provides the describe and expect functions?
Show answer
TestBed creates the fixture. Vitest provides describe and expect.