vitest_runner

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Vitest

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

🔄 工作流程

Aşama 1: Environment & Setup

步骤1:环境与配置

  • Vite Integration:
    vitest.config.ts
    dosyasının Vite ayarlarıyla senkronize olduğunu doğrula.
  • Environment Choice: Web projeleri için
    jsdom
    veya
    happy-dom
    , backend için
    node
    environment'ı seç.
  • Global Mocks: Sık kullanılan harici servisler (API, LocalStorage) için
    setup.ts
    içinde global mock'ları tanımla.
  • Vite集成: 确保
    vitest.config.ts
    文件与Vite设置同步。
  • 环境选择: Web项目选择
    jsdom
    happy-dom
    ,后端选择
    node
    环境。
  • 全局模拟: 在
    setup.ts
    中为常用外部服务(API、LocalStorage)定义全局模拟。

Aşama 2: Unit & Component Testing

步骤2:单元与组件测试

  • Isolation Layer: Bağımlılıkları
    vi.mock()
    ile izole ederek sadece hedef üniteyi test et.
  • Assertion Strategy:
    expect
    metodlarını kullanarak beklenen sonuçları (be.truthy, toEqual, toBeCalled) doğrula.
  • Snapshot Testing: UI bileşenlerindeki (Component) beklenmedik arayüz değişikliklerini
    toMatchSnapshot()
    ile yakala.
  • 隔离层: 使用
    vi.mock()
    隔离依赖,仅测试目标单元。
  • 断言策略: 使用
    expect
    方法验证预期结果(如toBeTruthy、toEqual、toBeCalled)。
  • 快照测试: 使用
    toMatchSnapshot()
    捕获UI组件中意外的界面变化。

Aşama 3: Performance & Coverage

步骤3:性能与覆盖率

  • Watch Mode: Geliştirme sürecinde testleri
    watch
    modunda tutarak anlık geri bildirim al.
  • Coverage Analysis:
    v8
    veya
    istanbul
    provider kullanarak test kapsamını raporla.
  • Dependency Cleanup:
    vi.clearAllMocks()
    ile testler arası veri kirliliğini (Pollution) önle.
  • 监听模式: 在开发过程中保持测试处于
    watch
    模式,获取实时反馈。
  • 覆盖率分析: 使用
    v8
    istanbul
    提供程序生成测试覆盖率报告。
  • 依赖清理: 使用
    vi.clearAllMocks()
    避免测试间的数据污染。

Kontrol Noktaları

检查点

AşamaDoğrulama
1Test dosyaları
*.test.ts
veya
*.spec.ts
formatında mı?
2Asenkron kodlar (
async/await
) doğru handle ediliyor mu?
3Karmaşık nesne karşılaştırmalarında
toBe
(referans) yerine
toEqual
(değer) mi kullanıldı?

Vitest Runner v1.5 - With Workflow
步骤验证内容
1测试文件是否为
*.test.ts
*.spec.ts
格式?
2异步代码(
async/await
)是否被正确处理?
3在复杂对象比较中是否使用了
toEqual
(值比较)而非
toBe
(引用比较)?

Vitest Runner v1.5 - 包含工作流程