vitest-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Vitest Testing

Vitest 测试

Vitest is a modern test runner designed for Vite projects. It's fast, ESM-native, and provides a Jest-compatible API with better TypeScript support and instant HMR-powered watch mode.
Vitest是为Vite项目设计的现代化测试运行器。它速度快、原生支持ESM,并提供与Jest兼容的API,同时具备更出色的TypeScript支持和由HMR驱动的即时监听模式。

When to Use This Skill

何时使用该技能

Use this skill when...Use another skill instead when...
Setting up or configuring VitestWriting E2E browser tests (use playwright-testing)
Writing unit/integration tests in TS/JSTesting Python code (use python-testing)
Migrating from Jest to VitestAnalyzing test quality (use test-quality-analysis)
Configuring coverage thresholdsGenerating property-based tests (use property-based-testing)
Using mocks, spies, or fake timersValidating test effectiveness (use mutation-testing)
适用场景应使用其他技能的场景
搭建或配置Vitest编写端到端浏览器测试(使用playwright-testing)
使用TS/JS编写单元/集成测试测试Python代码(使用python-testing)
从Jest迁移到Vitest分析测试质量(使用test-quality-analysis)
配置覆盖率阈值生成基于属性的测试(使用property-based-testing)
使用模拟、间谍或假计时器验证测试有效性(使用mutation-testing)

Core Expertise

核心特性

  • Vite-native: Reuses Vite config, transforms, and plugins
  • Fast: Instant feedback with HMR-powered watch mode
  • Jest-compatible: Drop-in replacement with similar API
  • TypeScript: First-class TypeScript support
  • ESM: Native ESM support, no transpilation needed
  • 原生适配Vite:复用Vite的配置、转换规则和插件
  • 速度快:借助HMR驱动的监听模式实现即时反馈
  • 兼容Jest:可直接替代Jest,API风格相似
  • TypeScript支持:一流的TypeScript支持
  • ESM原生支持:原生支持ESM,无需转译

Installation

安装

bash
bun add --dev vitest
bun add --dev @vitest/coverage-v8      # Coverage (recommended)
bun add --dev happy-dom                # DOM testing (optional)
bunx vitest --version                  # Verify
bash
bun add --dev vitest
bun add --dev @vitest/coverage-v8      # 代码覆盖率(推荐)
bun add --dev happy-dom                # DOM测试(可选)
bunx vitest --version                  # 验证安装

Configuration (vitest.config.ts)

配置(vitest.config.ts)

typescript
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    environment: 'node',
  },
});
typescript
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    environment: 'node',
  },
});

Essential Commands

常用命令

bash
bunx vitest                            # Watch mode (default)
bunx vitest run                        # Run once (CI mode)
bunx vitest --coverage                 # With coverage
bunx vitest src/utils.test.ts          # Specific file
bunx vitest -t "should add numbers"    # Filter by name
bunx vitest related src/utils.ts       # Related tests
bunx vitest -u                         # Update snapshots
bunx vitest bench                      # Benchmarks
bunx vitest --ui                       # UI mode
bash
bunx vitest                            # 监听模式(默认)
bunx vitest run                        # 单次运行(CI模式)
bunx vitest --coverage                 # 生成覆盖率报告
bunx vitest src/utils.test.ts          # 运行指定文件的测试
bunx vitest -t "should add numbers"    # 按测试名称过滤
bunx vitest related src/utils.ts       # 运行与指定文件相关的测试
bunx vitest -u                         # 更新快照
bunx vitest bench                      # 基准测试
bunx vitest --ui                       # UI模式

Writing Tests

编写测试

Basic Test Structure

基础测试结构

typescript
import { describe, it, expect } from 'vitest';
import { add, multiply } from './math';

describe('math utils', () => {
  it('should add two numbers', () => {
    expect(add(2, 3)).toBe(5);
  });

  it('should multiply two numbers', () => {
    expect(multiply(2, 3)).toBe(6);
  });
});
typescript
import { describe, it, expect } from 'vitest';
import { add, multiply } from './math';

describe('数学工具函数', () => {
  it('应该正确计算两个数的和', () => {
    expect(add(2, 3)).toBe(5);
  });

  it('应该正确计算两个数的乘积', () => {
    expect(multiply(2, 3)).toBe(6);
  });
});

Key Assertions

常用断言

AssertionDescription
toBe(value)
Strict equality
toEqual(value)
Deep equality
toStrictEqual(value)
Deep strict equality
toBeTruthy()
/
toBeFalsy()
Truthiness
toBeNull()
/
toBeUndefined()
Null checks
toBeGreaterThan(n)
/
toBeLessThan(n)
Numeric comparison
toBeCloseTo(n)
Float comparison
toMatch(regex)
/
toContain(str)
String matching
toHaveLength(n)
Array/string length
toHaveProperty(key)
Object property
toMatchObject(obj)
Partial object match
toThrow(msg)
Error throwing
断言方法描述
toBe(value)
严格相等判断
toEqual(value)
深度相等判断
toStrictEqual(value)
严格深度相等判断
toBeTruthy()
/
toBeFalsy()
真假值判断
toBeNull()
/
toBeUndefined()
Null/Undefined判断
toBeGreaterThan(n)
/
toBeLessThan(n)
数值比较
toBeCloseTo(n)
浮点数近似比较
toMatch(regex)
/
toContain(str)
字符串匹配
toHaveLength(n)
数组/字符串长度判断
toHaveProperty(key)
对象属性存在判断
toMatchObject(obj)
部分对象匹配
toThrow(msg)
异常抛出判断

Async Tests

异步测试

typescript
test('async test', async () => {
  const data = await fetchData();
  expect(data).toBe('expected');
});

test('promise resolves', async () => {
  await expect(fetchData()).resolves.toBe('expected');
});

test('promise rejects', async () => {
  await expect(fetchBadData()).rejects.toThrow('error');
});
typescript
test('异步测试', async () => {
  const data = await fetchData();
  expect(data).toBe('expected');
});

test('Promise成功解析', async () => {
  await expect(fetchData()).resolves.toBe('expected');
});

test('Promise拒绝', async () => {
  await expect(fetchBadData()).rejects.toThrow('error');
});

Mocking (Essential Patterns)

模拟(核心模式)

typescript
import { vi, test, expect } from 'vitest';

// Mock function
const mockFn = vi.fn();
mockFn.mockReturnValue(42);

// Mock module
vi.mock('./api', () => ({
  fetchUser: vi.fn(() => Promise.resolve({ id: 1, name: 'John' })),
}));

// Mock timers
vi.useFakeTimers();
vi.advanceTimersByTime(1000);
vi.restoreAllMocks();

// Spy on method
const spy = vi.spyOn(object, 'method');
typescript
import { vi, test, expect } from 'vitest';

// 模拟函数
const mockFn = vi.fn();
mockFn.mockReturnValue(42);

// 模拟模块
vi.mock('./api', () => ({
  fetchUser: vi.fn(() => Promise.resolve({ id: 1, name: 'John' })),
}));

// 模拟计时器
vi.useFakeTimers();
vi.advanceTimersByTime(1000);
vi.restoreAllMocks();

// 监听方法
const spy = vi.spyOn(object, 'method');

Snapshot Testing

快照测试

typescript
test('snapshot test', () => {
  expect(data).toMatchSnapshot();
});

test('inline snapshot', () => {
  expect(result).toMatchInlineSnapshot('5');
});
// Update snapshots: bunx vitest -u
typescript
test('快照测试', () => {
  expect(data).toMatchSnapshot();
});

test('内联快照', () => {
  expect(result).toMatchInlineSnapshot('5');
});
// 更新快照:bunx vitest -u

Coverage

代码覆盖率

bash
bun add --dev @vitest/coverage-v8
bunx vitest --coverage
Key config options:
provider
,
reporter
,
include
,
exclude
,
thresholds
.
bash
bun add --dev @vitest/coverage-v8
bunx vitest --coverage
关键配置选项:
provider
reporter
include
exclude
thresholds

Agentic Optimizations

智能优化命令

ContextCommand
Quick test
bunx vitest --reporter=dot --bail=1
CI test
bunx vitest run --reporter=junit
Coverage check
bunx vitest --coverage --reporter=dot
Single file
bunx vitest run src/utils.test.ts --reporter=dot
Failed only
bunx vitest --changed --bail=1
For detailed examples, advanced patterns, and best practices, see REFERENCE.md.
场景命令
快速测试
bunx vitest --reporter=dot --bail=1
CI环境测试
bunx vitest run --reporter=junit
覆盖率检查
bunx vitest --coverage --reporter=dot
单个文件测试
bunx vitest run src/utils.test.ts --reporter=dot
仅运行失败的测试
bunx vitest --changed --bail=1
如需详细示例、高级模式和最佳实践,请查看REFERENCE.md

References

参考资料