mcpField
V
vitest-testing

vitest-testing

github.com/secondsky测试与质量2401.3k 次安装5 周前更新
代码仓库

关于 vitest-testing

为 JavaScript 和 TypeScript 项目提供 Vitest 测试实践指南,面向编写和维护测试的开发者。内容涵盖测试编写、模拟、覆盖率及集成测试。

主要功能

  1. 01测试配置与运行
  2. 02断言与参数化测试
  3. 03函数及模块模拟
  4. 04假定时器测试
  5. 05覆盖率与集成测试

适用场景

  1. 01为源文件编写对应测试
  2. 02模拟外部依赖和异步函数
  3. 03生成覆盖率报告
  4. 04使用 Supertest 测试 API 端点

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/secondsky/claude-skills --skill vitest-testing

安装后在 Claude Code 中输入/vitest-testing确认已加载。

详细介绍

Vitest 测试

使用 Vitest 测试 JavaScript/TypeScript 项目的专业知识——Vitest 是由 Vite 驱动的极速测试框架。

快速入门

安装
# Using Bun (recommended)
bun add -d vitest

# Using npm
npm install -D vitest
配置
// vitest.config.ts
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    globals: true,
    environment: 'node', // or 'jsdom'
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
      thresholds: { lines: 80, functions: 80, branches: 80 },
    },
    include: ['**/*.{test,spec}.{js,ts,jsx,tsx}'],
  },
})

运行测试

# Run all tests (prefer bun)
bun test

# Watch mode (default)
bun test --watch

# Run once (CI mode)
bun test --run

# With coverage
bun test --coverage

# Specific file
bun test src/utils/math.test.ts

# Pattern matching
bun test --grep="calculates sum"

# UI mode (interactive)
bun test --ui

# Verbose output (in Vitest 2+, --reporter=verbose prints a flat list;
# use --reporter=tree for the hierarchical tree view)
bun test --reporter=verbose

编写测试

基本结构
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { add, subtract } from './math'

describe('Math utilities', () => {
  beforeEach(() => {
    // Setup before each test
  })

  it('adds two numbers correctly', () => {
    expect(add(2, 3)).toBe(5)
  })

  it('subtracts two numbers correctly', () => {
    expect(subtract(5, 3)).toBe(2)
  })
})
参数化测试
describe.each([
  { input: 2, expected: 4 },
  { input: 3, expected: 9 },
])('square function', ({ input, expected }) => {
  it(`squares ${input} to ${expected}`, () => {
    expect(square(input)).toBe(expected)
  })
})

断言

// Equality
expect(value).toBe(expected)
expect(value).toEqual(expected)

// Truthiness
expect(value).toBeTruthy()
expect(value).toBeNull()
expect(value).toBeDefined()

// Numbers
expect(number).toBeGreaterThan(3)
expect(number).toBeCloseTo(0.3, 1)

// Strings/Arrays
expect(string).toMatch(/pattern/)
expect(array).toContain(item)

// Objects
expect(object).toHaveProperty('key')
expect(object).toMatchObject({ a: 1 })

// Exceptions
expect(() => throwError()).toThrow('message')

// Promises
await expect(promise).resolves.toBe(value)
await expect(promise).rejects.toThrow()

模拟

函数模拟
import { vi } from 'vitest'

const mockFn = vi.fn()
mockFn.mockReturnValue(42)
mockFn.mockResolvedValue('async result')
mockFn.mockImplementation((x) => x * 2)

expect(mockFn).toHaveBeenCalled()
expect(mockFn).toHaveBeenCalledWith('arg')
模块模拟
vi.mock('./api', () => ({
  fetchUser: vi.fn(() => ({ id: 1, name: 'Test User' })),
}))

import { fetchUser } from './api'

beforeEach(() => {
  vi.clearAllMocks()
})
计时器
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.restoreAllMocks())

it('advances timers', () => {
  const callback = vi.fn()
  setTimeout(callback, 1000)
  vi.advanceTimersByTime(1000)
  expect(callback).toHaveBeenCalledOnce()
})

it('mocks dates', () => {
  const date = new Date('2024-01-01')
  vi.setSystemTime(date)
  expect(Date.now()).toBe(date.getTime())
})

覆盖率

# Generate coverage report
bun test --coverage

# HTML report
bun test --coverage --coverage.reporter=html
open coverage/index.html

# Check against thresholds
bun test --coverage --coverage.thresholds.lines=90

集成测试

import request from 'supertest'
import { app } from './app'

describe('API endpoints', () => {
  it('creates a user', async () => {
    const response = await request(app)
      .post('/api/users')
      .send({ name: 'John' })
      .expect(201)

    expect(response.body).toMatchObject({
      id: expect.any(Number),
      name: 'John',
    })
  })
})

最佳实践

  • 每个源文件对应一个测试文件:math.ts → math.test.ts
  • 使用 describe() 代码块将相关测试分组
  • 使用描述性测试名称
  • 只模拟外部依赖
  • 对相互独立的异步测试使用 concurrent
  • 使用 beforeAll() 共享开销较大的测试夹具
  • 目标是达到 80% 以上的覆盖率,但不要一味追求 100%

另请参阅

  • test-quality-analysis - 检测测试异味
  • playwright-testing - 端到端测试
  • mutation-testing - 验证测试有效性

评论

支持 Markdown