E2E 测试:从 Cypress 迁到 Playwright
MrSmy Lv5

E2E 测试是最贵的测试:慢、脆、维护成本高。但某些场景绕不过去——登录、支付、多步骤表单,这些必须”点一遍”才知道对不对。

我们用 Cypress 两年后迁到了 Playwright,这篇讲原因、迁移成本和踩的坑。

为什么换

Cypress 的问题是结构性的:

限制 影响
同源策略(cy.origin 之前) 跨域(SSO 登录、支付回调)很难测
单标签页 window.open 的流程无法测
运行在浏览器内(In-DOM) 无法真正模拟多个用户、无法做网络层拦截之外的代理
不支持并行(免费版要付费 dashboard) CI 上跑 20 个用例要 10 分钟
只能跑 Chromium 系(初期) Firefox/WebKit 覆盖不了

Playwright 直接对应这些:

  • 多浏览器引擎(Chromium / Firefox / WebKit)
  • 多 context(等价于多个独立用户,各自有 cookie/storage)
  • 多标签页、iframe、跨域
  • 原生并行(workers)
  • 自带 trace viewer(失败时回放)
  • 可以在 Node 层控制网络(route)

基础

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test'

export default defineConfig({
testDir: './e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 1 : 0,
workers: process.env.CI ? 4 : undefined,
reporter: [['html', { open: 'never' }], ['list']],
use: {
baseURL: 'http://localhost:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
{ name: 'mobile', use: { ...devices['iPhone 13'] } },
],
webServer: {
command: 'npm run start',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
},
})

webServer 自动起服务并等它就绪,比手工 start-server-and-test 干净。

trace: 'on-first-retry' 是性价比最高的配置——只在失败重试时录 trace,成功时不产生额外开销。

定位器:不要用 CSS 选择器

1
2
3
4
5
6
7
8
9
10
11
// ❌ 这样做前端一改 class 就全崩
await page.click('.btn-primary.mt-2')

// ❌ 用 testid 到处都是
await page.click('[data-testid="submit"]')

// ✅ 用可访问名称(推荐优先级最高)
await page.getByRole('button', { name: '提交订单' }).click()
await page.getByLabel('手机号').fill('13800138000')
await page.getByPlaceholder('请输入验证码').fill('1234')
await page.getByText('订单创建成功').isVisible()

Playwright 的 locator 优先级(官方推荐):

  1. getByRole —— 语义角色 + 可访问名称
  2. getByLabel —— 表单关联的 label
  3. getByPlaceholder
  4. getByText
  5. getByTestId —— 实在没有语义时

**用 role 定位还有一个副作用:它会逼你把 button 写成 <button> 而不是 <div onclick>**。等于免费拿到了可访问性改进。

自动等待:不要写 sleep

1
2
3
4
5
6
7
8
9
10
// ❌ 慢且不稳定
await page.waitForTimeout(2000)
await page.click('button')

// ✅ 自动等待元素可操作
await page.getByRole('button', { name: '提交' }).click()

// ✅ 等特定状态
await expect(page.getByText('保存成功')).toBeVisible()
await expect(page).toHaveURL(/\/orders\/\d+/)

Playwright 的 actionability 检查包括:元素是否可见、是否稳定(不在动画中)、是否可接收事件、是否没有被遮挡。这些检查在点击前自动执行,所以不需要 sleep。

这是 Cypress 时代养成的坏习惯,迁过来后要主动改。我们的用例里 waitForTimeout 从 47 处降到 2 处(两处是等后端定时任务)。

认证:用 storageState 复用登录态

1
2
3
4
5
6
7
8
9
10
11
12
// e2e/auth.setup.ts
import { test as setup } from '@playwright/test'

setup('登录并保存状态', async ({ page }) => {
await page.goto('/login')
await page.getByLabel('用户名').fill('e2e-user')
await page.getByLabel('密码').fill('test-password')
await page.getByRole('button', { name: '登录' }).click()

await expect(page).toHaveURL('/dashboard')
await page.context().storageState({ path: 'e2e/.auth/user.json' })
})
1
2
3
4
5
6
7
8
9
10
11
12
// playwright.config.ts
projects: [
{ name: 'setup', testMatch: /auth\.setup\.ts/ },
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
storageState: 'e2e/.auth/user.json',
},
dependencies: ['setup'],
},
]

这样每个用例不用重复登录(登录一次要 2-3 秒,100 个用例就是 5 分钟)。

但要注意:storageState 会保存 cookie 和 localStorage,如果用例会修改登录状态(比如”退出登录”的测试),要单独用 test.use({ storageState: { cookies: [], origins: [] } })。

测试数据:不要共享账号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// ❌ 所有用例都用同一个账号,并行时会互相干扰
const user = { name: 'testuser' }

// ✅ 每个用例生成独立数据
test('创建订单', async ({ page, request }) => {
const phone = `138${Date.now().toString().slice(-8)}`

// 用 API 快速准备数据,比 UI 点一遍快得多
const res = await request.post('/api/users', { data: { phone } })
const { id } = await res.json()

await page.goto(`/users/${id}/orders`)
// ...
})

用 API 准备数据是 E2E 提速最有效的手段。UI 上建一条数据要 5 秒,API 只要 50ms。E2E 要测的是”UI 层的流程”,前置数据不需要走 UI。

网络拦截

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 模拟接口错误
await page.route('**/api/orders', (route) => {
route.fulfill({ status: 500, body: JSON.stringify({ error: 'boom' }) })
})
await page.goto('/orders')
await expect(page.getByRole('alert')).toHaveText('加载失败')

// 延迟响应(测 loading 状态)
await page.route('**/api/orders', async (route) => {
await new Promise((r) => setTimeout(r, 2000))
route.continue()
})
await page.goto('/orders')
await expect(page.getByText('加载中')).toBeVisible()

// 拦截并修改响应
await page.route('**/api/user', async (route) => {
const response = await route.fetch()
const json = await response.json()
route.fulfill({ response, json: { ...json, role: 'admin' } })
})

最后一种在做”权限相关的视觉验证”时很有用。

视觉回归

1
2
3
4
5
6
7
test('首页布局', async ({ page }) => {
await page.goto('/')
await expect(page).toHaveScreenshot('home.png', {
maxDiffPixelRatio: 0.02, // 允许 2% 像素差异
mask: [page.getByTestId('timestamp')], // 遮掉动态内容
})
})

视觉回归的坑:字体渲染在不同系统上有细微差异。同样的代码在 macOS 和 Linux 上截图不完全一样。

我们的做法:只在 Linux 上跑视觉测试,基线也在 Linux 上生成(用 Docker 保证一致性)。通过 CI 更新基线:

1
2
# 本地更新基线
npx playwright test --update-snapshots

多用户场景

这是 Playwright 相对 Cypress 的明显优势:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
test('两个用户同时编辑,后保存者收到冲突提示', async ({ browser }) => {
const ctx1 = await browser.newContext({ storageState: 'e2e/.auth/user1.json' })
const ctx2 = await browser.newContext({ storageState: 'e2e/.auth/user2.json' })

const page1 = await ctx1.newPage()
const page2 = await ctx2.newPage()

await page1.goto('/doc/1')
await page2.goto('/doc/1')

await page1.getByRole('textbox').fill('版本 A')
await page1.getByRole('button', { name: '保存' }).click()
await expect(page1.getByText('已保存')).toBeVisible()

await page2.getByRole('textbox').fill('版本 B')
await page2.getByRole('button', { name: '保存' }).click()
await expect(page2.getByRole('alert')).toContainText('内容已被修改')

await ctx1.close()
await ctx2.close()
})

多 context 各自隔离 cookie/storage,等价于”两个独立浏览器”。Cypress 做不到这一点。

调试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 有头模式(看着它跑)
npx playwright test --headed

# 单步调试
npx playwright test --debug

# UI 模式(时间旅行、看 locator、重跑)
npx playwright test --ui

# 只跑某个文件/某个测试
npx playwright test e2e/checkout.spec.ts -g "支付成功"

# 看 trace(失败后)
npx playwright show-trace test-results/xxx/trace.zip

--ui 模式是效率提升最大的功能——可以逐个用例重跑、查看每一步的 DOM 快照、实时编辑 locator 并验证。

不稳定的用例怎么治

E2E 最大的敌人是 flaky。我们统计过,flaky 来源分布:

原因 占比 解法
固定 sleep 35% 改成断言等待
测试数据冲突 25% 独立数据 + API 准备
依赖执行顺序 15% 每个用例独立
动画未结束 10% 断言目标状态,或禁用动画
第三方服务慢 10% mock 掉
真 bug 5% 修

禁用动画(减少不确定性):

1
2
3
4
5
6
7
// 在 test 之前注入 CSS
await page.addStyleTag({
content: `*, *::before, *::after {
animation-duration: 0s !important;
transition-duration: 0s !important;
}`,
})

放到 fixtures 里全局生效更省事。

该测什么

E2E 数量应该少而精。我们目前的划分:

1
2
3
4
5
6
7
8
9
10
// ✅ 值得 E2E
test('用户能完成注册-下单-支付全流程')
test('未登录访问后台会跳转登录页')
test('权限不足时菜单不显示')
test('表单校验错误能正确提示')

// ❌ 不值得
test('按钮是蓝色的') // 视觉测试/人工
test('工具函数返回正确值') // 单元测试
test('接口返回 200') // 接口测试

一条经验:E2E 只覆盖”如果坏了会导致业务中断”的路径。我们的项目有 60 个单元测试文件和 18 个 E2E 用例,比例大概是 10:1(用例数约 300:18)。

踩过的坑

1. storageState 里的 cookie 有有效期

如果登录态 30 分钟过期,长时间的测试跑一半会失效。做法是把 token 有效期在测试环境调长,或者 setup 阶段刷新。

2. WebKit 在 Linux 上缺依赖

1
npx playwright install --with-deps webkit

CI 里忘了 --with-deps,WebKit 会因为缺 libwoff2 之类启动失败。

3. toHaveScreenshot 在 CI 上全失败

基线是在 macOS 上生成的,CI 是 Linux。见上文——基线必须在同一环境下生成。

4. 并行 worker 打满测试数据库

workers: 4 意味着 4 个用例同时操作数据库。要注意:

  • 唯一约束(手机号、邮箱)要用随机值
  • 跨用例的计数断言要避免(”应该有 3 条记录”在并行时会失败)

5. route 在 page 级还是 context 级

page.route 只对当前页面生效,context.route 对所有页面生效。如果应用会打开新标签页,必须用 context 级。

6. 忘了 await

1
2
3
4
5
6
7
// ❌ 忘了 await,断言在页面跳转前就执行了
page.getByRole('button').click()
expect(page.url()).toBe('/done')

// ✅
await page.getByRole('button').click()
await expect(page).toHaveURL('/done')

TypeScript 能缓解一部分(Playwright 的 API 都返回 Promise,但 page.click() 不 await 不会报类型错误),可以开 @typescript-eslint/no-floating-promises 规则强制检查。

迁移的实际成本

从 Cypress 迁 40 个 E2E 用例,用了大约 2 周(一个人,非全职):

工作 时间
配置搭建、CI 接入 2 天
逐个改写用例 6 天
修 flaky、调稳定 4 天
视觉测试基线重建 2 天

改写的机械部分很低(cy.get().click() → page.getByRole().click()),真正花时间的是”原来靠 cy.wait(2000) 掩盖的问题”全部暴露出来,需要一个个解决。

但结果是值得的:CI 时间从 11 分钟降到 3 分半(并行 + 去掉无用等待),flaky 率从 18% 降到 2%。

小结

E2E 的投入产出比取决于”写得对不对”,而不是”写得多不多”:

原则 效果
用 role/label 定位 稳定性 + 可访问性
不写 sleep 速度 + 稳定性
API 准备数据 速度(5-10 倍)
storageState 复用登录 速度(每用例省 2-3 秒)
独立测试数据 并行安全
trace on retry 排查效率

一个反直觉的结论:E2E 用例越少越可靠。18 个精心维护的用例,比 80 个到处是 sleep 的用例有价值得多。前者是信心来源,后者是噪音来源——当大家开始习惯”这个测试又挂了,重跑一下”时,测试就失去意义了。

  • 本文标题:E2E 测试:从 Cypress 迁到 Playwright
  • 本文作者:MrSmy
  • 创建时间:2023-05-14 20:06:00
  • 本文链接:https://fengyang.live/2023/05/14/E2E测试:从Cypress迁到Playwright/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!