系统学习 测试与质量四阶段学习路径:从单元与接口测试,到端到端、性能、契约和 CI 门禁

Playwright 端到端测试的定位、自动等待、调试与 CI 分片

适用场景

需要覆盖真实浏览器里的登录、下单、权限跳转等用户路径,并且希望测试在本地和 CI 都能稳定重复执行。Playwright 适合新项目从零搭 E2E,也适合替换依赖固定 sleep 的旧脚本。读完后应能写出可维护的定位器、用 trace 定位失败,并把测试分片跑进流水线。

核心概念 / 语法

定位优先级:getByRole → getByLabel / getByPlaceholder → getByTestId → CSS。少用 nth-child、自动生成的 class 和依赖文案的 XPath。

常用示例

安装并初始化:

npm init playwright@latest
npm install -D @playwright/test
npx playwright install --with-deps chromium

最小配置 playwright.config.ts:

import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  fullyParallel: true,
  retries: process.env.CI ? 2 : 0,
  reporter: process.env.CI ? [['blob'], ['html', { open: 'never' }]] : 'html',
  use: {
    baseURL: process.env.BASE_URL ?? 'http://127.0.0.1:3000',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'mobile', use: { ...devices['Pixel 7'] } },
  ],
});

一个完整的登录用例:

import { test, expect } from '@playwright/test';

test('登录后进入工作台', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('邮箱').fill('qa@example.com');
  await page.getByLabel('密码').fill('test-password');
  await page.getByRole('button', { name: '登录' }).click();

  await expect(page).toHaveURL(/\/dashboard/);
  await expect(page.getByRole('heading', { name: '工作台' })).toBeVisible();
});

调试 trace 与分片:

npx playwright test
npx playwright test --trace on
npx playwright show-trace test-results/*/trace.zip
npx playwright test --shard=1/4
# 合并各分片上传的 blob-report
npx playwright merge-reports --reporter=html ./all-blobs

复用登录态,避免每个用例都走 UI 登录:

// tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';

setup('authenticate', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('邮箱').fill(process.env.E2E_USER!);
  await page.getByLabel('密码').fill(process.env.E2E_PASS!);
  await page.getByRole('button', { name: '登录' }).click();
  await expect(page).toHaveURL(/\/dashboard/);
  await page.context().storageState({ path: 'playwright/.auth/user.json' });
});

在配置里加 setup project,并让浏览器 project 设置 storageState 与 dependencies: ['setup']。服务端 session 过期时,setup 会先失败,定位比“所有用例莫名跳登录页”快。

CI 中的分片命令:

# 每个矩阵 Job 安装浏览器后执行自己的分片
npx playwright install --with-deps chromium
npx playwright test --shard=$SHARD_INDEX/$SHARD_TOTAL
# 各 Job 上传 blob-report;合并 Job 下载全部产物后执行
npx playwright merge-reports --reporter=html ./all-blobs

GitHub Actions 用 matrix.shard: [1, 2, 3, 4] 生成 4 个 Job,并用 actions/upload-artifact 保存 blob-report,详见 github-actions。

易错点

相关条目

参考链接

读完自测

  1. Playwright 的 auto-wait 能等到元素可点击,为什么还不能替代对业务结果的断言?
  2. CI 里 4 个分片各自生成了 blob report,怎样合并成一个 HTML 报告?
  3. 多个用例并行操作同一个测试账号,可能出现什么问题和怎么隔离?
答案
  1. auto-wait 只保证元素满足可操作性,不保证接口返回、列表渲染或业务状态完成;要用 expect 轮询 URL、文本或元素出现等最终结果。
  2. 每个分片用 blob reporter 输出,CI 上传 blob-report 产物,合并 Job 下载全部产物后执行 npx playwright merge-reports --reporter=html ./all-blobs。
  3. 并发登录会互相踢下线、共享数据会冲突或断言到别人的记录;应使用唯一账号和数据、API 造数,或把有依赖的流程放在同一个串行测试里。
微信小程序码:扫码打开命令速查小程序

小程序版

微信扫码,随时查命令