👁️ 440
👍 67
📅 2026-06-13 收录
🔄 2026-06-13 更新

正文内容

测试运行器(Test Runner)

核心工作流

  1. 在进行任何更改之前,先检测项目所用的语言、包管理器以及已配置的测试框架。
  2. 优先复用项目当前的测试技术栈,而非引入新的框架。
  3. 首先运行最小且相关的测试范围;待明确失败原因后,再逐步扩大测试覆盖范围。
  4. 修复缺陷时,应从编写一个失败的测试开始,仅做最小必要代码修改使其通过,随后再进行重构。
  5. 完成修改后,先再次运行窄范围测试,若本地工作流支持,再运行更广范围的测试套件。

框架选型

若项目中已配置测试框架,则直接沿用。若项目尚无测试技术栈,则按以下优先级选择:

语言 单元测试 集成测试 端到端测试
TypeScript / JavaScript Vitest Supertest Playwright
Python pytest pytest + httpx Playwright
Swift XCTest XCTest XCUITest

命令指南

Vitest

npm install -D vitest @testing-library/react @testing-library/jest-dom
npx vitest
npx vitest run
npx vitest --coverage

当项目需要基础配置时,可采用如下默认配置:

import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: './tests/setup.ts',
  },
})

Jest

npm install -D jest @types/jest ts-jest
npx jest
npx jest --watch
npx jest --coverage
npx jest path/to/test

pytest

uv pip install pytest pytest-cov pytest-asyncio httpx
pytest
pytest -v
pytest -x
pytest --cov=app
pytest tests/test_api.py -k "test_login"
pytest --tb=short

XCTest

swift test
swift test --filter MyTests
swift test --parallel

Playwright

npm install -D @playwright/test
npx playwright install
npx playwright test
npx playwright test --headed
npx playwright test --debug
npx playwright test --project=chromium
npx playwright show-report

红–绿–重构(Red-Green-Refactor)

  1. 红(Red):为所需行为编写一个失败的测试
  2. 绿(Green):实施最小可行改动,使该测试通过。
  3. 重构(Refactor):在不改变外部行为的前提下,优化代码结构与可读性。

测试模式

组织–执行–断言(Arrange, Act, Assert)

test('calculates total with tax', () => {
  const cart = new Cart([{ price: 100, qty: 2 }])

  const total = cart.totalWithTax(0.08)

  expect(total).toBe(216)
})

异步测试

test('fetches user data', async () => {
  const user = await getUser('123')
  expect(user.name).toBe('Colt')
})

使用 Vitest 进行模拟(Mocking)

import { vi } from 'vitest'

const mockFetch = vi.fn().mockResolvedValue({
  json: () => Promise.resolve({ id: 1, name: 'Test' }),
})

vi.stubGlobal('fetch', mockFetch)

Python 中的 API 测试

import pytest
from httpx import AsyncClient
from app.main import app


@pytest.mark.asyncio
async def test_get_users():
    async with AsyncClient(app=app, base_url="http://test") as client:
        response = await client.get("/users")

    assert response.status_code == 200
    assert isinstance(response.json(), list)

React 组件测试

import { fireEvent, render, screen } from '@testing-library/react'
import { Button } from './Button'

test('calls onClick when clicked', () => {
  const handleClick = vi.fn()
  render(Click me)
  fireEvent.click(screen.getByText('Click me'))
  expect(handleClick).toHaveBeenCalledOnce()
})

覆盖率命令

# JavaScript / TypeScript
npx vitest --coverage
npx jest --coverage

# Python
pytest --cov=app --cov-report=html
pytest --cov=app --cov-report=term
pytest --cov=app --cov-fail-under=80

应该测试的内容

务必覆盖以下方面:

  • 公共 API 与导出函数
  • 边界场景:空输入、null、极值等
  • 错误处理逻辑:如非法输入、网络异常等
  • 业务逻辑:如数值计算、状态流转等

通常无需测试:

  • 私有实现细节
  • 框架内部机制
  • 简单的 getter/setter 方法
  • 第三方库自身的行为