跨语言和框架编写与运行测试。
| 语言 | 单元测试 | 集成测试 | 端到端测试 |
|---|---|---|---|
| TypeScript/JS | Vitest (推荐), Jest | Supertest | Playwright |
| Python | pytest | pytest + httpx | Playwright |
| Swift | XCTest | XCTest | XCUITest |
npm install -D vitest @testing-library/react @testing-library/jest-dom
// vitest.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
globals: true,
environment: 'jsdom',
setupFiles: './tests/setup.ts',
},
})
npx vitest # 监听模式
npx vitest run # 单次运行
npx vitest --coverage # 包含覆盖率
npm install -D jest @types/jest ts-jest
npx jest # 运行所有测试
npx jest --watch # 监听模式
npx jest --coverage # 包含覆盖率
npx jest path/to/test # 运行单个文件
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 # 简短回溯信息
swift test # 运行所有测试
swift test --filter MyTests # 运行特定测试套件
swift test --parallel # 并行执行
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 # 查看 HTML 报告
┌─────────┐ ┌─────────┐ ┌──────────┐
│ 编写 │────▶│ 编写 │────▶│ 重构 │──┐
│ 测试 │ │ 代码 │ │ 代码 │ │
│ (红) │ │ (绿) │ │ │ │
└─────────┘ └─────────┘ └──────────┘ │
▲ │
└──────────────────────────────────────────┘
test('计算含税总额', () => {
// 准备
const cart = new Cart([{ price: 100, qty: 2 }]);
// 执行
const total = cart.totalWithTax(0.08);
// 断言
expect(total).toBe(216);
});
test('获取用户数据', async () => {
const user = await getUser('123');
expect(user.name).toBe('Colt');
});
import { vi } from 'vitest';
const mockFetch = vi.fn().mockResolvedValue({
json: () => Promise.resolve({ id: 1, name: 'Test' }),
});
vi.stubGlobal('fetch', mockFetch);
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)
import { render, screen, fireEvent } from '@testing-library/react';
import { Button } from './Button';
test('点击时调用 onClick', () => {
const handleClick = vi.fn();
render(<Button onClick={handleClick}>点击我</Button>);
fireEvent.click(screen.getByText('点击我'));
expect(handleClick).toHaveBeenCalledOnce();
});
# JavaScript/TypeScript
npx vitest --coverage # Vitest (使用 v8 或 istanbul)
npx jest --coverage # Jest
# Python
pytest --cov=app --cov-report=html # HTML 报告
pytest --cov=app --cov-report=term # 终端输出
pytest --cov=app --cov-fail-under=80 # 覆盖率低于 80% 则失败
# 查看 HTML 覆盖率报告
open coverage/index.html # macOS
open htmlcov/index.html # Python
始终测试:
- 公共 API / 导出的函数
- 边界情况:空输入、null、边界值
- 错误处理:无效输入、网络故障
- 业务逻辑:计算、状态转换
无需测试:
- 私有实现细节
- 框架内部机制(React 渲染、Express 路由)
- 简单的 getter/setter
- 第三方库的行为