Design and write tests for Angular code — Vitest via the `@angular/build:unit-test` builder, component tests with Angular Testing Library and TestBed, CDK component harnesses, `HttpTestingController`, signals, Signal Forms, `httpResource`/`resource`, NgRx SignalStore, guards, interceptors and pipes, plus Playwright end-to-end journeys.
When agents use itUse this whenever the user asks how to test an Angular component, service, store, form, guard, interceptor or pipe, writes a `.spec.ts`, sets up `angular.json` `test` options or `vitest.config.ts`, asks about `TestBed.tick()`, `fixture.whenStable()`, `provideHttpClientTesting()`, `render` from `@testing-library/angular`, `MatDialogHarness`, `fakeAsync` under zoneless, or a flaky or slow Angular suite. Also use it when the user asks "what should I test" for Angular code they just wrote.
Install
Copilot (VS Code, Visual Studio, Copilot CLI and github.com) reads skills from the repository — commit them so the whole team gets them.
npx skills add AGCO-Global/org-skills --skill angular-testing -a github-copilot
# or with the org installer (adds .github/skills/angular-testing):
npx -y github:AGCO-Global/org-skills add skill angular-testing
Uses the open skills CLI. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, OpenCode, Windsurf and 60+ others — it asks which agent to install into.
Installs the frontend-angular-skills plugin, which bundles all Frontend / Angular skills and keeps them updated.
/plugin marketplace add AGCO-Global/org-skills
/plugin install frontend-angular-skills@org-skills
# or just this skill, in this repository:
npx skills add AGCO-Global/org-skills --skill angular-testing -a claude-code
Use Download .zip above, then upload it under Customize → Skills → Upload skill. Team and Enterprise admins can sync this repo as a plugin marketplace instead.
Installs into .agents/skills/, which Codex reads.
npx skills add AGCO-Global/org-skills --skill angular-testing -a codex
Installs into Cursor's skills folder.
npx skills add AGCO-Global/org-skills --skill angular-testing -a cursor
Installs into Gemini CLI's skills folder.
npx skills add AGCO-Global/org-skills --skill angular-testing -a gemini-cli
Nothing to install. Press Download .zip above, unzip it, and drop the angular-testing folder into your tool's skills folder — .claude/skills/, .github/skills/, .cursor/skills/ or .agents/skills/. Step-by-step, per tool: How to use it. For any other tool with rules or custom prompts, Copy SKILL.md and paste it in — it is plain Markdown.
The npx commands need Node.js 20+ and use your normal git sign-in to GitHub, so they work while the repository is private. Without Node.js, see the No Node.js tab — a skill is a folder of Markdown, so copying it in works just as well.
Test the public surface: what renders, what the user can do, which requests go out, where navigation lands. A test that reads a private signal or a component's internal method passes forever and protects nothing. The corollary is that most Angular tests should render something.
1. Decide first
Question
Default
Change when
Runner
Vitest via @angular/build:unit-test — the CLI default since v21
Existing Jest setup that is green and fast → leave it. Karma is still supported but no longer default; plan the move with angular-migration
Environment
jsdom
Testing layout, scroll, real focus or Shadow DOM → browsers: ["chromium"] in the test options
Component tests
render() from @testing-library/angular + role queries
The component is a thin wrapper over Material → CDK harnesses (MatDialogHarness, MatSelectHarness) read better
Change detection in tests
await fixture.whenStable()
Flushing effects or a signal-driven update inside a synchronous test → TestBed.tick(). Never detectChanges() in a loop
HTTP
provideHttpClient() + provideHttpClientTesting(), assert with HttpTestingController
The same mocks must also serve Storybook and e2e → MSW handlers in setupFiles
Children
Render them for real
Heavy (chart, map, editor) or side-effecting → a stub component with the same selector and input()s
Timers
vi.useFakeTimers()
Only zone.js-based projects can use fakeAsync/tick; it throws without zone-testing.js
Query by role and accessible name. A test that cannot find the button by its name has found a real accessibility bug.
inputs: { id: '42' } sets signal inputs, including route-bound ones; aliasedInput('alias', value) when the input is aliased; rerender({ inputs, partialUpdate: true }) to change one input and keep the rest. componentInputs/componentOutputs are deprecated — do not copy them from older examples.
Outputs: on: { save: vi.fn() } in the render options, then assert the payload.
await fixture.whenStable() after anything asynchronous; TestBed.tick() when you need effects and pending template work flushed synchronously. TestBed.flushEffects() is deprecated in favour of tick().
4. The rest of the surface
Services and signals:TestBed.inject(Service), call methods, assert service.items(). computed() is synchronous — no awaiting. Functions using inject() run under TestBed.runInInjectionContext(() => …).
httpResource/resource: drive them through HttpTestingController.expectOne(...).flush(...), await fixture.whenStable(), then assert value(), isLoading(), error(), hasValue().
Signal Forms: type into the real inputs with userEvent, assert the visible error message, and assert f.email().invalid() / f().valid() when the form state is the component's public API.
SignalStore:TestBed.inject(OrdersStore) with mocked API providers; call the store's methods and assert its state signals and computeds. To seed protected state directly, patchState(unprotected(store), …) with unprotected from @ngrx/signals/testing.
Guards and interceptors:TestBed.runInInjectionContext(() => authGuard(route, state)) asserting true or a UrlTree; interceptors via provideHttpClient(withInterceptors([authInterceptor])) and assertions on the captured request headers.
Material components:TestbedHarnessEnvironment.loader(fixture) then loader.getHarness(MatDialogHarness) — harnesses wait for stability themselves, which removes most dialog and overlay flake.
Full recipes for harnesses, @defer blocks, RouterTestingHarness, Signal Forms and stores: references/component-and-store-tests.md. Runner options, vitest.config.ts, MSW and coverage: references/runner-and-setup.md. Playwright, Storybook and accessibility assertions: references/e2e-and-visual.md.
5. Deliverable format
## Behaviours — the observable list: initial render, each input variation, each action, each output, loading/empty/error, a11y roles
## Tests — one `it` per behaviour, sentence-style name, arrange/act/assert, no shared mutable state
## Gaps — what is deliberately not covered and why (e.g. covered by an e2e journey)
## Run — the command, and the result
Checklist
Every test queries by role or label, not by CSS class or data-testid without a reason
No detectChanges() loop; await fixture.whenStable() or TestBed.tick() instead
No fakeAsync/tick unless the project still loads zone.js/testing
HttpTestingController.verify() runs in afterEach; no unexpected requests
Children render for real unless heavy or side-effecting, and any stub is named as such
Assertions are on rendered output, emitted outputs, requests or navigation — not private members
Each bug fix ships a test that fails without the fix
Tests pass when the file is run alone and when the suite is run in a random order
No TestBed.flushEffects(), componentInputs, componentOutputs or NO_ERRORS_SCHEMA by default
Anti-patterns
detectChanges() called repeatedly until the assertion passes → await fixture.whenStable(); repeated calls hide an imperative update that production will not perform.
fakeAsync in a zoneless project → it throws "zone-testing.js is needed"; use vi.useFakeTimers() or await stability.
NO_ERRORS_SCHEMA to silence unknown elements → import the child, or stub it explicitly; the schema also hides genuine typos in selectors and bindings.
Asserting on a component's private signal via componentInstance → assert what the template renders; the private field is free to change.
TestBed.overrideComponent stubbing every child → then the test proves only that the parent compiles.
Mocking your own services in a component test → mock at the network boundary so the real wiring is exercised.
A waitFor with a 10-second timeout → find the actual signal to await; a long timeout converts a failure into a slow failure.
Snapshot of a whole rendered component → assert the two things the test is about; whole-tree snapshots get re-recorded on every change.
references/component-and-store-tests.md — CDK harnesses, @defer block testing, RouterTestingHarness, Signal Forms, resources, SignalStore and NgRx Store
references/e2e-and-visual.md — Playwright journeys and toHaveScreenshot, Storybook play functions, automated accessibility assertions
version-notes.md in ../angular-development/references/ — what is default in v20, v21 and v22
Siblings: angular-development (the code under test), angular-migration (Karma → Vitest), angular-performance, frontend-code-review
---
name: angular-testing
description: Design and write tests for Angular code — Vitest via the `@angular/build:unit-test` builder, component tests with Angular Testing Library and TestBed, CDK component harnesses, `HttpTestingController`, signals, Signal Forms, `httpResource`/`resource`, NgRx SignalStore, guards, interceptors and pipes, plus Playwright end-to-end journeys. Use this whenever the user asks how to test an Angular component, service, store, form, guard, interceptor or pipe, writes a `.spec.ts`, sets up `angular.json` `test` options or `vitest.config.ts`, asks about `TestBed.tick()`, `fixture.whenStable()`, `provideHttpClientTesting()`, `render` from `@testing-library/angular`, `MatDialogHarness`, `fakeAsync` under zoneless, or a flaky or slow Angular suite. Also use it when the user asks "what should I test" for Angular code they just wrote.
metadata:
technology: Angular
type: testing
---
# Angular Testing
> **Targets:** Angular 22 (LTS 20 and 21 noted where different) · **Verified:** 2026-09 against https://angular.dev/guide/testing, https://angular.dev/guide/zoneless, https://angular.dev/api/core/testing/TestBed, https://testing-library.com/docs/angular-testing-library/api
Test the public surface: what renders, what the user can do, which requests go out, where navigation lands. A test that reads a private signal or a component's internal method passes forever and protects nothing. The corollary is that most Angular tests should render something.
## 1. Decide first
| Question | Default | Change when |
|---|---|---|
| Runner | Vitest via `@angular/build:unit-test` — the CLI default since v21 | Existing Jest setup that is green and fast → leave it. Karma is still supported but no longer default; plan the move with `angular-migration` |
| Environment | jsdom | Testing layout, scroll, real focus or Shadow DOM → `browsers: ["chromium"]` in the test options |
| Component tests | `render()` from `@testing-library/angular` + role queries | The component is a thin wrapper over Material → CDK harnesses (`MatDialogHarness`, `MatSelectHarness`) read better |
| Change detection in tests | `await fixture.whenStable()` | Flushing effects or a signal-driven update inside a synchronous test → `TestBed.tick()`. Never `detectChanges()` in a loop |
| HTTP | `provideHttpClient()` + `provideHttpClientTesting()`, assert with `HttpTestingController` | The same mocks must also serve Storybook and e2e → MSW handlers in `setupFiles` |
| Children | Render them for real | Heavy (chart, map, editor) or side-effecting → a stub component with the same selector and `input()`s |
| Timers | `vi.useFakeTimers()` | Only zone.js-based projects can use `fakeAsync`/`tick`; it throws without `zone-testing.js` |
| End-to-end | Playwright, journeys only, against built output | — |
## 2. What to test at which layer
| Layer | Tool | Covers |
|---|---|---|
| Static | `strict`, `strictTemplates`, `@angular-eslint` template a11y rules | Types and template errors — free, run first |
| Unit | Vitest on plain functions | `model/` logic, pure helpers, validators, mappers |
| Component | Testing Library + TestBed + `HttpTestingController`/MSW | The page with its real children, real store, mocked network — where most value is |
| End-to-end | Playwright | Critical journeys only: sign in → do the thing → see the result |
Skip the pyramid arithmetic. The useful rule is: if a bug could ship without any existing test turning red, that is the test worth writing.
## 3. A component test
```ts
import { render, screen } from '@testing-library/angular';
import userEvent from '@testing-library/user-event';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideRouter } from '@angular/router';
import { OrderEditPage } from './order-edit-page';
it('shows an error when saving fails', async () => {
const user = userEvent.setup();
const { fixture } = await render(OrderEditPage, {
providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([])],
inputs: { id: '42' },
});
const http = TestBed.inject(HttpTestingController);
http.expectOne('/api/orders/42').flush({ id: '42', number: 'A-42', total: 10, paid: false });
await fixture.whenStable();
await user.click(await screen.findByRole('button', { name: /save/i }));
http.expectOne({ method: 'PUT', url: '/api/orders/42' }).flush(null, { status: 500, statusText: 'Server Error' });
expect(await screen.findByRole('alert')).toHaveTextContent(/could not save/i);
http.verify();
});
```
- Query by **role and accessible name**. A test that cannot find the button by its name has found a real accessibility bug.
- `inputs: { id: '42' }` sets signal inputs, including route-bound ones; `aliasedInput('alias', value)` when the input is aliased; `rerender({ inputs, partialUpdate: true })` to change one input and keep the rest. `componentInputs`/`componentOutputs` are deprecated — do not copy them from older examples.
- Outputs: `on: { save: vi.fn() }` in the `render` options, then assert the payload.
- `await fixture.whenStable()` after anything asynchronous; `TestBed.tick()` when you need effects and pending template work flushed synchronously. `TestBed.flushEffects()` is deprecated in favour of `tick()`.
## 4. The rest of the surface
- **Services and signals:** `TestBed.inject(Service)`, call methods, assert `service.items()`. `computed()` is synchronous — no awaiting. Functions using `inject()` run under `TestBed.runInInjectionContext(() => …)`.
- **`httpResource`/`resource`:** drive them through `HttpTestingController.expectOne(...).flush(...)`, `await fixture.whenStable()`, then assert `value()`, `isLoading()`, `error()`, `hasValue()`.
- **Signal Forms:** type into the real inputs with `userEvent`, assert the visible error message, and assert `f.email().invalid()` / `f().valid()` when the form state *is* the component's public API.
- **SignalStore:** `TestBed.inject(OrdersStore)` with mocked API providers; call the store's methods and assert its state signals and computeds. To seed protected state directly, `patchState(unprotected(store), …)` with `unprotected` from `@ngrx/signals/testing`.
- **Guards and interceptors:** `TestBed.runInInjectionContext(() => authGuard(route, state))` asserting `true` or a `UrlTree`; interceptors via `provideHttpClient(withInterceptors([authInterceptor]))` and assertions on the captured request headers.
- **Material components:** `TestbedHarnessEnvironment.loader(fixture)` then `loader.getHarness(MatDialogHarness)` — harnesses wait for stability themselves, which removes most dialog and overlay flake.
Full recipes for harnesses, `@defer` blocks, `RouterTestingHarness`, Signal Forms and stores: `references/component-and-store-tests.md`. Runner options, `vitest.config.ts`, MSW and coverage: `references/runner-and-setup.md`. Playwright, Storybook and accessibility assertions: `references/e2e-and-visual.md`.
## 5. Deliverable format
```
## Behaviours — the observable list: initial render, each input variation, each action, each output, loading/empty/error, a11y roles
## Tests — one `it` per behaviour, sentence-style name, arrange/act/assert, no shared mutable state
## Gaps — what is deliberately not covered and why (e.g. covered by an e2e journey)
## Run — the command, and the result
```
## Checklist
- [ ] Every test queries by role or label, not by CSS class or `data-testid` without a reason
- [ ] No `detectChanges()` loop; `await fixture.whenStable()` or `TestBed.tick()` instead
- [ ] No `fakeAsync`/`tick` unless the project still loads `zone.js/testing`
- [ ] `HttpTestingController.verify()` runs in `afterEach`; no unexpected requests
- [ ] Children render for real unless heavy or side-effecting, and any stub is named as such
- [ ] Assertions are on rendered output, emitted outputs, requests or navigation — not private members
- [ ] Each bug fix ships a test that fails without the fix
- [ ] Tests pass when the file is run alone and when the suite is run in a random order
- [ ] No `TestBed.flushEffects()`, `componentInputs`, `componentOutputs` or `NO_ERRORS_SCHEMA` by default
## Anti-patterns
- **`detectChanges()` called repeatedly until the assertion passes** → `await fixture.whenStable()`; repeated calls hide an imperative update that production will not perform.
- **`fakeAsync` in a zoneless project** → it throws "zone-testing.js is needed"; use `vi.useFakeTimers()` or await stability.
- **`NO_ERRORS_SCHEMA` to silence unknown elements** → import the child, or stub it explicitly; the schema also hides genuine typos in selectors and bindings.
- **Asserting on a component's private signal via `componentInstance`** → assert what the template renders; the private field is free to change.
- **`TestBed.overrideComponent` stubbing every child** → then the test proves only that the parent compiles.
- **Mocking your own services in a component test** → mock at the network boundary so the real wiring is exercised.
- **A `waitFor` with a 10-second timeout** → find the actual signal to await; a long timeout converts a failure into a slow failure.
- **Snapshot of a whole rendered component** → assert the two things the test is about; whole-tree snapshots get re-recorded on every change.
## Go deeper
- `references/runner-and-setup.md` — `@angular/build:unit-test` options, `vitest.config.ts` overrides, jsdom vs browser mode, MSW, coverage thresholds, shared `render` helper
- `references/component-and-store-tests.md` — CDK harnesses, `@defer` block testing, `RouterTestingHarness`, Signal Forms, resources, SignalStore and NgRx Store
- `references/e2e-and-visual.md` — Playwright journeys and `toHaveScreenshot`, Storybook play functions, automated accessibility assertions
- `version-notes.md` in `../angular-development/references/` — what is default in v20, v21 and v22
- Siblings: `angular-development` (the code under test), `angular-migration` (Karma → Vitest), `angular-performance`, `frontend-code-review`