Recipes
A recipe solves one concrete problem with several features of Vitest, and has code that you can copy.
- Database Transaction per Test
Wrap each test in a database transaction that rolls back, with
aroundEachand a fixture. - Cancellable Test Resources
Stop a
fetch, a child process or a stream when Vitest cancels the test, with thesignalof the test context. - Waiting for Async Conditions
Wait for a condition without
setTimeout, withexpect.poll,vi.waitForandvi.waitUntil. - Type Narrowing in Tests
Narrow a value that can be
nullorundefinedwithexpect.assert, without casts. - Custom Assertion Helpers
Write assertion helpers whose errors point at the test that called them, with
vi.defineHelper. - Watching Non-Imported Files
Rerun tests in watch mode when a file changes that the tests do not import, with
watchTriggerPatterns. - Extending Browser Locators
Add your own locators for the parts of your app, with
locators.extend. - Schema-Driven Assertions
Check values against a Zod, Valibot or ArkType schema with
expect.schemaMatching. - Auto-Cleanup with
usingRestore spies and mocks automatically at the end of a block with the
usingkeyword. - Conditional Mocking with vi.when
Return different values for different arguments of a mock with
vi.when. - Per-File Isolation Settings
Turn isolation off for unit tests and keep it for integration tests, with projects.
- Parallel and Sequential Test Files
Run most test files in parallel and some files one after the other, with 2 projects.
- Running Only Affected Tests
Run only the tests that a change affects, with
--changedor--since-last-run.