vitest-v4

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
    - 对依赖时间的代码使用 fake timers
  • async-waitfor-polling
    - 使用 vi.waitFor 等待异步条件
  • async-concurrent-expect
    - 在并发测试中使用测试上下文的 expect
  • async-act-wrapper
    - 等待 user events 完成,避免 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 hook 中清理状态
  • setup-restore-mocks
    - 每个测试后恢复 mocks
  • setup-avoid-shared-state
    - 避免测试之间共享可变状态
  • setup-beforeall-expensive
    - 使用 beforeAll 执行高开销的一次性设置
  • setup-reset-modules
    - 测试模块状态时重置模块
  • setup-test-factories
    - 使用 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
    - 对动态 mocks 使用 mockImplementation
  • mock-msw-network
    - 使用 MSW Mock 网络请求
  • mock-avoid-overmocking
    - 避免过度 Mocking
  • mock-type-safety
    - 在 mocks 中保持类型安全
  • 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
    - 选择适合性能需求的 pool
  • perf-disable-isolation
    - 在安全的情况下禁用测试隔离
  • perf-happy-dom
    - 尽可能使用 happy-dom 而非 jsdom
  • perf-sharding
    - 使用 sharding 实现 CI 并行化
  • perf-run-mode-ci
    - 在 CI 环境中使用 run 模式
  • 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
    - 对小型值优先使用 inline snapshots
  • snap-avoid-large
    - 避免大型 snapshots
  • snap-stable-serialization
    - 确保快照序列化结果稳定
  • snap-review-updates
    - 提交前审查 snapshot 更新
  • 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
    - 使用 setup files 进行全局配置
  • env-globals-config
    - 统一配置 globals
  • 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
    - 使用具体的 matchers,而非通用 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 blocks 对相关内容进行逻辑分组
  • 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
阅读单独的参考文件以获取详细说明和代码示例:
  • 类别定义 - 类别结构和影响等级
  • 规则模板 - 用于添加新规则的模板
  • async-await-assertions - 示例规则文件
  • mock-vi-mock-hoisting - 示例规则文件

Interactions

交互关系

  • Does not cover app Playwright E2E — see playwright-v1 for ad-hoc browser automation; app E2E conventions live in consuming-repo rules
  • HTTP app tests with
    inject()
    and database isolation (PGLite,
    *.spec.ts
    vs
    *.test.ts
    ) are consuming-repo concerns — follow the project's Fastify testing rule, not this skill alone
  • 不涵盖应用级 Playwright E2E——有关临时浏览器自动化,请参阅 playwright-v1;应用 E2E 约定由使用方仓库的规则定义
  • 使用 inject() 和数据库隔离的 HTTP 应用测试(PGLite、
    *.spec.ts
    与
    *.test.ts
    )属于使用方仓库的关注事项——应遵循项目的 Fastify 测试规则,而不应仅依赖本 skill

Related Skills

相关 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
    skill
  • 关于使用 MSW 进行 API Mocking,请参阅
    test-msw
    skill
  • 关于 TypeScript 测试模式,请参阅
    typescript
    skill

Full Compiled Document

完整编译文档

For the complete guide with all rules expanded:
references/compiled.md
如需查看包含所有规则详细展开内容的完整指南,请参阅
references/compiled.md