vitest-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Vitest Best Practices

Vitest 最佳实践

When to Apply This Skill

何时应用此技能

Use this skill when you encounter any of these scenarios:
当你遇到以下任一场景时,可使用此技能:

File Patterns

文件模式

  • Working with
    *.test.ts
    ,
    *.spec.ts
    , or similar test files
  • Creating new test files for TypeScript/JavaScript modules
  • Reviewing existing vitest test suites
  • 处理
    *.test.ts
    *.spec.ts
    或类似测试文件
  • 为TypeScript/JavaScript模块创建新的测试文件
  • 审查现有的Vitest测试套件

User Intent Keywords

用户意图关键词

  • User mentions: vitest, testing, TDD, BDD, unit tests, integration tests
  • User asks to: write tests, add test coverage, fix failing tests, refactor tests
  • User discusses: mocking, stubbing, assertions, test performance, test organization
  • 用户提及:vitest、testing、TDD、BDD、单元测试、集成测试
  • 用户请求:编写测试、添加测试覆盖率、修复失败的测试、重构测试
  • 用户讨论:模拟、存根、断言、测试性能、测试组织

Code Context

代码上下文

  • Files importing from
    vitest
    (
    describe
    ,
    it
    ,
    expect
    ,
    vi
    )
  • Test setup/teardown code (
    beforeEach
    ,
    afterEach
    ,
    beforeAll
    ,
    afterAll
    )
  • Mock/spy implementations using
    vi.mock()
    ,
    vi.spyOn()
    ,
    vi.fn()
  • Assertion chains (
    expect(...).toEqual()
    ,
    .toBe()
    ,
    .toThrow()
    , etc.)
  • vitest
    导入的文件(
    describe
    it
    expect
    vi
  • 测试初始化/清理代码(
    beforeEach
    afterEach
    beforeAll
    afterAll
  • 使用
    vi.mock()
    vi.spyOn()
    vi.fn()
    实现的模拟/间谍
  • 断言链(
    expect(...).toEqual()
    .toBe()
    .toThrow()
    等)

Common Tasks

常见任务

  • Writing new test cases for existing functionality
  • Refactoring tests for better clarity or performance
  • Debugging flaky or failing tests
  • Improving test coverage or maintainability
  • Reviewing test code for best practices compliance
  • 为现有功能编写新的测试用例
  • 重构测试以提升清晰度或性能
  • 调试不稳定或失败的测试
  • 提升测试覆盖率或可维护性
  • 审查测试代码是否符合最佳实践

Do NOT Use This Skill When

请勿使用此技能的场景

  • Writing end-to-end tests with Playwright/Cypress (different scope)
  • The task is purely about implementation code, not tests
  • 使用Playwright/Cypress编写端到端测试(范围不同)
  • 任务仅涉及实现代码,与测试无关

What This Skill Covers

此技能涵盖的内容

This skill provides comprehensive guidance on:
  1. Test Organization: File placement, naming conventions, grouping strategies
  2. AAA Pattern: Arrange, Act, Assert structure for clarity
  3. Parameterized Tests: Using
    it.each()
    for testing variations
  4. Error Handling: Testing exceptions, edge cases, and fault injection
  5. Assertions: Choosing strict assertions (
    toEqual
    ,
    toStrictEqual
    ,
    toThrow
    )
  6. Test Doubles: Fakes, stubs, mocks, spies - when to use each
  7. Async Testing: Promises, async/await, timers, and concurrent tests
  8. Performance: Fast tests, avoiding expensive operations, cleanup patterns
  9. Vitest-Specific Features: Coverage, watch mode, benchmarking, type testing, setup files
  10. Snapshot Testing: When and how to use snapshots effectively
本技能提供以下方面的全面指导:
  1. 测试组织:文件放置、命名规范、分组策略
  2. AAA模式:Arrange(准备)、Act(执行)、Assert(断言)的清晰结构
  3. 参数化测试:使用
    it.each()
    测试多种变体
  4. 错误处理:测试异常、边缘情况和故障注入
  5. 断言:选择严格断言(
    toEqual
    toStrictEqual
    toThrow
  6. 测试替身:Fakes(伪实现)、Stubs(存根)、Mocks(模拟)、Spies(间谍)- 何时使用每种类型
  7. 异步测试:Promise、async/await、计时器和并发测试
  8. 性能:快速测试、避免昂贵操作、清理模式
  9. Vitest专属特性:覆盖率、监听模式、基准测试、类型测试、初始化文件
  10. 快照测试:何时以及如何有效使用快照

How to Use

使用方法

This skill uses a progressive disclosure structure to minimize context usage:
本技能采用渐进式披露结构,以最小化上下文使用:

1. Start with the Overview (AGENTS.md)

1. 从概述开始(AGENTS.md)

Read AGENTS.md for a concise overview of all rules with one-line summaries.
阅读 AGENTS.md 获取所有规则的简明概述,每条规则配有一行摘要。

2. Load Specific Rules as Needed

2. 根据需要加载特定规则

When you identify a relevant optimization, load the corresponding reference file for detailed implementation guidance:
Core Patterns:
  • organization.md
  • aaa-pattern.md
  • parameterized-tests.md
  • error-handling.md
  • assertions.md
  • test-doubles.md
Advanced Topics:
  • async-testing.md
  • performance.md
  • vitest-features.md
  • snapshot-testing.md
当你确定相关优化点时,加载对应的参考文件获取详细的实现指导:
核心模式:
  • organization.md
  • aaa-pattern.md
  • parameterized-tests.md
  • error-handling.md
  • assertions.md
  • test-doubles.md
高级主题:
  • async-testing.md
  • performance.md
  • vitest-features.md
  • snapshot-testing.md

3. Apply the Pattern

3. 应用模式

Each reference file contains:
  • ❌ Incorrect examples showing the anti-pattern
  • ✅ Correct examples showing the optimal implementation
  • Explanations of why the pattern matters
每个参考文件包含:
  • ❌ 展示反模式的错误示例
  • ✅ 展示最佳实现的正确示例
  • 解释该模式重要性的说明

Quick Example

快速示例

This skill helps you transform unclear tests into clear, maintainable ones:
Before (unclear):
ts
test('product test', () => {
  const p = new ProductService().add({name: 'Widget'});
  expect(p.status).toBe('pendingApproval');
});
After (optimized with this skill):
ts
describe('ProductService', () => {
  describe('Add new product', () => {
    it('should have status "pending approval" when no price is specified', () => {
      // Arrange
      const productService = new ProductService();

      // Act
      const newProduct = productService.add({name: 'Widget'});

      // Assert
      expect(newProduct.status).toEqual('pendingApproval');
    });
  });
});
本技能可帮助你将模糊的测试转换为清晰、可维护的测试:
优化前(模糊):
ts
test('product test', () => {
  const p = new ProductService().add({name: 'Widget'});
  expect(p.status).toBe('pendingApproval');
});
优化后(使用本技能):
ts
describe('ProductService', () => {
  describe('Add new product', () => {
    it('should have status "pending approval" when no price is specified', () => {
      // Arrange
      const productService = new ProductService();

      // Act
      const newProduct = productService.add({name: 'Widget'});

      // Assert
      expect(newProduct.status).toEqual('pendingApproval');
    });
  });
});

Key Principles

核心原则

  • Clarity over cleverness: Tests should be instantly understandable
  • Flat structure: Avoid deep nesting in describe blocks
  • One assertion per concept: Focus tests on single behaviors
  • Strict assertions: Prefer
    toEqual
    over
    toBe
    ,
    toStrictEqual
    when needed
  • Minimal mocking: Use real implementations when practical
  • Fast execution: Keep tests quick through efficient setup/teardown
  • 清晰优于技巧:测试应一目了然
  • 扁平化结构:避免在describe块中深度嵌套
  • 每个概念对应一个断言:测试聚焦于单一行为
  • 严格断言:优先使用
    toEqual
    而非
    toBe
    ,必要时使用
    toStrictEqual
  • 最小化模拟:实际可行时使用真实实现
  • 快速执行:通过高效的初始化/清理保持测试快速运行