vitest-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Vitest Testing

Vitest 测试

Overview

概述

Vitest is a Vite-native unit testing framework that shares the same configuration and plugin ecosystem. Built for speed with native ESM support, hot module replacement for tests, and parallel execution.
When to use: Unit tests, component tests, integration tests, hook tests, in-source tests. Testing React components with React Testing Library. Testing TanStack Query/Router/Form patterns.
When NOT to use: End-to-end testing (use Playwright), visual regression testing (use Percy/Chromatic), load testing (use k6).
Vitest 是一款原生基于 Vite 的单元测试框架,共享相同的配置和插件生态系统。专为速度优化,支持原生 ESM、测试热模块替换和并行执行。
适用场景: 单元测试、组件测试、集成测试、钩子测试、源内测试。使用 React Testing Library 测试 React 组件。测试 TanStack Query/Router/Form 模式。
不适用场景: 端到端测试(请使用 Playwright)、视觉回归测试(请使用 Percy/Chromatic)、负载测试(请使用 k6)。

Quick Reference

快速参考

PatternAPIKey Points
Test structure
describe('suite', () => {})
Organize related tests
Single test
test('behavior', () => {})
or
it()
Both are aliases
Parameterized tests
test.each([...])('name', (arg) => {})
Run same test with different inputs
Concurrent tests
test.concurrent('name', async () => {})
Run tests in parallel
Skip test
test.skip('name', () => {})
or
skipIf(cond)
Conditionally skip tests
Only test
test.only('name', () => {})
Run specific test for debugging
Assertions
expect(value).toBe(expected)
Compare primitive values
Deep equality
expect(obj).toEqual(expected)
Compare objects/arrays
Async assertions
await expect(promise).resolves.toBe(value)
Test promise resolution
Before each test
beforeEach(() => {})
Setup before each test
After each test
afterEach(() => {})
Cleanup after each test
Mock function
vi.fn()
Create spy function
Mock module
vi.mock('./module')
Replace entire module
Spy on method
vi.spyOn(obj, 'method')
Track calls to existing method
Clear mocks
vi.clearAllMocks()
Clear call history
Fake timers
vi.useFakeTimers()
Control setTimeout/setInterval
Render component
render(<Component />)
Mount React component for testing
Query by role
screen.getByRole('button')
Find elements by accessibility role
User interaction
await user.click(element)
Simulate user events
Wait for change
await waitFor(() => expect(...))
Wait for async changes
Find async element
await screen.findByText('text')
Query + wait combined
Render hook
renderHook(() => useHook())
Test custom hooks
Update hook props
rerender(newProps)
Re-render hook with new props
Snapshot
expect(value).toMatchSnapshot()
Compare against saved snapshot
Inline snapshot
expect(value).toMatchInlineSnapshot()
Snapshot stored in test file
模式API关键要点
测试结构
describe('suite', () => {})
组织相关测试用例
单个测试用例
test('behavior', () => {})
it()
两者是别名
参数化测试
test.each([...])('name', (arg) => {})
使用不同输入运行相同测试用例
并发测试
test.concurrent('name', async () => {})
并行运行测试用例
跳过测试
test.skip('name', () => {})
skipIf(cond)
有条件地跳过测试用例
仅运行指定测试
test.only('name', () => {})
运行特定测试用例以进行调试
断言
expect(value).toBe(expected)
比较原始值
深度相等
expect(obj).toEqual(expected)
比较对象/数组
异步断言
await expect(promise).resolves.toBe(value)
测试 Promise 解析结果
每个测试前执行
beforeEach(() => {})
在每个测试前进行设置
每个测试后执行
afterEach(() => {})
在每个测试后进行清理
模拟函数
vi.fn()
创建间谍函数
模拟模块
vi.mock('./module')
替换整个模块
监听方法
vi.spyOn(obj, 'method')
跟踪现有方法的调用情况
清除模拟
vi.clearAllMocks()
清除调用历史
假定时器
vi.useFakeTimers()
控制 setTimeout/setInterval
渲染组件
render(<Component />)
挂载 React 组件以进行测试
按角色查询
screen.getByRole('button')
按无障碍角色查找元素
用户交互
await user.click(element)
模拟用户事件
等待变更
await waitFor(() => expect(...))
等待异步变更
查找异步元素
await screen.findByText('text')
查询与等待的结合
渲染钩子
renderHook(() => useHook())
测试自定义钩子
更新钩子属性
rerender(newProps)
使用新属性重新渲染钩子
快照
expect(value).toMatchSnapshot()
与保存的快照进行比较
内联快照
expect(value).toMatchInlineSnapshot()
快照存储在测试文件中

Common Mistakes

常见错误

MistakeCorrect Pattern
Using
getBy
for async content
Use
findBy
or
waitFor
for async
Testing implementation detailsTest behavior and public API
Using
getByTestId
as first choice
Prefer
getByRole
,
getByLabelText
,
getByText
Missing
userEvent.setup()
Always call
const user = userEvent.setup()
first
Shared state between testsUse
beforeEach
to reset or create fresh instances
Not cleaning up mocksUse
vi.clearAllMocks()
in
afterEach
Mocking too muchOnly mock external dependencies and APIs
Not disabling retries in testsSet
retry: false
for TanStack Query tests
Immediate assertions on asyncUse
await waitFor()
or
findBy
queries
Creating QueryClient in renderCreate once in wrapper or use
useState
Testing library codeTrust the library, test your usage
Not awaiting user eventsAll
user.*
methods return promises
Using
act
manually
userEvent
and Testing Library handle this
Inline select without memoizationExtract to stable function for TanStack Query
错误正确做法
对异步内容使用
getBy
对异步内容使用
findBy
waitFor
测试实现细节测试行为和公共 API
优先使用
getByTestId
优先使用
getByRole
getByLabelText
getByText
遗漏
userEvent.setup()
始终先调用
const user = userEvent.setup()
测试间共享状态使用
beforeEach
重置或创建新实例
未清理模拟
afterEach
中使用
vi.clearAllMocks()
过度模拟仅模拟外部依赖和 APIs
未在测试中禁用重试为 TanStack Query 测试设置
retry: false
对异步内容立即断言使用
await waitFor()
findBy
查询
在渲染中创建 QueryClient在包装器中创建一次或使用
useState
测试库代码信任库,测试你的使用方式
未等待用户事件所有
user.*
方法都返回 Promise
手动使用
act
userEvent
和 Testing Library 会处理此问题
内联选择器未进行记忆化提取为稳定函数以用于 TanStack Query

Delegation

任务委托

  • Test discovery: For finding untested code paths, use
    Explore
    agent
  • Coverage analysis: For comprehensive coverage review, use
    Task
    agent
  • E2E testing: If
    playwright
    skill is available, delegate E2E testing to it
  • Code review: After writing tests, delegate to
    code-reviewer
    agent
  • 测试发现:若要查找未测试的代码路径,请使用
    Explore
    agent
  • 覆盖率分析:若要进行全面的覆盖率审查,请使用
    Task
    agent
  • 端到端测试:如果有
    playwright
    技能,请将端到端测试委托给它
  • 代码审查:编写完测试后,委托给
    code-reviewer
    agent

References

参考资料

  • Test fundamentals: structure, assertions, lifecycle hooks
  • Mocking: vi.fn, vi.mock, vi.spyOn, module mocking
  • Component testing: React Testing Library, queries, user-event
  • Hook testing: renderHook, async hooks, TanStack patterns
  • Configuration: vitest.config.ts, workspace, coverage, reporters
  • Advanced patterns: snapshots, concurrent tests, in-source, type testing
  • 测试基础:结构、断言、生命周期钩子
  • 模拟:vi.fn、vi.mock、vi.spyOn、模块模拟
  • 组件测试:React Testing Library、查询、user-event
  • 钩子测试:renderHook、异步钩子、TanStack 模式
  • 配置:vitest.config.ts、工作区、覆盖率、报告器
  • 高级模式:快照、并发测试、源内测试、类型测试