vitest-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Vitest Best Practices

Vitest 最佳实践

Quick Reference

快速参考

ts
import { describe, it, expect, beforeEach, vi } from 'vitest'

describe('feature name', () => {
  beforeEach(() => {
    vi.clearAllMocks()
  })

  it('should do something specific', () => {
    expect(actual).toBe(expected)
  })

  it.todo('planned test')
  it.skip('temporarily disabled')
  it.only('run only this during dev')
})
ts
import { describe, it, expect, beforeEach, vi } from 'vitest'

describe('feature name', () => {
  beforeEach(() => {
    vi.clearAllMocks()
  })

  it('should do something specific', () => {
    expect(actual).toBe(expected)
  })

  it.todo('planned test')
  it.skip('temporarily disabled')
  it.only('run only this during dev')
})

Common Assertions

常用断言

ts
// Equality
expect(value).toBe(42)                    // Strict (===)
expect(obj).toEqual({ a: 1 })             // Deep equality
expect(obj).toStrictEqual({ a: 1 })       // Strict deep (checks types)

// Truthiness
expect(value).toBeTruthy()
expect(value).toBeFalsy()
expect(value).toBeNull()
expect(value).toBeUndefined()

// Numbers
expect(0.1 + 0.2).toBeCloseTo(0.3)
expect(value).toBeGreaterThan(5)

// Strings/Arrays
expect(str).toMatch(/pattern/)
expect(str).toContain('substring')
expect(array).toContain(item)
expect(array).toHaveLength(3)

// Objects
expect(obj).toHaveProperty('key')
expect(obj).toHaveProperty('nested.key', 'value')
expect(obj).toMatchObject({ subset: 'of properties' })

// Exceptions
expect(() => fn()).toThrow()
expect(() => fn()).toThrow('error message')
expect(() => fn()).toThrow(/pattern/)
ts
// Equality
expect(value).toBe(42)                    // Strict (===)
expect(obj).toEqual({ a: 1 })             // Deep equality
expect(obj).toStrictEqual({ a: 1 })       // Strict deep (checks types)

// Truthiness
expect(value).toBeTruthy()
expect(value).toBeFalsy()
expect(value).toBeNull()
expect(value).toBeUndefined()

// Numbers
expect(0.1 + 0.2).toBeCloseTo(0.3)
expect(value).toBeGreaterThan(5)

// Strings/Arrays
expect(str).toMatch(/pattern/)
expect(str).toContain('substring')
expect(array).toContain(item)
expect(array).toHaveLength(3)

// Objects
expect(obj).toHaveProperty('key')
expect(obj).toHaveProperty('nested.key', 'value')
expect(obj).toMatchObject({ subset: 'of properties' })

// Exceptions
expect(() => fn()).toThrow()
expect(() => fn()).toThrow('error message')
expect(() => fn()).toThrow(/pattern/)

Async Testing

异步测试

ts
// Async/await (preferred)
it('fetches data', async () => {
  const data = await fetchData()
  expect(data).toEqual({ id: 1 })
})

// Promise matchers - ALWAYS await these
await expect(fetchData()).resolves.toEqual({ id: 1 })
await expect(fetchData()).rejects.toThrow('Error')

// Wrong - creates false positive
expect(promise).resolves.toBe(value)  // Missing await!
ts
// Async/await (preferred)
it('fetches data', async () => {
  const data = await fetchData()
  expect(data).toEqual({ id: 1 })
})

// Promise matchers - ALWAYS await these
await expect(fetchData()).resolves.toEqual({ id: 1 })
await expect(fetchData()).rejects.toThrow('Error')

// Wrong - creates false positive
expect(promise).resolves.toBe(value)  // Missing await!

Quick Mock Reference

快速模拟参考

ts
const mockFn = vi.fn()
mockFn.mockReturnValue(42)
mockFn.mockResolvedValue({ data: 'value' })

expect(mockFn).toHaveBeenCalled()
expect(mockFn).toHaveBeenCalledWith('arg1', 'arg2')
expect(mockFn).toHaveBeenCalledTimes(2)
ts
const mockFn = vi.fn()
mockFn.mockReturnValue(42)
mockFn.mockResolvedValue({ data: 'value' })

expect(mockFn).toHaveBeenCalled()
expect(mockFn).toHaveBeenCalledWith('arg1', 'arg2')
expect(mockFn).toHaveBeenCalledTimes(2)

Additional Documentation

更多文档

  • Mocking: See references/mocking.md for module mocking, spying, cleanup
  • Configuration: See references/config.md for vitest.config, setup files, coverage
  • Patterns: See references/patterns.md for timers, snapshots, anti-patterns
  • 模拟:关于模块模拟、监听与清理,请查看references/mocking.md
  • 配置:关于vitest.config、设置文件与测试覆盖率,请查看references/config.md
  • 模式:关于定时器、快照与反模式,请查看references/patterns.md

Test Methods Quick Reference

测试方法快速参考

MethodPurpose
it()
/
test()
Define test
describe()
Group tests
beforeEach()
/
afterEach()
Per-test hooks
beforeAll()
/
afterAll()
Per-suite hooks
.skip
Skip test/suite
.only
Run only this
.todo
Placeholder
.concurrent
Parallel execution
.each([...])
Parameterized tests
方法用途
it()
/
test()
定义测试
describe()
分组测试
beforeEach()
/
afterEach()
单测试钩子
beforeAll()
/
afterAll()
套件级钩子
.skip
跳过测试/套件
.only
仅运行当前测试/套件
.todo
占位符
.concurrent
并行执行
.each([...])
参数化测试