Imported from Cobalt-Money/Cobalt (
.agents/skills/vitest/AGENTS.md). Install upstream withnpx skills add Cobalt-Money/Cobalt --skill vitest. Copyright stays with the author.
Vitest
Version 1.0.0
community
January 2026
Note:
This document is mainly for agents and LLMs to follow when maintaining,
generating, or refactoring codebases. Humans may also find it useful,
but guidance here is optimized for automation and consistency by AI-assisted workflows.
Abstract
Comprehensive testing best practices guide for Vitest, designed for AI agents and LLMs. Contains 44 rules across 8 categories, prioritized by impact from critical (async patterns, test isolation) to incremental (test organization). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated test writing and code review.
Table of Contents
- Async Patterns — CRITICAL
- 1.1 Await Async Assertions — CRITICAL (Prevents false positives where tests pass despite failing assertions)
- 1.2 Await User Events to Avoid Act Warnings — CRITICAL (Prevents "not wrapped in act(...)" warnings and ensures UI updates complete)
- 1.3 Return Promises from Test Functions — CRITICAL (Prevents tests from completing before async operations finish)
- 1.4 Test Async Error Handling Properly — CRITICAL (Prevents tests from passing when async operations fail silently)
- 1.5 Use Fake Timers for Time-Dependent Code — CRITICAL (Eliminates timer-based flaky tests and reduces test duration by 100×)
- 1.6 Use Test Context Expect in Concurrent Tests — CRITICAL (Prevents snapshot collision and assertion cross-contamination in parallel tests)
- 1.7 Use vi.waitFor for Async Conditions — CRITICAL (Replaces arbitrary timeouts with condition-based waiting, eliminating flaky tests)
- Test Setup & Isolation — CRITICAL
- 2.1 Avoid Shared Mutable State Between Tests — CRITICAL (Eliminates order-dependent test failures and enables reliable parallel execution)
- 2.2 Clean Up State in afterEach Hooks — CRITICAL (Prevents test pollution where one test's side effects cause subsequent tests to fail)
- 2.3 Reset Modules When Testing Module State — HIGH (Ensures modules with cached state are properly isolated between tests)
- 2.4 Restore Mocks After Each Test — CRITICAL (Prevents mock leakage where mocked behavior persists into unrelated tests)
- 2.5 Use beforeAll for Expensive One-Time Setup — HIGH (Reduces test suite time by 50-90% for tests with expensive setup)
- 2.6 Use Test Factories for Complex Test Data — MEDIUM (Reduces test setup boilerplate by 60% and improves test readability)
- Mocking Patterns — HIGH
- 3.1 Avoid Over-Mocking — HIGH (Prevents tests that pass despite broken code by testing mocks instead of behavior)
- 3.2 Choose vi.spyOn vs vi.mock Appropriately — HIGH (Prevents over-mocking and ensures tests exercise real code paths)
- 3.3 Clear Mock State Between Tests — MEDIUM (Prevents call count and argument contamination between tests)
- 3.4 Maintain Type Safety in Mocks — MEDIUM (Catches mock/implementation mismatches at compile time instead of runtime)
- 3.5 Understand vi.mock Hoisting Behavior — HIGH (Prevents "module not mocked" errors and unexpected real implementations)
- 3.6 Use mockImplementation for Dynamic Mocks — HIGH (Enables context-aware mocks that respond differently based on input)
- 3.7 Use MSW for Network Request Mocking — HIGH (Provides realistic request/response mocking at the network level)
- Performance — HIGH
- 4.1 Choose the Right Pool for Performance — HIGH (2-5× performance difference between pool types on large test suites)
- 4.2 Disable Test Isolation When Safe — HIGH (30-50% faster test execution for well-isolated tests)
- 4.3 Use Bail for Fast Failure in CI — MEDIUM (Saves CI minutes by stopping early when tests fail)
- 4.4 Use happy-dom Over jsdom When Possible — HIGH (2-3× faster DOM operations compared to jsdom)
- 4.5 Use Run Mode in CI Environments — MEDIUM (Avoids watch mode overhead and file system polling in CI)
- 4.6 Use Sharding for CI Parallelization — HIGH (Linear speedup with additional CI nodes (3 nodes = ~3× faster))
- Snapshot Testing — MEDIUM
- 5.1 Avoid Large Snapshots — MEDIUM (Large snapshots are rarely reviewed and blindly updated, masking real bugs)
- 5.2 Ensure Stable Snapshot Serialization — MEDIUM (Eliminates false snapshot failures from non-deterministic data)
- 5.3 Name Snapshot Tests Descriptively — LOW (Improves snapshot file organization and failure debugging)
- 5.4 Prefer Inline Snapshots for Small Values — MEDIUM (Improves test readability by showing expected output directly in test code)
- 5.5 Review Snapshot Updates Before Committing — MEDIUM (Prevents bugs from being silently committed via blind snapshot updates)
- Environment — MEDIUM
- 6.1 Configure Globals Consistently — LOW (Determines whether imports are required for test APIs)
- 6.2 Mock Browser APIs Not Available in Test Environment — MEDIUM (Prevents "X is not defined" errors when testing browser-specific code)
- 6.3 Override Environment Per File When Needed — MEDIUM (Allows mixing node and browser tests without separate config files)
- 6.4 Use Setup Files for Global Configuration — MEDIUM (Centralizes test setup and ensures consistent environment across all tests)
- Assertions — LOW-MEDIUM
- 7.1 Choose toBe vs toEqual Correctly — LOW (Prevents false positives from reference vs value comparison)
- 7.2 Test Edge Cases and Boundaries — MEDIUM (Catches bugs that happy-path-only tests miss)
- 7.3 Test One Concept Per Test — LOW-MEDIUM (Improves failure diagnosis and test maintainability)
- 7.4 Use expect.assertions for Async Tests — MEDIUM (Prevents tests from passing when async assertions are skipped)
- 7.5 Use Specific Matchers Over Generic Ones — MEDIUM (Provides clearer failure messages and catches more specific bugs)
- Test Organization — LOW
- 8.1 Colocate Test Files with Source Files — LOW (Reduces navigation overhead and improves test discoverability)
- 8.2 Use Describe Blocks for Logical Grouping — LOW (Improves test output readability and enables scoped setup/teardown)
- 8.3 Use skip and only Appropriately — LOW (Prevents accidentally committing focused or skipped tests)
- 8.4 Write Descriptive Test Names — LOW (Improves test documentation and failure debugging)
References
- https://vitest.dev/guide/improving-performance
- https://vitest.dev/guide/profiling-test-performance
- https://vitest.dev/guide/mocking
- https://vitest.dev/guide/snapshot
- https://vitest.dev/guide/browser/component-testing
- https://trunk.io/blog/how-to-avoid-and-detect-flaky-tests-in-vitest
- https://mswjs.io/docs/
Source Files
This document was compiled from individual reference files. For detailed editing or extension:
| File | Description |
|---|---|
| references/_sections.md | Category definitions and impact ordering |
| assets/templates/_template.md | Template for creating new rules |
| SKILL.md | Quick reference entry point |
| metadata.json | Version and reference URLs |