writing-tests

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Writing Tests

编写测试

Write effective tests using Vitest and React Testing Library.
使用Vitest和React Testing Library编写高效的测试。

Quick Start

快速开始

Create a unit test in
src/common/__tests__/utils/math.test.ts
:
typescript
import { describe, it, expect } from 'vitest';
import { add } from '../../utils/math';

describe('math utility', () => {
  it('adds two numbers correctly', () => {
    expect(add(1, 2)).toBe(3);
  });
});
Run tests with
npm run test
.
src/common/__tests__/utils/math.test.ts
中创建单元测试:
typescript
import { describe, it, expect } from 'vitest';
import { add } from '../../utils/math';

describe('math utility', () => {
  it('adds two numbers correctly', () => {
    expect(add(1, 2)).toBe(3);
  });
});
使用
npm run test
运行测试。

Core Patterns

核心模式

Unit Testing

单元测试

Focus on pure functions and logic in
src/main
or
src/common
. Use
vi.mock()
for dependencies.
  • references/unit-testing-examples.md
聚焦于
src/main
src/common
中的纯函数与逻辑。使用
vi.mock()
处理依赖项。
  • references/unit-testing-examples.md

Component Testing

组件测试

Test React components in
src/renderer
. Focus on user interactions and props.
  • references/component-testing-patterns.md
测试
src/renderer
中的React组件。聚焦于用户交互与属性。
  • references/component-testing-patterns.md

Mocking

模拟

Use centralized mock factories for consistent testing across components and contexts.
  • references/mocking-guide.md - Mock factories and API patterns
使用集中式模拟工厂,确保跨组件和上下文的测试一致性。
  • references/mocking-guide.md - 模拟工厂与API模式

Debugging Failing Tests

调试失败的测试

  1. Read the error output and identify the failing assertion
  2. Check mock setup — verify
    vi.mock()
    paths and return values match expectations
  3. For component tests, inspect rendered output with
    screen.debug()
  4. Run a single test in isolation:
    npm run test:node -- --no-color -t "test name"
  5. Verify coverage:
    npm run test:coverage
    to confirm new code is tested
  1. 读取错误输出并定位失败的断言
  2. 检查模拟设置——确认
    vi.mock()
    的路径和返回值符合预期
  3. 对于组件测试,使用
    screen.debug()
    检查渲染输出
  4. 单独运行单个测试:
    npm run test:node -- --no-color -t "测试名称"
  5. 验证覆盖率:使用
    npm run test:coverage
    确认新代码已被测试

Advanced Usage

高级用法

For detailed information:
  • references/test-organization.md - Directory structure and naming
  • references/running-tests.md - CLI commands and coverage
  • references/best-practices.md - Principles and patterns
  • references/test-patterns.md - Code templates
  • assets/test-checklist.md - Pre-flight checklist
如需详细信息:
  • references/test-organization.md - 目录结构与命名规范
  • references/running-tests.md - CLI命令与覆盖率
  • references/best-practices.md - 原则与模式
  • references/test-patterns.md - 代码模板
  • assets/test-checklist.md - 预检查清单