Open this when wiring a suite: the builder options, the Vitest overrides, MSW, coverage and the shared render helper. Verified 2026-09 against https://angular.dev/guide/testing and https://angular.dev/guide/testing/migrating-to-vitest.
1. The @angular/build:unit-test builder
Vitest is the default runner for new Angular CLI projects. In angular.json:
"test": {
"builder": "@angular/build:unit-test",
"options": {
"include": ["src/**/*.spec.ts"],
"exclude": ["src/**/*.e2e.spec.ts"],
"setupFiles": ["src/testing/setup.ts"],
"providersFile": "src/testing/providers.ts",
"coverage": true
}
}
| Option | What it does |
|---|---|
include / exclude |
Glob patterns selecting spec files |
setupFiles |
Run before the suite — MSW server, custom matchers, global mocks |
providersFile |
Exports providers applied to every TestBed — the one place to put app-wide test providers |
coverage |
Enables coverage reporting |
browsers |
Run in real browsers (e.g. ["chromium"]) instead of jsdom |
tsConfig defaults to tsconfig.spec.json and buildTarget to ::development; set them only when your project differs.
jsdom or a real browser? jsdom is faster and enough for logic, roles, text and events. Switch a subset of specs to browsers: ["chromium"] when the assertion depends on real layout (element sizes, scroll position, IntersectionObserver), real focus behaviour, or Shadow DOM. Running the whole suite in a browser to fix three specs costs minutes on every push.
2. providersFile — the app-wide test defaults
// src/testing/providers.ts
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { provideRouter } from '@angular/router';
import { provideLocationMocks } from '@angular/common/testing';
export default [
provideHttpClient(),
provideHttpClientTesting(),
provideRouter([]),
provideLocationMocks(),
];
On v20, add provideZonelessChangeDetection() here so tests run in the same mode as production. On v21+ new projects zone.js is not loaded at all, so TestBed is already zoneless and the provider is unnecessary.
3. A shared render helper
// src/testing/render.ts
import { render, type RenderComponentOptions } from '@testing-library/angular';
import type { Type } from '@angular/core';
import { APP_CONFIG } from '../app/core/config/app-config';
export function renderPage<T>(component: Type<T>, options: RenderComponentOptions<T> = {}) {
return render(component, {
...options,
providers: [
{ provide: APP_CONFIG, useValue: { apiBaseUrl: '/api', environment: 'dev', features: {} } },
...(options.providers ?? []),
],
});
}
One helper, imported by every component spec. When a cross-cutting provider changes, one file changes instead of two hundred.
4. MSW when the mocks must be shared
Use HttpTestingController when the test is about the request (method, URL, body, headers). Use MSW when the same handlers should serve unit tests, Storybook and the dev server — one definition of "what the API returns".
// src/testing/setup.ts
import { afterAll, afterEach, beforeAll } from 'vitest';
import { setupServer } from 'msw/node';
import { handlers } from './handlers';
export const server = setupServer(...handlers);
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
onUnhandledRequest: 'error' is the important flag: without it a typo'd URL silently returns nothing and the test fails somewhere unrelated, ten minutes of debugging later.
Do not mix both in one spec. provideHttpClientTesting() intercepts before the request ever reaches the network layer MSW patches, so the MSW handler never runs and the failure is confusing.
5. Coverage
Enable coverage in the builder options, and set the threshold on changed files, not on the whole repository. A repo-wide 80 % gate on a legacy codebase is either permanently red or permanently ignored; a gate on the diff moves the number in the right direction on every PR.
Coverage is a smoke detector, not a goal. A file at 100 % whose assertions are expect(component).toBeTruthy() is worse than one at 60 % with real assertions, because it reports safety that is not there.
6. Jest projects
jest-preset-angular remains viable. Do not migrate a green, fast Jest suite for its own sake — there is no behaviour difference worth the churn. Migrate when you are already touching the build, when Jest's ESM handling is costing time, or when the suite is slow enough to change behaviour on the team.
Translation table if you do move: jest.fn → vi.fn, jest.spyOn → vi.spyOn, jest.mock → vi.mock, jest.useFakeTimers → vi.useFakeTimers, jest.config.ts setupFilesAfterEnv → the builder's setupFiles.
7. Speed
- Most of an Angular suite's time is TestBed compilation. Fewer, larger component tests beat many tiny ones that each rebuild the same module graph.
- Keep
beforeEachcheap: build fixtures as plain object literals rather than through builders that hit the injector. - Run in parallel (Vitest does by default) and make that safe by never sharing mutable module-level state between specs. A root-provided service holding state is the usual culprit — provide it on the component or reset it in
afterEach. - Tag and split: a fast unit project on every push, the browser-mode subset and end-to-end on the merge queue.