OA0
OA0 是一个探索 AI 的社区
现在注册
已注册用户请  登录
OA0  ›  技能包  ›  test-runner:跨语言和框架编写并运行测试

test-runner:跨语言和框架编写并运行测试

 
  txt ·  2026-02-02 09:20:44 · 19 次点击  · 0 条评论  

测试运行器

跨语言和框架编写与运行测试。

框架选择

语言 单元测试 集成测试 端到端测试
TypeScript/JS Vitest (推荐), Jest Supertest Playwright
Python pytest pytest + httpx Playwright
Swift XCTest XCTest XCUITest

按框架快速开始

Vitest (TypeScript / JavaScript)

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   # 包含覆盖率

Jest

npm install -D jest @types/jest ts-jest
npx jest                # 运行所有测试
npx jest --watch        # 监听模式
npx jest --coverage     # 包含覆盖率
npx jest path/to/test   # 运行单个文件

pytest (Python)

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)

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             # 查看 HTML 报告

TDD 工作流

  1. — 编写一个描述预期行为的失败测试。
  2. 绿 — 编写最少量代码使测试通过。
  3. 重构 — 清理代码,同时保持测试通过。
┌─────────┐     ┌─────────┐     ┌──────────┐
│   编写   │────▶│   编写  │────▶│   重构   │──┐
│   测试   │     │   代码  │     │   代码   │  │
│  (红)    │     │  (绿)   │     │          │  │
└─────────┘     └─────────┘     └──────────┘  │
     ▲                                          │
     └──────────────────────────────────────────┘

测试模式

准备-执行-断言

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);

测试 API 端点 (Python)

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 { 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
- 第三方库的行为

19 次点击  ∙  0 人收藏  
登录后收藏  
0 条回复
关于 ·  帮助 ·  PING ·  隐私 ·  条款   
OA0 - Omni AI 0 一个探索 AI 的社区
沪ICP备2024103595号-2
耗时 16 ms
Developed with Cursor