Write unit tests with Vitest for TypeScript logic — `vi.mock` / `vi.fn` / `vi.spyOn`, `test.each` parameterized cases, async error assertions, Server Actions with mocked dependencies, and `vitest.config.ts` coverage setup. Trigger when the user says "unit test", "test this function", "test the server action", "test my schema", "test this hook", "add tests for this module", or is editing a `*.test.ts` file — even if they only say "this needs tests". NOT for React component rendering or interac...
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Unit Testing?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/janszewczyk-unit-testing)
---
name: unit-testing
description: Write unit tests with Vitest for TypeScript logic — `vi.mock` / `vi.fn` / `vi.spyOn`, `test.each` parameterized cases, async error assertions, Server Actions with mocked dependencies, and `vitest.config.ts` coverage setup. Trigger when the user says "unit test", "test this function", "test the server action", "test my schema", "test this hook", "add tests for this module", or is editing a `*.test.ts` file — even if they only say "this needs tests". NOT for React component rendering or interaction (use create-stories), API route handlers (use api-test), full-page E2E flows (use playwright-cli / true-dom-tester), or finding which code is untested (use coverage-gaps).
allowed-tools: Read, Write, Edit, Glob, Grep, Bash, mcp__context7__resolve-library-id, mcp__context7__get-library-docs
argument-hint: "[file or module to test, e.g. src/features/billing/utils.ts]"
---
# Unit Testing Skill (Vitest)
Write fast, isolated unit tests with **Vitest** for TypeScript logic — utilities, Zod schemas, hooks,
and Server Actions (with dependencies mocked). Unit tests do NOT render components in a browser
(use the `create-stories` skill for that).
This file holds the rules. Code lives in the references — this block is the only index, so the body
below names them without linking again:
> - [references/examples.md](./references/examples.md) — six worked examples: Zod schema, Server Action
> with mocked DB, transform function, parameterized (`test.each`), async error handling, hooks.
> - [references/patterns.md](./references/patterns.md) — AAA, test isolation, mock boundaries, the
> `vi.mock` vs `vi.fn` vs `vi.spyOn` decision table, what to cover and skip, and anti-patterns.
> - [references/mocking.md](./references/mocking.md) — the full mocking catalogue (factories, hoisting,
> partial/dynamic mocks, async, DB/auth/time/env recipes). Read before writing non-trivial mocks.
## Global Test Utilities
Check `vitest.config.ts` for `globals: true` and `tsconfig.json` for `"types": ["vitest/globals"]`
**before writing the first test**. When both are set, do **not** import test utilities:
```typescript
// ❌ Not needed
import { describe, test, expect, vi, beforeEach } from "vitest";
// ✅ Available globally: describe, test, expect,
// beforeEach/afterEach/beforeAll/afterAll, vi
```
If either is missing, import what you use from `"vitest"` explicitly rather than editing the
project's config.
## Workflow
1. **Analyze the code** — the module named in the argument, or the one under discussion: inputs,
outputs, side effects, dependencies, and every branch; whether it is pure or carries auth checks
and side effects; which use cases it serves and whether it is worth covering (see `patterns.md`).
2. **Identify cases** — happy path, edge cases, error paths, boundary values.
3. **Write tests** — AAA pattern (Arrange, Act, Assert); mock external dependencies at module boundaries.
4. **Run** — read the `scripts` block of `package.json` and use the project's own test script and
package manager; `npm run test:unit` is the assumed default, `npx vitest run <file>` the fallback
when no script exists. Verify all pass and check coverage.
5. **Iterate** — if a test fails, decide whether the test or the code is wrong before changing
either; fix and re-run. Repeat until the suite passes and every branch from step 1 is covered.
Never delete or `.skip` a failing test to make the run green.
## File Naming
Follow the convention already present in the repo. Absent one, tests live **next to the source
file**, named `<source-filename>.test.ts` (`.test.tsx` if it imports React/JSX):
```
src/utils/format-currency.ts → src/utils/format-currency.test.ts
src/features/budgets/actions/create-budget.ts → .../create-budget.test.ts
```
## Core Rules
- **Always write `test()`, never the `it()` alias** — one spelling across the whole suite. The same
goes for its variants: `test.each`, `test.skip`, `test.only`, `test.todo`. When a file already
uses `it()`, convert it to `test()` rather than adding a second convention to the same repo.
- **AAA structure** — Arrange, Act, Assert, separated by a blank line; group with nested `describe`
(module → function → case).
- **Test behavior, not implementation** — assert on return values and observable effects, never on
private internals; don't test private functions or abuse snapshots.
- **Name tests after the observable behavior** — `returns a formatted string for a positive amount`,
not `should work`.
- **Mock only at module boundaries** — external dependencies (DB, auth, network, time, UUID). Never
mock the internal utility you're testing.
- **Pick the right mock tool** (full decision table in `patterns.md`):
- `vi.mock("module", factory)` — replace an entire module (DB, auth).
- `vi.fn()` — a standalone mock (callback / injected dependency).
- `vi.spyOn(obj, "method")` — observe or replace one method, restorable via `.mockRestore()`.
- Beyond these three — `vi.hoisted()`, partial mocks, async/DB/auth/time recipes — read
`mocking.md` before writing the mock.
- **Reset between tests** — `beforeEach(() => vi.clearAllMocks())` wipes call history so one test's
assertions cannot see another's calls; `afterEach(() => vi.restoreAllMocks())` puts `vi.spyOn`
originals back so a spy cannot leak into an unrelated suite.
- **Type your mocks** — `vi.mocked(fn).mockResolvedValue(...)`.
- **Parameterize repetitive cases** with `test.each([...])` instead of copy-pasting tests.
- **Async** — `await` the call; use `await expect(p).rejects.toThrow(...)` / `.resolves.toMatchObject(...)`.
- **Pure functions need no mocking** — the easiest and highest-value tests.
## Shared rules
Rules shared with the other testing skills (test independence, what to assert, test data builders),
generated from the knowledge notes. Open a rule in [rules.md](./references/rules.md) when the test
you are writing touches it.
<!-- BEGIN:knowledge -->
<!-- generated by knowledge.mjs from 35 note(s) (sha256 658b9cba09ac); edit the notes in knowledge/, then run build -->
| Impact | Rule | Applies to |
| --- | --- | --- |
| critical | [Make every test able to fail when the behaviour it names breaks](references/rules.md#make-every-test-able-to-fail-when-the-behaviour-it-names-breaks) — A test with no assertion, or one that holds whatever the code does, passes forever and proves nothing. | any |
| critical | [Fix the cause of a flaky test instead of rerunning it until it passes](references/rules.md#fix-the-cause-of-a-flaky-test-instead-of-rerunning-it-until-it-passes) — A test that fails without a code change hides a race, a leak or a clock; reruns hide it and teach people to ignore red. | any |
| critical | [Wait for a condition the user would see, never for a fixed time](references/rules.md#wait-for-a-condition-the-user-would-see-never-for-a-fixed-time) — Await the element, value or call you expect with a retrying query; never sleep for a guessed number of milliseconds. | any |
| high | [Assert the resulting state, not which calls the code made to its collaborators](references/rules.md#assert-the-resulting-state-not-which-calls-the-code-made-to-its-collaborators) — Check the return value, the error or a dependency's resulting state; verify a call only when it is the behaviour. | any |
| high | [Set every value the test asserts on explicitly when you build test data](references/rules.md#set-every-value-the-test-asserts-on-explicitly-when-you-build-test-data) — Let the builder randomise what the test ignores; pass an override for every value the test checks. | any |
| high | [Keep branches and loops out of a test's body](references/rules.md#keep-branches-and-loops-out-of-a-tests-body) — A branch means some runs check nothing; write straight-line steps and parametrise over inputs. | any |
| high | [Keep the unit under test real, and change the test rather than the code](references/rules.md#keep-the-unit-under-test-real-and-change-the-test-rather-than-the-code) — Never mock the thing being tested or edit it to make a new test pass; report a failure that shows a real bug. | any |
| high | [Find elements the way a user or a screen reader does](references/rules.md#find-elements-the-way-a-user-or-a-screen-reader-does) — Query by role and accessible name, then label, then visible text; a test id is the last resort, never a CSS selector. | any |
| high | [Replace a dependency the test cannot run with a fake that passes the real contract tests](references/rules.md#replace-a-dependency-the-test-cannot-run-with-a-fake-that-passes-the-real-contract-tests) — Prefer a working in-memory fake to per-test stubs and call expectations, and run one contract suite against both. | any |
| high | [Mock only what a test cannot run or could only run with great difficulty](references/rules.md#mock-only-what-a-test-cannot-run-or-could-only-run-with-great-difficulty) — Every mock trades confidence for convenience; UI tests fake network, animations, costly services; E2E almost nothing. | any |
| high | [Reproduce a bug with a failing test before fixing it](references/rules.md#reproduce-a-bug-with-a-failing-test-before-fixing-it) — Write the test first and see it fail; decide whether a bug earns a test by what the breakage costs users. | any |
| high | [Spend most testing effort on integration tests](references/rules.md#spend-most-testing-effort-on-integration-tests) — Integration gets the largest share, E2E a few critical happy paths, unit the complex logic, static checks the typos. | any |
| high | [Test only what the end user or the developer using the code can touch](references/rules.md#test-only-what-the-end-user-or-the-developer-using-the-code-can-touch) — Rendered output for the end user, props and providers for the developer; a behaviour-keeping refactor changes no test. | any |
| high | [Make every test pass alone and in any order](references/rules.md#make-every-test-pass-alone-and-in-any-order) — No test relies on what an earlier one clicked or mocked; reset mocks per test, share setup through helpers. | any |
| high | [Wrap function-typed fields in fixed() so the builder does not call them](references/rules.md#wrap-function-typed-fields-in-fixed-so-the-builder-does-not-call-them) — A plain function as a field value is called on every build; fixed(fn) keeps it as the value. | typescript, mimicry-js |
| high | [Place mimicry-js generators directly as field values, use Faker inside arrow functions](references/rules.md#place-mimicry-js-generators-directly-as-field-values-use-faker-inside-arrow-functions) — oneOf, int, sequence and friends resolve only at field level; inside () => they return a descriptor, not a value. | typescript, mimicry-js |
| high | [Build with .one() and .many() and pass overrides or traits for asserted values](references/rules.md#build-with-one-and-many-and-pass-overrides-or-traits-for-asserted-values) — userBuilder.one({ overrides }) for one object, .many(n) for lists, traits for named states. | typescript, mimicry-js |
| high | [Write TypeScript builders with mimicry-js and Faker](references/rules.md#write-typescript-builders-with-mimicry-js-and-faker) — Every builder uses mimicry-js with Faker; a builder with traits types its fields as FieldsConfiguration<T>. | typescript, mimicry-js |
| medium | [Assert what the user sees or can do, never internal state or markup](references/rules.md#assert-what-the-user-sees-or-can-do-never-internal-state-or-markup) — Check visibility, text, values, focus, ARIA state and callback calls; never state, class names or markup snapshots. | any |
| medium | [Keep test setup inline until repetition hides what differs between tests](references/rules.md#keep-test-setup-inline-until-repetition-hides-what-differs-between-tests) — A helper takes overrides and returns what the test needs, with no branch per case; a test shows what matters to it. | any |
| medium | [Reset builder counters and random state between tests that depend on them](references/rules.md#reset-builder-counters-and-random-state-between-tests-that-depend-on-them) — Sequences and seeded randomness carry over between tests; reset them where a test depends on their values. | any |
| medium | [Build structured test data with a builder, not inline object literals](references/rules.md#build-structured-test-data-with-a-builder-not-inline-object-literals) — Typed objects with three or more fields come from a shared builder; reuse an existing one before writing one. | any |
| medium | [Derive the expected value from the test's own input, not a repeated literal](references/rules.md#derive-the-expected-value-from-the-tests-own-input-not-a-repeated-literal) — Assert against the data the test passed in (items.length, the prefilled value), never a hard-coded copy of it. | any |
| medium | [Keep snapshots small and inline, for output whose exact text matters](references/rules.md#keep-snapshots-small-and-inline-for-output-whose-exact-text-matters) — Snapshot error messages, logs or transformed code inline; replace a large snapshot with explicit assertions. | any |
| medium | [Name each test after the behaviour it checks, the situation and the expected outcome](references/rules.md#name-each-test-after-the-behaviour-it-checks-the-situation-and-the-expected-outcome) — test_returning_an_overdue_book_charges_a_fine, not test_return_book or test_2. | any |
| medium | [Query by the text users read, not by translation keys](references/rules.md#query-by-the-text-users-read-not-by-translation-keys) — Look up the default locale's real text, so a changed label is a change the test reports. | any |
| medium | [Choose the next test by what would hurt most if it broke](references/rules.md#choose-the-next-test-by-what-would-hurt-most-if-it-broke) — Start from the worst breakage in untested code, narrow to its units and users, write the manual steps, automate them. | any |
| medium | [Judge a suite by the use cases it covers, not by a coverage percentage](references/rules.md#judge-a-suite-by-the-use-cases-it-covers-not-by-a-coverage-percentage) — Use the coverage report to find untested code; set no percentage target for an application, and none for E2E tests. | any |
| medium | [Use semantic HTML instead of adding ARIA so that a query works](references/rules.md#use-semantic-html-instead-of-adding-aria-so-that-a-query-works) — The right element and input type give the implicit role; add role or aria-* only for what HTML cannot express. | any |
| medium | [Fill nested typed objects from their own builder](references/rules.md#fill-nested-typed-objects-from-their-own-builder) — A nested type gets its own builder, used as () => otherBuilder.one(); overrides deep-merge into it. | typescript, mimicry-js |
| medium | [Build lists with .many(count), not Array.from or map](references/rules.md#build-lists-with-manycount-not-arrayfrom-or-map) — .many(n) applies overrides and traits to each item and keeps sequence and unique state right. | typescript, mimicry-js |
| medium | [Compute fields that derive from other fields in postBuild](references/rules.md#compute-fields-that-derive-from-other-fields-in-postbuild) — Totals, counts and display names built from sibling fields go in postBuild, so overrides stay consistent. | typescript, mimicry-js |
| medium | [Call builder.reset() in beforeEach when a test depends on sequence values](references/rules.md#call-builderreset-in-beforeeach-when-a-test-depends-on-sequence-values) — reset() restarts sequence() and unique() counters; seed() makes oneOf, int, float and bool reproducible. | typescript, mimicry-js |
| medium | [Use unique() for values that must differ across built objects](references/rules.md#use-unique-for-values-that-must-differ-across-built-objects) — oneOf() can repeat a value within one .many() call; unique() hands each value out once. | typescript, mimicry-js |
| low | [Write the test first when the requirements are clear](references/rules.md#write-the-test-first-when-the-requirements-are-clear) — TDD for pure functions, bug fixes and UIs with a settled design; in exploratory coding, test once the direction holds. | any |
<!-- END:knowledge -->
## Setup (vitest.config.ts essentials)
Never rewrite an existing `vitest.config.ts`. This is the baseline to check against when a test
behaves unexpectedly, and the starting point only when the project has no Vitest config at all.
```typescript
test: {
globals: true, // no test-utility imports needed
environment: "node", // "jsdom" for hooks/DOM
include: ["src/**/*.test.{ts,tsx}"],
coverage: {
provider: "v8",
exclude: ["src/**/*.test.{ts,tsx}", "src/**/*.stories.{ts,tsx}", "src/**/index.ts", "src/types/**"],
},
}
```
## Running Tests
```bash
npm run test:unit # all unit tests
npm run test:unit -- --watch # watch mode
npm run test:unit -- src/utils/format-currency.test.ts # one file
npm run test:unit -- -t "formatCurrency" # by test name pattern
npm run test:unit -- --coverage # coverage report
```