E2E Testing Automation
概述
端到端(E2E)测试验证从 UI 到所有后端系统的完整用户工作流,确保整个应用栈从用户视角正确协同工作。E2E 测试通过浏览器模拟真实用户交互,处理认证、导航、表单提交并验证结果。
适用场景
- 测试关键用户旅程(注册、结账、登录)
- 验证多步骤工作流
- 跨不同浏览器和设备测试
- 针对 UI 变更的回归测试
- 验证前后端集成
- 使用真实用户交互(点击、输入、滚动)进行测试
- 部署冒烟测试
快速开始
最小可用示例:
// tests/e2e/checkout.spec.ts import { test, expect, Page } from "@playwright/test";
test.describe("E-commerce Checkout Flow", () => { let page: Page;
test.beforeEach(async ({ page: p }) => { page = p; await page.goto("/"); });
test("complete checkout flow as guest user", async () => { // 1. Browse and add product to cart await page.click("text=Shop Now"); await page.click('[data-testid="product-1"]'); await expect(page.locator("h1")).toContainText("Product Name");
await page.click('button:has-text("Add to Cart")');
await expect(page.locator(".cart-count")).toHaveText("1");
// 2. Go to cart and proceed to checkout
await page.click('[data-testid="cart-icon"]');
await expect(page.locator(".cart-item")).toHaveCount(1);
await page.click("text=Proceed to Checkout");
// ...(完整实现见参考指南)
参考指南
references/ 目录中的详细实现:
- Playwright E2E Tests
- Cypress E2E Tests
- Selenium with Python (pytest)
- Page Object Model Pattern
最佳实践
✅ 应做
- 使用 data-testid 属性以获得稳定的选择器
- 实施 Page Object Model 以提升可维护性
- 彻底测试关键用户旅程
- 在多个浏览器中运行测试(跨浏览器测试)
- 使用显式等待而非 sleep/timeout
- 每个测试后清理测试数据
- 失败时截图
- 尽可能并行执行测试
❌ 不应做
- 使用脆弱的 CSS 选择器(如 nth-child)
- 测试每一种可能的 UI 组合(聚焦关键路径)
- 在测试之间共享状态
- 使用固定延迟(sleep/timeout)
- 忽略不稳定的测试
- 用 E2E 测试做单元级测试
- 详细测试第三方 UI 组件
- 跳过移动端/响应式测试