vitest-skill
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseVitest Testing Skill
Vitest 测试 Skill
Core Patterns
核心模式
Basic Test
基础测试
typescript
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { Calculator } from './calculator';
describe('Calculator', () => {
let calc: Calculator;
beforeEach(() => { calc = new Calculator(); });
it('adds two numbers', () => {
expect(calc.add(2, 3)).toBe(5);
});
it('throws on divide by zero', () => {
expect(() => calc.divide(10, 0)).toThrow();
});
});typescript
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { Calculator } from './calculator';
describe('Calculator', () => {
let calc: Calculator;
beforeEach(() => { calc = new Calculator(); });
it('adds two numbers', () => {
expect(calc.add(2, 3)).toBe(5);
});
it('throws on divide by zero', () => {
expect(() => calc.divide(10, 0)).toThrow();
});
});Mocking (vi instead of jest)
Mock(使用 vi 而不是 jest)
typescript
import { vi } from 'vitest';
// Mock module
vi.mock('./database', () => ({
getUser: vi.fn().mockResolvedValue({ name: 'Alice' }),
saveUser: vi.fn().mockResolvedValue(true),
}));
// Mock function
const mockFn = vi.fn();
mockFn.mockReturnValue(42);
mockFn.mockResolvedValue({ data: 'test' });
// Spy
const spy = vi.spyOn(console, 'log').mockImplementation(() => {});
expect(spy).toHaveBeenCalledWith('message');
spy.mockRestore();
// Timers
vi.useFakeTimers();
vi.advanceTimersByTime(1000);
vi.runAllTimers();
vi.useRealTimers();typescript
import { vi } from 'vitest';
// Mock module
vi.mock('./database', () => ({
getUser: vi.fn().mockResolvedValue({ name: 'Alice' }),
saveUser: vi.fn().mockResolvedValue(true),
}));
// Mock function
const mockFn = vi.fn();
mockFn.mockReturnValue(42);
mockFn.mockResolvedValue({ data: 'test' });
// Spy
const spy = vi.spyOn(console, 'log').mockImplementation(() => {});
expect(spy).toHaveBeenCalledWith('message');
spy.mockRestore();
// Timers
vi.useFakeTimers();
vi.advanceTimersByTime(1000);
vi.runAllTimers();
vi.useRealTimers();In-Source Testing
源码内测试
typescript
// src/math.ts — tests alongside code!
export function add(a: number, b: number) { return a + b; }
export function multiply(a: number, b: number) { return a * b; }
if (import.meta.vitest) {
const { it, expect } = import.meta.vitest;
it('adds', () => { expect(add(2, 3)).toBe(5); });
it('multiplies', () => { expect(multiply(3, 4)).toBe(12); });
}typescript
// src/math.ts — tests alongside code!
export function add(a: number, b: number) { return a + b; }
export function multiply(a: number, b: number) { return a * b; }
if (import.meta.vitest) {
const { it, expect } = import.meta.vitest;
it('adds', () => { expect(add(2, 3)).toBe(5); });
it('multiplies', () => { expect(multiply(3, 4)).toBe(12); });
}Snapshot Testing
Snapshot 测试
typescript
it('serializes user', () => {
expect(serializeUser(user)).toMatchSnapshot();
});
it('inline snapshot', () => {
expect(serializeUser(user)).toMatchInlineSnapshot(`
{ "name": "Alice", "email": "alice@test.com" }
`);
});typescript
it('serializes user', () => {
expect(serializeUser(user)).toMatchSnapshot();
});
it('inline snapshot', () => {
expect(serializeUser(user)).toMatchInlineSnapshot(`
{ "name": "Alice", "email": "alice@test.com" }
`);
});React Component Testing
React 组件测试
typescript
import { render, screen } from '@testing-library/react';
import { describe, it, expect } from 'vitest';
import Button from './Button';
describe('Button', () => {
it('renders with label', () => {
render(<Button label="Click me" />);
expect(screen.getByText('Click me')).toBeDefined();
});
});typescript
import { render, screen } from '@testing-library/react';
import { describe, it, expect } from 'vitest';
import Button from './Button';
describe('Button', () => {
it('renders with label', () => {
render(<Button label="Click me" />);
expect(screen.getByText('Click me')).toBeDefined();
});
});Anti-Patterns
反模式
| Bad | Good | Why |
|---|---|---|
| | Vitest uses |
| | Different namespace |
| No type safety | TypeScript + strict | Vitest is TS-first |
| 不推荐 | 推荐 | 原因 |
|---|---|---|
| | Vitest 使用 |
| | 命名空间不同 |
| 缺少类型安全 | TypeScript + strict | Vitest 以 TypeScript 为先 |
Quick Reference
快速参考
| Task | Command |
|---|---|
| Run once | |
| Watch | |
| UI | |
| Coverage | |
| Specific file | |
| Filter | |
| 任务 | 命令 |
|---|---|
| 单次运行 | |
| 监听模式 | |
| UI | |
| 覆盖率 | |
| 指定文件 | |
| 筛选 | |
vitest.config.ts
vitest.config.ts
typescript
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'jsdom',
coverage: { provider: 'v8', reporter: ['text', 'html'] },
include: ['src/**/*.{test,spec}.{js,ts,tsx}'],
includeSource: ['src/**/*.{js,ts}'],
},
});typescript
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'jsdom',
coverage: { provider: 'v8', reporter: ['text', 'html'] },
include: ['src/**/*.{test,spec}.{js,ts,tsx}'],
includeSource: ['src/**/*.{js,ts}'],
},
});Deep Patterns → reference/playbook.md
reference/playbook.md深入模式 → reference/playbook.md
reference/playbook.md| § | Section | Lines |
|---|---|---|
| 1 | Production Configuration | Config, workspace, setup file |
| 2 | Mocking Patterns | vi.mock, spies, timers, fetch |
| 3 | React Testing Library | Components, hooks, providers |
| 4 | Snapshot & Inline Snapshots | File, inline, serializers |
| 5 | Table-Driven Tests | test.each, describe.each |
| 6 | In-Source Testing | Co-located tests in source |
| 7 | API / Integration Testing | Server tests with fetch |
| 8 | CI/CD Integration | GitHub Actions, scripts |
| 9 | Debugging Quick-Reference | 10 common problems |
| 10 | Best Practices Checklist | 13 items |
| § | 章节 | 行数 |
|---|---|---|
| 1 | 生产环境配置 | 配置、工作区、设置文件 |
| 2 | Mock 模式 | vi.mock、spy、计时器、fetch |
| 3 | React Testing Library | 组件、hooks、providers |
| 4 | Snapshot 与 Inline Snapshot | 文件、内联、序列化器 |
| 5 | 表格驱动测试 | test.each、describe.each |
| 6 | 源码内测试 | 与源代码同置的测试 |
| 7 | API / 集成测试 | 使用 fetch 的服务器测试 |
| 8 | CI/CD 集成 | GitHub Actions、脚本 |
| 9 | 调试快速参考 | 10 个常见问题 |
| 10 | 最佳实践检查清单 | 13 项 |