vitest_runner
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseVitest
Vitest
Description
描述
Modern JavaScript/TypeScript testing with Vitest including mocking and coverage.
使用Vitest进行现代化JavaScript/TypeScript测试,包括模拟和覆盖率统计。
When to Use
适用场景
- Testing JavaScript/TypeScript
- React component testing
- Unit and integration tests
- 测试JavaScript/TypeScript代码
- React组件测试
- 单元测试与集成测试
Core Patterns
核心模式
Basic Tests
基础测试
typescript
import { describe, it, expect } from 'vitest';
describe('math', () => {
it('should add numbers', () => {
expect(1 + 1).toBe(2);
});
it('should throw on invalid input', () => {
expect(() => divide(1, 0)).toThrow('Division by zero');
});
});typescript
import { describe, it, expect } from 'vitest';
describe('math', () => {
it('should add numbers', () => {
expect(1 + 1).toBe(2);
});
it('should throw on invalid input', () => {
expect(() => divide(1, 0)).toThrow('Division by zero');
});
});Mocking
模拟
typescript
import { vi, describe, it, expect } from 'vitest';
// Mock module
vi.mock('./api', () => ({
fetchUser: vi.fn().mockResolvedValue({ id: 1 })
}));
// Mock function
const callback = vi.fn();
callback('arg');
expect(callback).toHaveBeenCalledWith('arg');typescript
import { vi, describe, it, expect } from 'vitest';
// Mock module
vi.mock('./api', () => ({
fetchUser: vi.fn().mockResolvedValue({ id: 1 })
}));
// Mock function
const callback = vi.fn();
callback('arg');
expect(callback).toHaveBeenCalledWith('arg');Async Tests
异步测试
typescript
it('should fetch data', async () => {
const data = await fetchData();
expect(data).toEqual({ id: 1 });
});
it('should reject on error', async () => {
await expect(fetchData()).rejects.toThrow('Error');
});typescript
it('should fetch data', async () => {
const data = await fetchData();
expect(data).toEqual({ id: 1 });
});
it('should reject on error', async () => {
await expect(fetchData()).rejects.toThrow('Error');
});React Testing
React测试
typescript
import { render, screen } from '@testing-library/react';
import { userEvent } from '@testing-library/user-event';
it('should handle click', async () => {
const onClick = vi.fn();
render(<Button onClick={onClick}>Click</Button>);
await userEvent.click(screen.getByRole('button'));
expect(onClick).toHaveBeenCalled();
});typescript
import { render, screen } from '@testing-library/react';
import { userEvent } from '@testing-library/user-event';
it('should handle click', async () => {
const onClick = vi.fn();
render(<Button onClick={onClick}>Click</Button>);
await userEvent.click(screen.getByRole('button'));
expect(onClick).toHaveBeenCalled();
});🔄 Workflow
🔄 工作流程
来源: Vitest官方文档 & Vite + Testing最佳实践
Aşama 1: Environment & Setup
步骤1:环境与配置
- Vite Integration: dosyasının Vite ayarlarıyla senkronize olduğunu doğrula.
vitest.config.ts - Environment Choice: Web projeleri için veya
jsdom, backend içinhappy-domenvironment'ı seç.node - Global Mocks: Sık kullanılan harici servisler (API, LocalStorage) için içinde global mock'ları tanımla.
setup.ts
- Vite集成: 确保文件与Vite设置同步。
vitest.config.ts - 环境选择: Web项目选择或
jsdom,后端选择happy-dom环境。node - 全局模拟: 在中为常用外部服务(API、LocalStorage)定义全局模拟。
setup.ts
Aşama 2: Unit & Component Testing
步骤2:单元与组件测试
- Isolation Layer: Bağımlılıkları ile izole ederek sadece hedef üniteyi test et.
vi.mock() - Assertion Strategy: metodlarını kullanarak beklenen sonuçları (be.truthy, toEqual, toBeCalled) doğrula.
expect - Snapshot Testing: UI bileşenlerindeki (Component) beklenmedik arayüz değişikliklerini ile yakala.
toMatchSnapshot()
- 隔离层: 使用隔离依赖,仅测试目标单元。
vi.mock() - 断言策略: 使用方法验证预期结果(如toBeTruthy、toEqual、toBeCalled)。
expect - 快照测试: 使用捕获UI组件中意外的界面变化。
toMatchSnapshot()
Aşama 3: Performance & Coverage
步骤3:性能与覆盖率
- Watch Mode: Geliştirme sürecinde testleri modunda tutarak anlık geri bildirim al.
watch - Coverage Analysis: veya
v8provider kullanarak test kapsamını raporla.istanbul - Dependency Cleanup: ile testler arası veri kirliliğini (Pollution) önle.
vi.clearAllMocks()
- 监听模式: 在开发过程中保持测试处于模式,获取实时反馈。
watch - 覆盖率分析: 使用或
v8提供程序生成测试覆盖率报告。istanbul - 依赖清理: 使用避免测试间的数据污染。
vi.clearAllMocks()
Kontrol Noktaları
检查点
| Aşama | Doğrulama |
|---|---|
| 1 | Test dosyaları |
| 2 | Asenkron kodlar ( |
| 3 | Karmaşık nesne karşılaştırmalarında |
Vitest Runner v1.5 - With Workflow
| 步骤 | 验证内容 |
|---|---|
| 1 | 测试文件是否为 |
| 2 | 异步代码( |
| 3 | 在复杂对象比较中是否使用了 |
Vitest Runner v1.5 - 包含工作流程