testing-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Test layering policy

测试分层策略

Unit tests

Unit tests(单元测试)

Purpose: verify individual functions and invariants in isolation.
  • Data-driven: parameterized tables covering happy path, boundary, error, and edge cases.
  • Property-based: fuzz invariants that must hold across all inputs (e.g., idempotency, sort stability, roundtrip serialization).
  • Derive cases from the module's public API surface: input types/constraints, output shape, error modes, invariants.
目的:在隔离环境中验证单个函数及其不变量。
  • Data-driven:使用参数化表覆盖 happy path、boundary、error 和 edge cases。
  • Property-based:对所有输入下都必须成立的不变量进行 fuzz 测试(例如,幂等性、排序稳定性、往返序列化)。
  • 根据模块的公开 API surface 推导测试用例:输入类型/约束、输出结构、错误模式和不变量。

Integration / contract tests

Integration / contract tests(集成/契约测试)

Purpose: verify interactions between components and external services.
  • API envelope: request/response shape, status codes, content types, pagination.
  • Error contract: error codes, error shapes, rate limiting, retries.
  • Auth and scoping: token validation, role-based access, tenant isolation.
  • Eventual consistency: verify convergence within bounded time; poll rather than sleep.
  • Reuse auth state across tests where possible; avoid redundant login flows.
目的:验证组件与外部服务之间的交互。
  • API envelope:请求/响应结构、状态码、content types 和分页。
  • Error contract:错误码、错误结构、rate limiting 和 retries。
  • Auth and scoping:token validation、基于角色的访问控制和 tenant isolation。
  • Eventual consistency:验证数据在有限时间内达到一致;使用轮询而非 sleep。
  • 尽可能在测试之间复用 auth state;避免重复的登录流程。

E2E tests

E2E tests

Purpose: verify real user workflows through the full stack.
  • No mocks; exercise real services, databases, and APIs.
  • Happy-path workflows only; save edge cases for lower layers.
  • State-tolerant: never assume a clean slate; tolerate and work with prior state.
  • Idempotent: safe to run repeatedly without cleanup between runs.
  • Flow-oriented: validate real data paths end-to-end rather than isolated assertions.
目的:通过完整技术栈验证真实用户工作流。
  • 不使用 mocks;调用真实的 services、databases 和 APIs。
  • 仅覆盖 happy-path 工作流;将 edge cases 留给较低层级处理。
  • State-tolerant:绝不假设环境处于全新状态;应容忍并适应已有状态。
  • Idempotent:可安全重复运行,运行时之间无需清理。
  • Flow-oriented:端到端验证真实数据路径,而不是仅执行孤立的断言。

Hard rules

硬性规则

  • Never invent signatures, source locations, or line numbers. Only reference what you have read from the codebase.
  • No fabricated fixtures. Derive test data from actual schemas, types, or seed data in the repo.
  • No test-only hacks in product code. No
    if (process.env.TEST)
    branches, no test-specific exports, no test backdoors.
  • E2E must not rely on clean slate. Tests must tolerate pre-existing data, prior test runs, and shared environments.
  • **绝不臆造签名、源码位置或行号。**只能引用已从代码库读取的内容。
  • **不得编造 fixtures。**测试数据必须根据 repo 中真实的 schemas、types 或 seed data 推导。
  • **产品代码中不得使用仅供测试的 hacks。**不得出现
    if (process.env.TEST)
    分支、测试专用导出或测试后门。
  • **E2E 不得依赖全新状态(clean slate)。**测试必须能够容忍预先存在的数据、之前的测试运行记录和共享环境。

Execution guidance

执行指导

Preflight checks (before e2e)

Preflight checks(执行前检查,e2e 之前)

  1. Verify the target environment is reachable (health endpoint, ping).
  2. Confirm required services are running (database, API, auth provider).
  3. Validate test user / credentials exist and are functional.
  4. Check for leftover state that could cause false failures; log it, do not fail on it.
  1. 验证目标环境是否可达(health endpoint、ping)。
  2. 确认所需 services 正在运行(database、API、auth provider)。
  3. 验证测试用户/凭据是否存在且功能正常。
  4. 检查可能导致误报的残留状态;记录这些状态,但不要因此判定测试失败。

Deterministic fixtures

确定性 fixtures

  • Use seeded randomness for generated data (seeded faker, deterministic UUIDs).
  • Fixtures should be self-contained; avoid cross-test fixture dependencies.
  • Prefer factory functions over shared mutable fixture objects.
  • 对生成的数据使用 seeded randomness(seeded faker、确定性 UUID)。
  • Fixtures 应自包含;避免跨测试的 fixture 依赖。
  • 优先使用 factory functions,而不是共享的可变 fixture objects。

Async handling

异步处理

  • Poll with bounded timeout and backoff; never use fixed
    sleep
    /
    waitForTimeout
    .
  • Set explicit timeout per operation; fail fast with a descriptive message on timeout.
  • Bound retry attempts (e.g., max 3 retries with exponential backoff).
  • Use framework-native waiting (Playwright
    expect
    , async assertions) over manual loops.
  • 使用轮询,并设置有界 timeout 和 backoff;绝不使用固定的
    sleep
    /
    waitForTimeout
    。
  • 为每个操作显式设置 timeout;超时时立即失败,并提供描述性消息。
  • 限制 retry 次数(例如,最多重试 3 次并采用指数退避)。
  • 优先使用框架原生等待机制(Playwright
    expect
    、async assertions),而不是手动循环。

Flake handling

Flake 处理

  • Single infrastructure retry per test run; if it fails twice, it is not flake.
  • On retry failure, collect diagnostics: screenshots, network logs, service health, timestamps.
  • Classify the failure (flaky / outdated / bug) before attempting a fix.
  • Never add arbitrary delays or retry loops as a flake "fix."
  • 每次 test run 仅允许一次基础设施重试;如果失败两次,则不再视为 flake。
  • 重试后仍失败时,收集诊断信息:截图、网络日志、service health 和时间戳。
  • 尝试修复前,先对失败进行分类(flaky / outdated / bug)。
  • 绝不能将任意延迟或 retry loops 当作 flake 的“修复”。

API surface discovery

API surface discovery

Before generating test cases:
  • Read the module source to enumerate exports/public functions.
  • Confirm scope from the user request and inspected code context; if ambiguous, state assumptions and proceed conservatively.
  • For each function: input types/constraints, output shape, error modes, invariants.
  • Probe for state dependencies and ordering constraints between functions.
生成测试用例前:
  • 阅读模块源码,枚举 exports/public functions。
  • 根据用户请求和已检查的代码上下文确认范围;如果存在歧义,说明假设并谨慎推进。
  • 针对每个函数确认:输入类型/约束、输出结构、错误模式和不变量。
  • 探查 functions 之间的 state dependencies 和 ordering constraints。

Output format

输出格式

Use markdown. Produce three sections:
Test Strategy -- one bullet per layer (unit/integration/e2e) naming the functions/flows and their coverage type.
Test Matrix -- table per function: columns
ID | Category | Name | Input | Expected
. Case ID scheme:
{CATEGORY}-{NN}
(HP, BV, ERR, EDGE). Append-only; never renumber.
Implementation Plan -- ordered steps: fixtures, unit tests, integration tests, e2e flows, run command.
使用 Markdown。生成以下三个部分:
Test Strategy——每个层级(unit/integration/e2e)一个条目,注明所涉及的 functions/flows 及其 coverage type。
Test Matrix——每个 function 一张表,列为
ID | Category | Name | Input | Expected
。Case ID 格式为
{CATEGORY}-{NN}
(HP、BV、ERR、EDGE)。仅追加用例;绝不重新编号。
Implementation Plan——按顺序列出以下步骤:fixtures、unit tests、integration tests、e2e flows 和 run command。

CI guidance

CI 指导

Fast PR smoke lane

快速 PR smoke lane

  • Unit tests + linting + type-check on every PR.
  • Subset of integration tests covering critical contracts.
  • Target: under 5 minutes.
  • 每个 PR 都运行 unit tests + linting + type-check。
  • 运行覆盖关键 contracts 的 integration tests 子集。
  • 目标:5 分钟以内。

Nightly full lane

Nightly full lane

Full unit + integration + e2e suite with higher property-based iteration counts. Flag tests that pass on retry but failed initially.
运行完整的 unit + integration + e2e suite,并使用更高的 property-based iteration counts。标记首次失败但重试后通过的测试。

Workflow

工作流

  1. Spec or code defines the module behavior (types, constraints, API surface).
  2. Agent (with this skill) produces test strategy, matrix, and implementation plan.
  3. test-writer agent translates the plan to runnable code in the target language's idiom.
  4. Developer implements to pass the tests.
  5. If implementation reveals missing cases, propose them first; append to spec only when explicitly requested.
  1. Spec 或代码定义模块行为(types、constraints、API surface)。
  2. Agent(使用此 skill)生成测试策略、测试矩阵和实施计划。
  3. test-writer
    Agent 将计划转换为符合目标语言惯用风格的可运行代码。
  4. Developer 实现代码以通过测试。
  5. 如果实现过程中发现缺失的用例,应先提出这些用例;仅在明确要求时才将其追加到 spec。