关于 designing-tests
Designing Tests 是帮助开发者规划、编写和验证软件测试的实践指南,结合测试金字塔、框架建议、模板、覆盖率指导、测试数据与模拟策略,以及验证流程。
主要功能
- 01分步骤的测试工作流
- 02测试金字塔与测试类型
- 03按语言提供框架建议
- 04单元、集成与 E2E 模板
- 05覆盖率与测试数据指南
- 06模拟与验证策略
适用场景
- 01为功能规划测试覆盖率
- 02选择测试类型与框架
- 03验证测试结果与覆盖率
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ cloudai-x/ claude-workflow-v2 --skill designing-tests安装后在 Claude Code 中输入/designing-tests确认已加载。
详细介绍
设计测试
加载时机
- 触发条件:添加测试、规划测试策略、提高覆盖率、搭建测试基础设施
- 跳过条件:任务不涉及测试的非测试代码更改
测试实现工作流
复制此清单并跟踪进度:
Test Implementation Progress:
- [ ] Step 1: Identify what to test
- [ ] Step 2: Select appropriate test type
- [ ] Step 3: Write tests following templates
- [ ] Step 4: Run tests and verify passing
- [ ] Step 5: Check coverage meets targets
- [ ] Step 6: Fix any failing tests
测试金字塔
应用测试金字塔,实现均衡的覆盖率:
/\
/ \ E2E Tests (10%)
/----\ - Critical user journeys
/ \ - Slow but comprehensive
/--------\ Integration Tests (20%)
/ \ - Component interactions
/------------\ - API contracts
/ \ Unit Tests (70%)
/________________\ - Fast, isolated
- Business logic focus
框架选择
JavaScript/TypeScript
| 类型 | 推荐方案 | 替代方案 |
|---|---|---|
| 单元测试 | Vitest | Jest |
| 集成测试 | Vitest + MSW | Jest + SuperTest |
| 端到端测试 | Playwright | Cypress |
| 组件测试 | Testing Library | Vitest Browser Mode |
Python
| 类型 | 推荐方案 | 替代方案 |
|---|---|---|
| 单元测试 | pytest | unittest |
| 集成测试 | pytest + httpx | pytest + requests |
| 端到端测试 | Playwright | Selenium |
| API 测试 | pytest + FastAPI TestClient | - |
Go
| 类型 | 推荐方案 |
|---|---|
| 单元测试 | testing + testify |
| 集成测试 | testing + httptest |
| 端到端测试 | testing + chromedp |
测试结构模板
单元测试
describe("[Unit] ComponentName", () => {
describe("methodName", () => {
it("should [expected behavior] when [condition]", () => {
// Arrange
const input = createTestInput();
// Act
const result = methodName(input);
// Assert
expect(result).toEqual(expectedOutput);
});
it("should throw error when [invalid condition]", () => {
expect(() => methodName(invalidInput)).toThrow(ExpectedError);
});
});
});
集成测试
describe("[Integration] API /users", () => {
beforeAll(async () => {
await setupTestDatabase();
});
afterAll(async () => {
await teardownTestDatabase();
});
it("should create user and return 201", async () => {
const response = await request(app)
.post("/users")
.send({ name: "Test", email: "[email protected]" });
expect(response.status).toBe(201);
expect(response.body.id).toBeDefined();
});
});
端到端测试
import { test, expect } from "@playwright/test";
test.describe("[E2E] User Registration Flow", () => {
test("should complete registration successfully", async ({ page }) => {
await page.goto("/register");
await page.getByTestId("email").fill("[email protected]");
await page.getByTestId("password").fill("SecurePass123!");
await page.getByTestId("submit").click();
await expect(page.locator(".welcome-message")).toBeVisible();
await expect(page).toHaveURL("/dashboard");
});
});
覆盖率策略
覆盖内容
- ✅ 业务逻辑(100%)
- ✅ 边界情况和错误处理(90%+)
- ✅ API 契约(100%)
- ✅ 关键用户路径(端到端)
- ⚠️ UI 组件(快照 + 交互)
- ❌ 第三方库内部实现
- ❌ 简单的 getter/setter
覆盖率阈值
此处展示的是 Jest 配置;Vitest 对应的配置项是 vitest.config 中的 test.coverage.thresholds。
{
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": 80
},
"src/core/": {
"branches": 95,
"functions": 95
}
}
}
测试数据管理
工厂/构建器
// factories/user.js
export const userFactory = (overrides = {}) => ({
id: faker.string.uuid(),
name: faker.person.fullName(),
email: faker.internet.email(),
createdAt: new Date(),
...overrides,
});
// Usage
const admin = userFactory({ role: "admin" });
固定数据
// fixtures/users.json
{
"validUser": { "name": "Test", "email": "[email protected]" },
"invalidUser": { "name": "", "email": "invalid" }
}
Mock 策略
何时使用 Mock
- ✅ 外部 API 和服务
- ✅ 单元测试中的数据库
- ✅ 时间/日期,以确保结果确定
- ✅ 随机值
- ❌ 内部模块(通常不需要)
- ❌ 被测代码
Mock 示例
// API mocking with MSW
import { http, HttpResponse } from "msw";
export const handlers = [
http.get("/api/users", () => {
return HttpResponse.json([{ id: 1, name: "John" }]);
}),
];
// Time mocking
vi.useFakeTimers();
vi.setSystemTime(new Date("2024-01-01"));
测试验证循环
编写测试后,运行以下验证:
Test Validation:
- [ ] All tests pass: `npm test`
- [ ] Coverage meets thresholds: `npm test -- --coverage`
- [ ] No flaky tests (run multiple times)
- [ ] Tests are independent (order doesn't matter)
- [ ] Test names clearly describe behavior
如果有任何测试失败,请先修复,再继续。如果覆盖率低于目标,请为未覆盖的代码路径添加更多测试。
# Run tests
npm test
# Run with coverage
npm test -- --coverage
# Run specific test file
npm test -- path/to/test.spec.ts
# Run in watch mode during development
npm test -- --watch
评论
支持 Markdown