← Docs
recipe

Vitest patterns

Composable test factories, snapshot contracts, and mock boundaries that keep the suite fast and deterministic.

Factory-first tests

Every entity gets a createTest* factory. Defaults are production-shaped; overrides are explicit in each test. No shared mutable fixtures — every test owns its data.

Snapshot contracts

Snapshots are reserved for serializable output contracts — API responses, CLI tables, config hashes. Never snapshot mutable state or timestamps. Review every diff in PR.

Mock boundaries

Only mock at the I/O seam: fetch, fs, crypto.randomUUID. Business logic is tested with real implementations. Use vi.hoistedfor module-level mocks so they land before imports.

Timers & flakes

Fake timers with vi.useFakeTimers(). Never setTimeout in tests. If a test fails once in 1000 runs, it is broken — fix the race, do not retry.