Skip to content

project rulesTestingjavascripttypescript

Jest Vitest Rules

Project rules for Jest and Vitest unit tests: clear names, arrange-act-assert, narrow mocks, deterministic time and meaningful coverage.

npx workspacetemplates add jest-vitest-rules --tool claude-code

Writes 1 file to your project root

CLAUDE.mdadd to your file19 lines · 1.3 KBFile
# Project rules: Jest and Vitest

## Structure and naming
- Colocate `*.test.ts` next to the source. `describe` the unit; write `it('returns 404 when the user is missing')` as a behavior, not a method name.
- Arrange, act, assert, separated by blank lines. One behavior per test; use `it.each` for tables of inputs.

## Isolation
- Tests must not depend on order or share mutable state. Build data with small factory functions; reset in `beforeEach`, not `afterAll`.
- Control time with fake timers (`vi.useFakeTimers` or `jest.useFakeTimers`) and `setSystemTime`; never wait on real delays. Seed randomness.

## Mocks
- Mock only boundaries: network, filesystem, clock, third-party SDKs. Do not mock the unit under test or its pure helpers.
- Prefer `vi.fn()` or `jest.fn()` with explicit return values, and restore mocks automatically (`restoreMocks: true`). Verify calls with `toHaveBeenCalledWith`, not call counts alone.
- For HTTP, use MSW rather than stubbing fetch by hand.

## Assertions and coverage
- Assert outcomes users see. Use `toEqual` for data, `toThrow` with a message, `await expect(p).rejects` for promises. Avoid snapshots of large objects.
- Treat coverage as a gap finder; set thresholds on branches. Do not add assertion-free tests.
- Run the type check, lint and `npm test -- --coverage` before finishing.

What it does

These rules set one style for unit tests in JavaScript and TypeScript projects, whether the runner is Jest or Vitest. Tests read as specifications and fail with messages that point at the cause.

They limit mocking to boundaries and ban hidden shared state, so the suite stays quick and trustworthy as it grows.

Example

you › Add tests for the discount calculator

agent › The agent writes an it.each table covering tiers and edge cases, uses fixed dates with fake timers, mocks nothing internal and reports coverage of the branches.

Questions

Do the rules differ between Jest and Vitest?
Only the API names do. Swap vi for jest where the file calls for it; the conventions are the same.
Are snapshots banned?
No, only large ones. Small inline snapshots are fine for stable output such as error messages.
  • Playwright E2E Rules

    Project rulestypescript

    Free
  • Contract Testing

    SkillTesting

    Free
  • E2E Test Design

    SkillTesting

    Free
  • Flaky Test Diagnosis

    SkillTesting

    Free