vitest-testing
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseVitest 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 Vitest | Writing E2E browser tests (use playwright-testing) |
| Writing unit/integration tests in TS/JS | Testing Python code (use python-testing) |
| Migrating from Jest to Vitest | Analyzing test quality (use test-quality-analysis) |
| Configuring coverage thresholds | Generating property-based tests (use property-based-testing) |
| Using mocks, spies, or fake timers | Validating 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 # Verifybash
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 modebash
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
常用断言
| Assertion | Description |
|---|---|
| Strict equality |
| Deep equality |
| Deep strict equality |
| Truthiness |
| Null checks |
| Numeric comparison |
| Float comparison |
| String matching |
| Array/string length |
| Object property |
| Partial object match |
| Error throwing |
| 断言方法 | 描述 |
|---|---|
| 严格相等判断 |
| 深度相等判断 |
| 严格深度相等判断 |
| 真假值判断 |
| Null/Undefined判断 |
| 数值比较 |
| 浮点数近似比较 |
| 字符串匹配 |
| 数组/字符串长度判断 |
| 对象属性存在判断 |
| 部分对象匹配 |
| 异常抛出判断 |
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 -utypescript
test('快照测试', () => {
expect(data).toMatchSnapshot();
});
test('内联快照', () => {
expect(result).toMatchInlineSnapshot('5');
});
// 更新快照:bunx vitest -uCoverage
代码覆盖率
bash
bun add --dev @vitest/coverage-v8
bunx vitest --coverageKey config options: , , , , .
providerreporterincludeexcludethresholdsbash
bun add --dev @vitest/coverage-v8
bunx vitest --coverage关键配置选项:、、、、。
providerreporterincludeexcludethresholdsAgentic Optimizations
智能优化命令
| Context | Command |
|---|---|
| Quick test | |
| CI test | |
| Coverage check | |
| Single file | |
| Failed only | |
For detailed examples, advanced patterns, and best practices, see REFERENCE.md.
| 场景 | 命令 |
|---|---|
| 快速测试 | |
| CI环境测试 | |
| 覆盖率检查 | |
| 单个文件测试 | |
| 仅运行失败的测试 | |
如需详细示例、高级模式和最佳实践,请查看REFERENCE.md。
References
参考资料
- Official docs: https://vitest.dev
- Configuration: https://vitest.dev/config/
- API reference: https://vitest.dev/api/
- Migration from Jest: https://vitest.dev/guide/migration.html
- Coverage: https://vitest.dev/guide/coverage.html