testing-integration
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseIntegration & Contract Testing
集成与契约测试
Focused patterns for testing API boundaries, cross-service contracts, component integration, database layers, property-based verification, and schema validation.
本文聚焦于API边界测试、跨服务契约验证、组件集成测试、数据库层测试、基于属性的验证以及Schema验证相关模式。
Quick Reference
快速参考
| Area | Rule / Reference | Impact |
|---|---|---|
| Stateful API testing (emulate) | | HIGH |
| API endpoint tests | | HIGH |
| React component integration | | HIGH |
| Database layer testing | | HIGH |
| Zod schema validation | | HIGH |
| Pact contract testing | | MEDIUM |
| Stateful testing (Hypothesis) | | MEDIUM |
| Evidence & property-based | | MEDIUM |
| 领域 | 规则/参考文档 | 影响等级 |
|---|---|---|
| 有状态API测试(使用emulate) | | 高 |
| API端点测试 | | 高 |
| React组件集成测试 | | 高 |
| 数据库层测试 | | 高 |
| Zod schema验证 | | 高 |
| Pact契约测试 | | 中 |
| 有状态测试(Hypothesis) | | 中 |
| 基于证据与属性的测试 | | 中 |
References
参考文档
| Topic | File |
|---|---|
| Consumer-side Pact tests | |
| Pact Broker CI/CD | |
| Provider verification setup | |
| Hypothesis strategies guide | |
| 主题 | 文件 |
|---|---|
| 消费者端Pact测试 | |
| Pact Broker CI/CD集成 | |
| 提供者验证配置 | |
| Hypothesis策略指南 | |
Checklists
检查清单
| Checklist | File |
|---|---|
| Contract testing readiness | |
| Property-based testing | |
| 检查清单 | 文件 |
|---|---|
| 契约测试就绪检查 | |
| 基于属性的测试检查 | |
Scripts & Templates
脚本与模板
| Script | File |
|---|---|
| Create integration test | |
| Test plan template | |
| 脚本 | 文件 |
|---|---|
| 创建集成测试脚本 | |
| 测试计划模板 | |
Examples
示例
| Example | File |
|---|---|
| Full testing strategy | |
| 示例 | 文件 |
|---|---|
| 完整测试策略示例 | |
Stateful API Testing (emulate — FIRST CHOICE)
有状态API测试(emulate — 首选方案)
For GitHub, Vercel, and Google API integration tests, emulate is the first choice. It provides full state machines that model real API behavior — not static mocks.
| Tool | Best For |
|---|---|
| emulate | Stateful API tests (GitHub/Vercel/Google) — FIRST CHOICE |
| Pact | Cross-team contract verification |
| MSW | Frontend HTTP mocking (simple request/response) |
| Nock | Node.js unit-level HTTP interception |
See for the full decision matrix, seed-start-test-assert pattern, and incorrect/correct examples.
rules/emulate-stateful-testing.md针对GitHub、Vercel和Google API的集成测试,emulate是首选工具。它提供完整的状态机来模拟真实API行为,而非静态Mock。
| 工具 | 适用场景 |
|---|---|
| emulate | 有状态API测试(GitHub/Vercel/Google)——首选方案 |
| Pact | 跨团队契约验证 |
| MSW | 前端HTTP Mock(简单请求/响应场景) |
| Nock | Node.js单元级HTTP拦截 |
详细决策矩阵、seed-start-test-assert模式以及错误/正确示例,请参考。
rules/emulate-stateful-testing.mdQuick Start: API Integration Test
快速开始:API集成测试
TypeScript (Supertest)
TypeScript(Supertest)
typescript
import request from 'supertest';
import { app } from '../app';
describe('POST /api/users', () => {
test('creates user and returns 201', async () => {
const response = await request(app)
.post('/api/users')
.send({ email: 'test@example.com', name: 'Test' });
expect(response.status).toBe(201);
expect(response.body.id).toBeDefined();
expect(response.body.email).toBe('test@example.com');
});
test('returns 400 for invalid email', async () => {
const response = await request(app)
.post('/api/users')
.send({ email: 'invalid', name: 'Test' });
expect(response.status).toBe(400);
expect(response.body.error).toContain('email');
});
});typescript
import request from 'supertest';
import { app } from '../app';
describe('POST /api/users', () => {
test('creates user and returns 201', async () => {
const response = await request(app)
.post('/api/users')
.send({ email: 'test@example.com', name: 'Test' });
expect(response.status).toBe(201);
expect(response.body.id).toBeDefined();
expect(response.body.email).toBe('test@example.com');
});
test('returns 400 for invalid email', async () => {
const response = await request(app)
.post('/api/users')
.send({ email: 'invalid', name: 'Test' });
expect(response.status).toBe(400);
expect(response.body.error).toContain('email');
});
});Python (FastAPI + httpx)
Python(FastAPI + httpx)
python
import pytest
from httpx import AsyncClient
from app.main import app
@pytest.fixture
async def client():
async with AsyncClient(app=app, base_url="http://test") as ac:
yield ac
@pytest.mark.asyncio
async def test_create_user(client: AsyncClient):
response = await client.post(
"/api/users",
json={"email": "test@example.com", "name": "Test"}
)
assert response.status_code == 201
assert response.json()["email"] == "test@example.com"python
import pytest
from httpx import AsyncClient
from app.main import app
@pytest.fixture
async def client():
async with AsyncClient(app=app, base_url="http://test") as ac:
yield ac
@pytest.mark.asyncio
async def test_create_user(client: AsyncClient):
response = await client.post(
"/api/users",
json={"email": "test@example.com", "name": "Test"}
)
assert response.status_code == 201
assert response.json()["email"] == "test@example.com"Coverage Targets
覆盖率目标
| Area | Target |
|---|---|
| API endpoints | 70%+ |
| Service layer | 80%+ |
| Component interactions | 70%+ |
| Contract tests | All consumer-used endpoints |
| Property tests | All encode/decode, idempotent functions |
| 领域 | 目标覆盖率 |
|---|---|
| API端点 | 70%+ |
| 服务层 | 80%+ |
| 组件交互 | 70%+ |
| 契约测试 | 覆盖所有消费者使用的端点 |
| 基于属性的测试 | 覆盖所有编解码、幂等函数 |
Key Principles
核心原则
- Test at boundaries -- API inputs, database queries, service calls, external integrations
- Fresh state per test -- In-memory databases, transaction rollback, no shared mutable state
- Use matchers in contracts -- ,
Like(),EachLike()instead of exact valuesTerm() - Property-based for invariants -- Roundtrip, idempotence, commutativity properties
- Validate schemas at edges -- Zod at every API boundary
.safeParse() - Evidence-backed completion -- Exit code 0, coverage reports, timestamps
- 在边界处测试——覆盖API输入、数据库查询、服务调用、外部集成场景
- 每个测试使用独立新鲜状态——使用内存数据库、事务回滚,避免共享可变状态
- 在契约中使用匹配器——使用、
Like()、EachLike()而非精确值Term() - 基于属性测试不变量——覆盖往返一致性、幂等性、交换性等属性
- 在边缘处验证Schema——在每个API边界使用Zod 进行校验
.safeParse() - 基于证据确认完成——通过退出码0、覆盖率报告、时间戳证明测试完成
When to Use This Skill
适用场景
- Writing API endpoint tests (Supertest, httpx)
- Setting up React component integration tests with providers
- Creating database integration tests with isolation
- Implementing Pact consumer/provider contract tests
- Adding property-based tests with Hypothesis
- Validating Zod schemas at API boundaries
- Planning a testing strategy for a new feature or service
- 编写API端点测试(Supertest、httpx)
- 配置带Providers的React组件集成测试
- 创建具备隔离性的数据库集成测试
- 实现Pact消费者/提供者契约测试
- 基于Hypothesis添加基于属性的测试
- 在API边界处验证Zod schemas
- 为新功能或服务规划测试策略
Related Skills
相关技能
- — Unit testing patterns, fixtures, mocking
ork:testing-unit - — End-to-end Playwright tests
ork:testing-e2e - — Seed configuration authoring for emulate providers
ork:emulate-seed - — Database schema and migration patterns
ork:database-patterns - — API design patterns for endpoint testing
ork:api-design
- — 单元测试模式、测试夹具、Mock技术
ork:testing-unit - — 基于Playwright的端到端测试
ork:testing-e2e - — 为emulate提供者编写种子配置
ork:emulate-seed - — 数据库Schema与迁移模式
ork:database-patterns - — 适用于端点测试的API设计模式
ork:api-design