AgentSkillsCN

vitest-expert

使用 Vitest 构建结构清晰、全面且高效的单元测试,从而保障代码的高质量与高稳定性。

SKILL.md
--- frontmatter
name: vitest-expert
description: Create organized, comprehensive, and efficient unit tests with Vitest, ensuring high code quality and stability.

Guidelines for UNIT

VITEST

  • Leverage the vi object for test doubles - Use vi.fn() for function mocks, vi.spyOn() to monitor existing functions, and vi.stubGlobal() for global mocks. Prefer spies over mocks when you only need to verify interactions without changing behavior.
  • Master vi.mock() factory patterns - Place mock factory functions at the top level of your test file, return typed mock implementations, and use mockImplementation() or mockReturnValue() for dynamic control during tests. Remember the factory runs before imports are processed.
  • Create setup files for reusable configuration - Define global mocks, custom matchers, and environment setup in dedicated files referenced in your vitest.config.ts. This keeps your test files clean while ensuring consistent test environments.
  • Use inline snapshots for readable assertions - Replace complex equality checks with expect(value).toMatchInlineSnapshot() to capture expected output directly in your test file, making changes more visible in code reviews.
  • Monitor coverage with purpose and only when asked - Configure coverage thresholds in vitest.config.ts to ensure critical code paths are tested, but focus on meaningful tests rather than arbitrary coverage percentages.
  • Make watch mode part of your workflow - Run vitest --watch during development for instant feedback as you modify code, filtering tests with -t to focus on specific areas under development.
  • Explore UI mode for complex test suites - Use vitest --ui to visually navigate large test suites, inspect test results, and debug failures more efficiently during development.
  • Handle optional dependencies with smart mocking - Use conditional mocking to test code with optional dependencies by implementing vi.mock() with the factory pattern for modules that might not be available in all environments.
  • Configure jsdom for DOM testing - Set environment: 'jsdom' in your configuration for frontend component tests and combine with testing-library utilities for realistic user interaction simulation.
  • Structure tests for maintainability - Group related tests with descriptive describe blocks, use explicit assertion messages, and follow the Arrange-Act-Assert pattern to make tests self-documenting.
  • Leverage TypeScript type checking in tests - Enable strict typing in your tests to catch type errors early, use expectTypeOf() for type-level assertions, and ensure mocks preserve the original type signatures.