📦 Test Runner — 跨语言和框架测试运行器
v1.0.1写作和运行跨多种编程语言和框架的测试,支持 JavaScript、Python、Swift 等,涵盖单元测试、集成测试和端到端测试。
运行时依赖
版本
安装命令
点击复制技能文档
核心工作流程
- 在更改任何内容之前,先检测语言、包管理器和现有的测试框架。
- 优先使用项目当前的测试堆栈,而不是引入新的测试框架。
- 先运行最小的相关测试范围,在理解失败原因后再扩大覆盖范围。
- 修复 bug 时,从失败的测试开始,进行最小的代码更改使其通过,然后重构。
- 更改后,重新运行窄范围测试,如果本地工作流程支持,再运行更广泛的测试套件。
框架选择
当已配置了现有框架时使用它。如果项目没有测试堆栈,优先选择:
| 语言 | 单元测试 | 集成测试 | 端到端测试 |
|---|---|---|---|
| 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
红-绿-重构
- 红:为你需要的行为编写一个失败的测试。
- 绿:进行最小的更改使其通过。
- 重构:在不改变行为的情况下清理代码。
测试模式
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 进行模拟
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()
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
- 第三方库的行为