vitest

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Vitest Best Practices

Vitest 最佳实践

Comprehensive performance optimization and best practices guide for Vitest testing framework. Contains 44 rules across 8 categories, prioritized by impact to guide test writing, refactoring, and code review.
这是一份针对Vitest测试框架的全面性能优化与最佳实践指南。包含8个类别共44条规则,按影响优先级排序,可指导测试编写、重构及代码评审。

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
在以下场景中可参考本指南:
  • 编写新的Vitest测试
  • 调试不稳定或缓慢的测试
  • 配置测试环境
  • 评审PR中的测试代码
  • 从Jest迁移至Vitest
  • 优化CI/CD中的测试性能

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-
3Mocking模式
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
    - 每次测试后恢复Mock
  • setup-avoid-shared-state
    - 避免测试间共享可变状态
  • setup-beforeall-expensive
    - 使用beforeAll执行耗时的一次性设置
  • setup-reset-modules
    - 测试模块状态时重置模块
  • setup-test-factories
    - 使用测试工厂生成复杂测试数据

3. Mocking Patterns (HIGH)

3. Mocking模式(高)

  • 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
  • mock-msw-network
    - 使用MSW进行网络请求Mocking
  • mock-avoid-overmocking
    - 避免过度Mock
  • mock-type-safety
    - 保持Mock的类型安全性
  • mock-clear-between-tests
    - 测试间清理Mock状态

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中使用快速失败机制

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
    - Mock测试环境中不存在的浏览器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:
  • Section definitions - Category structure and impact levels
  • Rule template - Template for adding new rules
  • async-await-assertions - Example rule file
  • mock-vi-mock-hoisting - Example rule file
阅读单个参考文件获取详细说明及代码示例:
  • Section definitions - 类别结构与影响级别说明
  • Rule template - 添加新规则的模板
  • async-await-assertions - 规则示例文件
  • mock-vi-mock-hoisting - 规则示例文件

Related Skills

相关技能

  • For TDD methodology, see
    test-tdd
    skill
  • For API mocking with MSW, see
    test-msw
    skill
  • For TypeScript testing patterns, see
    typescript
    skill
  • 如需了解TDD方法论,请查看
    test-tdd
    技能
  • 如需基于MSW的API Mocking,请查看
    test-msw
    技能
  • 如需TypeScript测试模式,请查看
    typescript
    技能

Full Compiled Document

完整编译文档

For the complete guide with all rules expanded:
AGENTS.md
包含所有规则详细内容的完整指南:
AGENTS.md