testing-e2e
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseE2E Testing Patterns
端到端测试模式
End-to-end testing with Playwright 1.58+, visual regression, accessibility, and AI agent workflows.
基于Playwright 1.58+的端到端测试,涵盖视觉回归、可访问性测试及AI Agent工作流。
Quick Reference
快速参考
| Category | Rules | Impact | When to Use |
|---|---|---|---|
| emulate Backends | | HIGH | FIRST CHOICE — deterministic API backends for E2E |
| Playwright Core | | HIGH | Semantic locators, auto-wait, flaky detection |
| Page Objects | | HIGH | Encapsulate page interactions, visual regression |
| AI Agents | | HIGH | Planner/Generator/Healer, init-agents |
| A11y Playwright | | MEDIUM | Full-page axe-core scanning with WCAG 2.2 AA |
| A11y CI/CD | | MEDIUM | CI gates, jest-axe unit tests, PR blocking |
| End-to-End Types | | HIGH | tRPC, Prisma, Pydantic type safety |
Total: 7 rules, 4 references, 3 checklists, 3 examples, 1 script
| 类别 | 规则文档 | 影响等级 | 适用场景 |
|---|---|---|---|
| 模拟后端 | | 高 | 首选方案——为E2E测试提供确定性的API后端 |
| Playwright核心实践 | | 高 | 语义化定位器、自动等待、不稳定测试检测 |
| 页面对象模式 | | 高 | 封装页面交互、视觉回归测试 |
| AI Agent测试 | | 高 | 规划器/生成器/修复器工作流、init-agents初始化 |
| 可访问性测试(Playwright) | | 中 | 基于WCAG 2.2 AA标准的全页面axe-core扫描 |
| 可访问性测试(CI/CD) | | 中 | CI门禁、jest-axe单元测试、PR阻断 |
| 端到端类型安全 | | 高 | tRPC、Prisma、Pydantic类型安全 |
总计:7项规则、4份参考文档、3份检查清单、3个示例、1个脚本工具
emulate Backends
模拟后端
For E2E tests that interact with external APIs (GitHub, Vercel, Google), use emulate as the backend instead of hitting real APIs. This eliminates flakiness from rate limits, network issues, and non-deterministic data.
| Approach | Result |
|---|---|
| emulate backends (FIRST CHOICE) | Deterministic, fast, CI-friendly |
| Real APIs | Flaky, rate-limited, slow |
| MSW/Nock intercepts | No state machines, manual response management |
Key features: seed config for reproducible data, per-worker port isolation for parallel Playwright, full state machine transitions.
See for patterns, CI configuration, and per-worker isolation fixtures.
rules/emulate-e2e.md对于需要与外部API(如GitHub、Vercel、Google)交互的E2E测试,请使用模拟后端而非调用真实API。这可以消除由速率限制、网络问题和非确定性数据导致的测试不稳定问题。
| 实现方式 | 效果 |
|---|---|
| 模拟后端(首选方案) | 确定性强、速度快、适配CI环境 |
| 真实API | 不稳定、受速率限制、速度慢 |
| MSW/Nock拦截 | 无状态机、需手动管理响应 |
核心特性:可生成用于可复现数据的种子配置、为并行运行的Playwright提供每个工作进程的端口隔离、完整的状态机转换逻辑。
有关模式、CI配置及每个工作进程的隔离夹具,请查看。
rules/emulate-e2e.mdPlaywright Quick Start
Playwright快速开始
typescript
import { test, expect } from '@playwright/test';
test('user can complete checkout', async ({ page }) => {
await page.goto('/products');
await page.getByRole('button', { name: 'Add to cart' }).click();
await page.getByRole('link', { name: 'Checkout' }).click();
await page.getByLabel('Email').fill('test@example.com');
await page.getByRole('button', { name: 'Submit' }).click();
await expect(page.getByRole('heading', { name: 'Order confirmed' })).toBeVisible();
});Locator Priority: > > >
getByRole()getByLabel()getByPlaceholder()getByTestId()typescript
import { test, expect } from '@playwright/test';
test('user can complete checkout', async ({ page }) => {
await page.goto('/products');
await page.getByRole('button', { name: 'Add to cart' }).click();
await page.getByRole('link', { name: 'Checkout' }).click();
await page.getByLabel('Email').fill('test@example.com');
await page.getByRole('button', { name: 'Submit' }).click();
await expect(page.getByRole('heading', { name: 'Order confirmed' })).toBeVisible();
});定位器优先级: > > >
getByRole()getByLabel()getByPlaceholder()getByTestId()Playwright Core
Playwright核心实践
Semantic locator patterns and best practices for resilient tests.
| Rule | File | Key Pattern |
|---|---|---|
| Playwright E2E | | Semantic locators, auto-wait, new 1.58+ features |
Anti-patterns (FORBIDDEN):
- Hardcoded waits:
await page.waitForTimeout(2000) - CSS selectors for interactions:
await page.click('.submit-btn') - XPath locators
用于构建稳定测试的语义化定位器模式及最佳实践。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| Playwright E2E测试 | | 语义化定位器、自动等待、1.58+版本新特性 |
反模式(禁止使用):
- 硬编码等待:
await page.waitForTimeout(2000) - 使用CSS选择器进行交互:
await page.click('.submit-btn') - XPath定位器
Page Objects
页面对象模式
Encapsulate page interactions into reusable classes.
| Rule | File | Key Pattern |
|---|---|---|
| Page Object Model | | Locators in constructor, action methods, assertion methods |
typescript
const checkout = new CheckoutPage(page);
await checkout.fillEmail('test@example.com');
await checkout.submit();
await checkout.expectConfirmation();将页面交互逻辑封装为可复用的类。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| 页面对象模型 | | 在构造函数中定义定位器、动作方法、断言方法 |
typescript
const checkout = new CheckoutPage(page);
await checkout.fillEmail('test@example.com');
await checkout.submit();
await checkout.expectConfirmation();AI Agents
AI Agent测试
Playwright 1.58+ AI agent framework for test planning, generation, and self-healing. Includes a token-efficient CLI mode designed for coding agents — minimal output, structured responses, reduced context overhead.
| Rule | File | Key Pattern |
|---|---|---|
| AI Agents | | Planner, Generator, Healer workflow |
bash
npx playwright init-agents --loop=claude # For Claude CodeToken-efficient CLI mode (1.58+): Playwright ships a SKILL-focused CLI mode that produces compact, agent-friendly output — use this when running Playwright from AI agents to minimize token consumption.
Workflow: Planner (explores app, creates specs) -> Generator (reads spec, tests live app) -> Healer (fixes failures, updates selectors).
Playwright 1.58+提供的AI Agent框架,用于测试规划、测试用例生成及测试自修复。包含专为编码Agent设计的Token高效CLI模式——输出简洁、响应结构化,降低上下文开销。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| AI Agent测试 | | 规划器、生成器、修复器工作流 |
bash
npx playwright init-agents --loop=claude # 适用于Claude CodeToken高效CLI模式(1.58+版本):Playwright提供了以SKILL为核心的CLI模式,可生成紧凑、适配Agent的输出——当通过AI Agent运行Playwright时,请使用此模式以减少Token消耗。
工作流:规划器(探索应用、创建测试规范)→ 生成器(读取规范、测试线上应用)→ 修复器(修复测试失败、更新定位器)。
Accessibility (Playwright)
可访问性测试(Playwright)
Full-page accessibility validation with axe-core in E2E tests.
| Rule | File | Key Pattern |
|---|---|---|
| Playwright + axe | | WCAG 2.2 AA, interactive state testing |
typescript
import AxeBuilder from '@axe-core/playwright';
test('page meets WCAG 2.2 AA', async ({ page }) => {
await page.goto('/');
const results = await new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa', 'wcag22aa'])
.analyze();
expect(results.violations).toEqual([]);
});在E2E测试中借助axe-core进行全页面可访问性验证。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| Playwright + axe-core | | WCAG 2.2 AA标准、交互状态测试 |
typescript
import AxeBuilder from '@axe-core/playwright';
test('page meets WCAG 2.2 AA', async ({ page }) => {
await page.goto('/');
const results = await new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa', 'wcag22aa'])
.analyze();
expect(results.violations).toEqual([]);
});Accessibility (CI/CD)
可访问性测试(CI/CD)
CI pipeline integration and jest-axe unit-level component testing.
| Rule | File | Key Pattern |
|---|---|---|
| CI Gates + jest-axe | | PR blocking, component state testing |
CI流水线集成及基于jest-axe的组件级单元测试。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| CI门禁 + jest-axe | | PR阻断、组件状态测试 |
End-to-End Types
端到端类型安全
Type safety across API layers to eliminate runtime type errors.
| Rule | File | Key Pattern |
|---|---|---|
| Type Safety | | tRPC, Zod, Pydantic, schema rejection tests |
跨API层的类型安全,消除运行时类型错误。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| 类型安全 | | tRPC、Zod、Pydantic、Schema拒绝测试 |
Visual Regression
视觉回归测试
Native Playwright screenshot comparison without external services.
typescript
await expect(page).toHaveScreenshot('checkout-page.png', {
maxDiffPixels: 100,
mask: [page.locator('.dynamic-content')],
});See for full configuration, CI/CD workflows, cross-platform handling, and Percy migration guide.
references/visual-regression.md无需外部服务,使用Playwright原生截图对比功能。
typescript
await expect(page).toHaveScreenshot('checkout-page.png', {
maxDiffPixels: 100,
mask: [page.locator('.dynamic-content')],
});有关完整配置、CI/CD工作流、跨平台处理及Percy迁移指南,请查看。
references/visual-regression.mdKey Decisions
核心决策建议
| Decision | Recommendation |
|---|---|
| E2E framework | Playwright 1.58+ with semantic locators |
| Locator strategy | |
| Browser | Chromium (Chrome for Testing in 1.58+) |
| Page pattern | Page Object Model for complex pages |
| Visual regression | Playwright native |
| A11y testing | axe-core (E2E) + jest-axe (unit) |
| CI retries | 2-3 in CI, 0 locally |
| Flaky detection | |
| AI agents | Planner/Generator/Healer via |
| Type safety | tRPC for end-to-end, Zod for runtime validation |
| 决策项 | 推荐方案 |
|---|---|
| E2E测试框架 | Playwright 1.58+ 搭配语义化定位器 |
| 定位器策略 | |
| 浏览器 | Chromium(1.58+版本中为Chrome for Testing) |
| 页面模式 | 复杂页面使用页面对象模型 |
| 视觉回归测试 | Playwright原生 |
| 可访问性测试 | axe-core(E2E) + jest-axe(单元) |
| CI环境重试次数 | CI环境2-3次,本地环境0次 |
| 不稳定测试检测 | CI中启用 |
| AI Agent测试 | 通过 |
| 类型安全 | 端到端使用tRPC,运行时验证使用Zod |
References
参考资源
| Resource | Description |
|---|---|
| Playwright 1.58+ API: locators, assertions, AI agents, auth, flaky detection |
| Installation, MCP server, seed tests, agent initialization |
| Screenshot config, CI/CD workflows, cross-platform, Percy migration |
| jest-axe setup, Playwright axe-core, CI pipelines, manual checklists |
| 资源 | 说明 |
|---|---|
| Playwright 1.58+ API:定位器、断言、AI Agent、认证、不稳定测试检测 |
| 安装指南、MCP服务器、种子测试、Agent初始化 |
| 截图配置、CI/CD工作流、跨平台处理、Percy迁移 |
| jest-axe配置、Playwright + axe-core、CI流水线、手动检查清单 |
Checklists
检查清单
| Checklist | Description |
|---|---|
| Locator strategy, page objects, CI/CD, visual regression |
| Comprehensive: planning, implementation, SSE, responsive, maintenance |
| Automated + manual: keyboard, screen reader, color contrast, WCAG |
| 检查清单 | 说明 |
|---|---|
| 定位器策略、页面对象、CI/CD、视觉回归测试 |
| 全面覆盖:测试规划、实现、SSE、响应式测试、维护 |
| 自动化+手动测试:键盘操作、屏幕阅读器、色彩对比度、WCAG标准 |
Examples
示例
| Example | Description |
|---|---|
| User flows, page objects, auth fixtures, API mocking, multi-tab, file upload |
| jest-axe components, Playwright axe E2E, custom rules, CI pipeline |
| OrchestKit analysis flow: page objects, SSE progress, error handling |
| 示例文档 | 说明 |
|---|---|
| 用户流、页面对象、认证夹具、API模拟、多标签页、文件上传 |
| jest-axe组件测试、Playwright + axe-core E2E测试、自定义规则、CI流水线 |
| OrchestKit分析流:页面对象、SSE进度、错误处理 |
Scripts
脚本工具
| Script | Description |
|---|---|
| Generate Playwright page object with auto-detected patterns |
| 脚本 | 说明 |
|---|---|
| 通过自动检测模式生成Playwright页面对象 |
Related Skills
相关技能
- - Unit testing patterns with mocking, fixtures, and data factories
testing-unit - - AAA and naming enforcement
test-standards-enforcer - - Test execution orchestration
run-tests - - Seed configuration authoring for emulate providers
emulate-seed - (upstream) - Stable
portlessfor local E2E tests (baseURLinstead of port guessing)myapp.localhost:1355
- - 包含模拟、夹具和数据工厂的单元测试模式
testing-unit - - AAA测试规范及命名规则检查
test-standards-enforcer - - 测试执行编排
run-tests - - 为模拟提供者编写种子配置
emulate-seed - (上游依赖)- 为本地E2E测试提供稳定的
portless(使用baseURL而非端口猜测)myapp.localhost:1355