vitest

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Vitest Best Practices

Vitest 最佳实践

Vitest 4-compatible testing guide with 44 rules across 8 categories. Vitest 4 requires Node.js 20+ and Vite 6+ when used with Vite.
兼容 Vitest 4 的测试指南,包含8个分类下的44条规则。使用 Vite 时,Vitest 4 需要 Node.js 20+ 和 Vite 6+ 版本。

When to Apply

适用场景

Reference these guidelines when:
  • Writing new Vitest tests
  • Debugging flaky or slow tests
  • Setting up test configuration
  • Reviewing test code in PRs
  • Migrating from Jest to Vitest
  • Optimizing CI/CD test performance
Jest-specific APIs and configuration outside documented migration differences are out of scope; use Jest's own documentation for tests that still run under Jest.
在以下场景中可参考本指南:
  • 编写新的 Vitest 测试用例
  • 调试不稳定或运行缓慢的测试
  • 配置测试环境
  • 审查 PR 中的测试代码
  • 从 Jest 迁移至 Vitest
  • 优化 CI/CD 中的测试性能
超出文档记录的迁移差异之外的 Jest 专属 API 和配置不在本指南范围内;仍在 Jest 下运行的测试请参考 Jest 官方文档。

Rule Categories by Priority

按优先级划分的规则分类

PriorityCategoryImpactPrefix
1Async PatternsCRITICAL
async-
2Test Setup & IsolationCRITICAL
setup-
3Mocking PatternsHIGH
mock-
4PerformanceHIGH
perf-
5Snapshot TestingMEDIUM
snap-
6EnvironmentMEDIUM
env-
7AssertionsLOW-MEDIUM
assert-
8Test OrganizationLOW
org-
优先级分类影响程度前缀
1异步模式关键
async-
2测试设置与隔离关键
setup-
3模拟模式
mock-
4性能
perf-
5快照测试
snap-
6环境
env-
7断言低-中
assert-
8测试组织
org-

Quick Reference

快速参考

1. Async Patterns (CRITICAL)

1. 异步模式(关键)

  • async-await-assertions
    - Await async assertions to prevent false positives
  • async-return-promises
    - Return promises from test functions
  • async-fake-timers
    - Use fake timers for time-dependent code
  • async-waitfor-polling
    - Use vi.waitFor for async conditions
  • async-concurrent-expect
    - Use test context expect in concurrent tests
  • async-act-wrapper
    - Await user events to avoid act warnings
  • async-error-handling
    - Test async error handling properly
  • async-await-assertions
    - 等待异步断言完成,避免误报
  • async-return-promises
    - 从测试函数返回 Promise
  • async-fake-timers
    - 为依赖时间的代码使用假计时器
  • async-waitfor-polling
    - 使用 vi.waitFor 处理异步条件
  • async-concurrent-expect
    - 在并发测试中使用测试上下文的 expect
  • async-act-wrapper
    - 等待用户事件完成,避免 act 警告
  • async-error-handling
    - 正确测试异步错误处理逻辑

2. Test Setup & Isolation (CRITICAL)

2. 测试设置与隔离(关键)

  • setup-beforeeach-cleanup
    - Clean up state in afterEach hooks
  • setup-restore-mocks
    - Restore mocks after each test
  • setup-avoid-shared-state
    - Avoid shared mutable state between tests
  • setup-beforeall-expensive
    - Use beforeAll for expensive one-time setup
  • setup-reset-modules
    - Reset modules when testing module state
  • setup-test-factories
    - Use test factories for complex test data
  • setup-beforeeach-cleanup
    - 在 afterEach 钩子中清理状态
  • setup-restore-mocks
    - 每次测试后恢复模拟
  • setup-avoid-shared-state
    - 避免测试间共享可变状态
  • setup-beforeall-expensive
    - 使用 beforeAll 处理耗时的一次性设置
  • setup-reset-modules
    - 测试模块状态时重置模块
  • setup-test-factories
    - 使用测试工厂生成复杂测试数据

3. Mocking Patterns (HIGH)

3. 模拟模式(高)

  • mock-vi-mock-hoisting
    - Understand vi.mock hoisting behavior
  • mock-spyon-vs-mock
    - Choose vi.spyOn vs vi.mock appropriately
  • mock-implementation-not-value
    - Use mockImplementation for dynamic mocks
  • mock-msw-network
    - Use MSW for network request mocking
  • mock-avoid-overmocking
    - Avoid over-mocking
  • mock-type-safety
    - Maintain type safety in mocks
  • mock-clear-between-tests
    - Clear mock state between tests
  • mock-vi-mock-hoisting
    - 理解 vi.mock 的提升行为
  • mock-spyon-vs-mock
    - 合理选择 vi.spyOn 和 vi.mock
  • mock-implementation-not-value
    - 使用 mockImplementation 创建动态模拟
  • mock-msw-network
    - 使用 MSW 进行网络请求模拟
  • mock-avoid-overmocking
    - 避免过度模拟
  • mock-type-safety
    - 保持模拟的类型安全性
  • mock-clear-between-tests
    - 测试间清除模拟状态

4. Performance (HIGH)

4. 性能(高)

  • perf-pool-selection
    - Choose the right pool for performance
  • perf-disable-isolation
    - Disable test isolation when safe
  • perf-happy-dom
    - Use happy-dom over jsdom when possible
  • perf-sharding
    - Use sharding for CI parallelization
  • perf-run-mode-ci
    - Use run mode in CI environments
  • perf-bail-fast-fail
    - Use bail for fast failure in CI
  • perf-pool-selection
    - 选择合适的工作池以提升性能
  • perf-disable-isolation
    - 在安全情况下禁用测试隔离
  • perf-happy-dom
    - 尽可能使用 happy-dom 替代 jsdom
  • perf-sharding
    - 在 CI 中使用分片实现并行化
  • perf-run-mode-ci
    - 在 CI 环境中使用运行模式
  • perf-bail-fast-fail
    - 在 CI 中使用 bail 快速失败机制

5. Snapshot Testing (MEDIUM)

5. 快照测试(中)

  • snap-inline-over-file
    - Prefer inline snapshots for small values
  • snap-avoid-large
    - Avoid large snapshots
  • snap-stable-serialization
    - Ensure stable snapshot serialization
  • snap-review-updates
    - Review snapshot updates before committing
  • snap-describe-intent
    - Name snapshot tests descriptively
  • snap-inline-over-file
    - 小值优先使用内联快照
  • snap-avoid-large
    - 避免使用大型快照
  • snap-stable-serialization
    - 确保快照序列化的稳定性
  • snap-review-updates
    - 提交前审查快照更新
  • snap-describe-intent
    - 为快照测试命名时清晰描述意图

6. Environment (MEDIUM)

6. 环境(中)

  • env-per-file-override
    - Override environment per file when needed
  • env-setup-files
    - Use setup files for global configuration
  • env-globals-config
    - Configure globals consistently
  • env-browser-api-mocking
    - Mock browser APIs not available in test environment
  • env-per-file-override
    - 必要时按文件覆盖环境配置
  • env-setup-files
    - 使用设置文件进行全局配置
  • env-globals-config
    - 统一配置全局变量
  • env-browser-api-mocking
    - 模拟测试环境中不可用的浏览器 API

7. Assertions (LOW-MEDIUM)

7. 断言(低-中)

  • assert-specific-matchers
    - Use specific matchers over generic ones
  • assert-edge-cases
    - Test edge cases and boundaries
  • assert-one-assertion-concept
    - Test one concept per test
  • assert-expect-assertions
    - Use expect.assertions for async tests
  • assert-toequal-vs-tobe
    - Choose toBe vs toEqual correctly
  • assert-specific-matchers
    - 使用特定断言替代通用断言
  • assert-edge-cases
    - 测试边界情况
  • assert-one-assertion-concept
    - 每个测试仅验证一个概念
  • assert-expect-assertions
    - 在异步测试中使用 expect.assertions
  • assert-toequal-vs-tobe
    - 正确选择 toBe 和 toEqual

8. Test Organization (LOW)

8. 测试组织(低)

  • org-file-colocation
    - Colocate test files with source files
  • org-describe-nesting
    - Use describe blocks for logical grouping
  • org-test-naming
    - Write descriptive test names
  • org-test-skip-only
    - Use skip and only appropriately
  • org-file-colocation
    - 将测试文件与源文件放在同一目录
  • org-describe-nesting
    - 使用 describe 块进行逻辑分组
  • org-test-naming
    - 编写描述性的测试名称
  • org-test-skip-only
    - 合理使用 skip 和 only

How to Use

使用方法

Read individual reference files for detailed explanations and code examples:
  • async-await-assertions - Example rule file
  • mock-vi-mock-hoisting - Example rule file
阅读单个参考文件获取详细说明和代码示例:
  • async-await-assertions - 规则示例文件
  • mock-vi-mock-hoisting - 规则示例文件

Related Skills

相关技能

  • For TDD methodology, see
    tdd
    skill
  • For API mocking with MSW, see
    msw
    skill
  • For TypeScript testing patterns, see
    typescript
    skill
  • TDD 方法论请参考
    tdd
    技能文档
  • MSW API 模拟请参考
    msw
    技能文档
  • TypeScript 测试模式请参考
    typescript
    技能文档

Full Compiled Document

完整编译文档

For the complete guide with all rules expanded:
AGENTS.md
如需查看包含所有规则扩展说明的完整指南,请查看:
AGENTS.md