testing-integration

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Integration & 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

快速参考

AreaRule / ReferenceImpact
Stateful API testing (emulate)
rules/emulate-stateful-testing.md
HIGH
API endpoint tests
rules/integration-api.md
HIGH
React component integration
rules/integration-component.md
HIGH
Database layer testing
rules/integration-database.md
HIGH
Zod schema validation
rules/validation-zod-schema.md
HIGH
Pact contract testing
rules/verification-contract.md
MEDIUM
Stateful testing (Hypothesis)
rules/verification-stateful.md
MEDIUM
Evidence & property-based
rules/verification-techniques.md
MEDIUM
领域规则/参考文档影响等级
有状态API测试(使用emulate)
rules/emulate-stateful-testing.md
API端点测试
rules/integration-api.md
React组件集成测试
rules/integration-component.md
数据库层测试
rules/integration-database.md
Zod schema验证
rules/validation-zod-schema.md
Pact契约测试
rules/verification-contract.md
有状态测试(Hypothesis)
rules/verification-stateful.md
基于证据与属性的测试
rules/verification-techniques.md

References

参考文档

TopicFile
Consumer-side Pact tests
references/consumer-tests.md
Pact Broker CI/CD
references/pact-broker.md
Provider verification setup
references/provider-verification.md
Hypothesis strategies guide
references/strategies-guide.md
主题文件
消费者端Pact测试
references/consumer-tests.md
Pact Broker CI/CD集成
references/pact-broker.md
提供者验证配置
references/provider-verification.md
Hypothesis策略指南
references/strategies-guide.md

Checklists

检查清单

ChecklistFile
Contract testing readiness
checklists/contract-testing-checklist.md
Property-based testing
checklists/property-testing-checklist.md
检查清单文件
契约测试就绪检查
checklists/contract-testing-checklist.md
基于属性的测试检查
checklists/property-testing-checklist.md

Scripts & Templates

脚本与模板

ScriptFile
Create integration test
scripts/create-integration-test.md
Test plan template
scripts/test-plan-template.md
脚本文件
创建集成测试脚本
scripts/create-integration-test.md
测试计划模板
scripts/test-plan-template.md

Examples

示例

ExampleFile
Full testing strategy
examples/orchestkit-test-strategy.md

示例文件
完整测试策略示例
examples/orchestkit-test-strategy.md

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.
ToolBest For
emulateStateful API tests (GitHub/Vercel/Google) — FIRST CHOICE
PactCross-team contract verification
MSWFrontend HTTP mocking (simple request/response)
NockNode.js unit-level HTTP interception
See
rules/emulate-stateful-testing.md
for the full decision matrix, seed-start-test-assert pattern, and incorrect/correct examples.

针对GitHub、Vercel和Google API的集成测试,emulate是首选工具。它提供完整的状态机来模拟真实API行为,而非静态Mock。
工具适用场景
emulate有状态API测试(GitHub/Vercel/Google)——首选方案
Pact跨团队契约验证
MSW前端HTTP Mock(简单请求/响应场景)
NockNode.js单元级HTTP拦截
详细决策矩阵、seed-start-test-assert模式以及错误/正确示例,请参考
rules/emulate-stateful-testing.md

Quick 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

覆盖率目标

AreaTarget
API endpoints70%+
Service layer80%+
Component interactions70%+
Contract testsAll consumer-used endpoints
Property testsAll encode/decode, idempotent functions

领域目标覆盖率
API端点70%+
服务层80%+
组件交互70%+
契约测试覆盖所有消费者使用的端点
基于属性的测试覆盖所有编解码、幂等函数

Key Principles

核心原则

  1. Test at boundaries -- API inputs, database queries, service calls, external integrations
  2. Fresh state per test -- In-memory databases, transaction rollback, no shared mutable state
  3. Use matchers in contracts --
    Like()
    ,
    EachLike()
    ,
    Term()
    instead of exact values
  4. Property-based for invariants -- Roundtrip, idempotence, commutativity properties
  5. Validate schemas at edges -- Zod
    .safeParse()
    at every API boundary
  6. Evidence-backed completion -- Exit code 0, coverage reports, timestamps

  1. 在边界处测试——覆盖API输入、数据库查询、服务调用、外部集成场景
  2. 每个测试使用独立新鲜状态——使用内存数据库、事务回滚,避免共享可变状态
  3. 在契约中使用匹配器——使用
    Like()
    EachLike()
    Term()
    而非精确值
  4. 基于属性测试不变量——覆盖往返一致性、幂等性、交换性等属性
  5. 在边缘处验证Schema——在每个API边界使用Zod
    .safeParse()
    进行校验
  6. 基于证据确认完成——通过退出码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

相关技能

  • ork:testing-unit
    — Unit testing patterns, fixtures, mocking
  • ork:testing-e2e
    — End-to-end Playwright tests
  • ork:emulate-seed
    — Seed configuration authoring for emulate providers
  • ork:database-patterns
    — Database schema and migration patterns
  • ork:api-design
    — API design patterns for endpoint testing
  • ork:testing-unit
    — 单元测试模式、测试夹具、Mock技术
  • ork:testing-e2e
    — 基于Playwright的端到端测试
  • ork:emulate-seed
    — 为emulate提供者编写种子配置
  • ork:database-patterns
    — 数据库Schema与迁移模式
  • ork:api-design
    — 适用于端点测试的API设计模式