E2E 与 Playwright
浏览器自动化、关键路径冒烟。
E2E 与 Playwright
这一课你将能做到
- 配置 Playwright 双服务环境(Next.js 前端 + Spring Boot 后端),写出「打开页 → 可见 → 跳转」的关键路径冒烟
- 用
getByRole/ 自动等待 /waitForResponse替代 sleep,把 flaky 压到最低 - 列出本站 3~5 条值得 E2E 守护的路径,并说清哪些不该进 E2E
为什么要学
单元与 MockMvc 再绿,仍可能出事:前端路由配错、环境变量 NEXT_PUBLIC_API_BASE 指错、CORS 没开、真浏览器才暴露的水合错误。人话:E2E 是用真实浏览器走用户的路——少、慢、贵,但只有它能抓住「整条链断了」。
它不能替代金字塔底部。本课目标是会写稳定的冒烟,并知道 CI 策略:PR 上仍以 mvn test + npm test 为主,E2E 放主分支或发布前跑(分轨思想见 test-ci)。
CodeForge 值得 E2E 守护的命门很清楚:访客能打开首页、能看到课程列表、注册登录能走通、提交代码能看到判题状态。每多一条用例就要多付一份维护税——文案改、路由改、数据改都会红,所以清单要像产品的命门列表,不是测试同学的 KPI。
先建立图像
E2E: Browser ──► platform(Next.js :3000) ──HTTP──► backend(Spring Boot :8080)
▲ │
└── Playwright 驱动:点击、填表、断言 ←──────┘
MySQL / Redis
成本:分钟级;失败定位面横跨四层
策略:3~5 条命门;能下沉到组件测 / MockMvc 的就下沉
| 层级 | 已被谁测 | E2E 要不要重复 |
|---|---|---|
| 业务分支 | Mockito 单测 | 不重复 |
| HTTP 契约 | MockMvc | 不重复字段细节 |
| 整页用户路径 | — | E2E 主场 |
选择器优先级与 Testing Library 一致:role / label / 文本 ≫ CSS class / XPath。
跟着做
步骤 1:安装与最小配置
cd platform
npm install -D @playwright/test
npx playwright install chromium
playwright.config.ts——重点是 webServer 让脚本自动拉起前后端:
import { defineConfig } from "@playwright/test";
export default defineConfig({
testDir: "./e2e",
use: {
baseURL: "http://localhost:3000",
trace: "on-first-retry", // 失败重试时录 trace,定位神器
},
retries: process.env.CI ? 1 : 0,
webServer: [
{
command: "cd ../backend && mvn spring-boot:run",
url: "http://localhost:8080/tracks",
reuseExistingServer: true,
timeout: 120_000,
},
{
command: "npm run dev",
url: "http://localhost:3000",
reuseExistingServer: true,
timeout: 120_000,
},
],
});