需要覆盖真实浏览器里的登录、下单、权限跳转等用户路径,并且希望测试在本地和 CI 都能稳定重复执行。Playwright 适合新项目从零搭 E2E,也适合替换依赖固定 sleep 的旧脚本。读完后应能写出可维护的定位器、用 trace 定位失败,并把测试分片跑进流水线。
click、fill、expect 等操作会等待元素可见、可编辑、稳定、可接收事件,默认受 actionTimeout 和测试超时约束。expect(locator).toBeVisible() 会轮询直到通过或超时,比 waitForTimeout 可靠。page 属于 context。show-trace 回放。--shard=1/4 把测试文件分到多个 CI Job,再用 blob report 合并。定位优先级: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。
div:nth-child(3) > span 和构建后哈希 class 一改就碎;优先角色、label、稳定的 data-testid。waitForTimeout(3000) 既慢又不稳;auto-wait 只保证元素可操作,不保证接口返回或列表渲染完成,要用 expect 轮询最终状态。elementHandle,否则丢失自动等待。fullyParallel 下用例顺序不保证;有依赖的流程放同一个 test 里,或显式 test.describe.serial,不要依赖上一个用例的登录态。trace: 'on-first-retry' 却没重试:本地 retries: 0 时不会留下 trace;排查阶段改成 --trace on。use 里固定 locale、timezoneId、viewport。expect 轮询 URL、文本或元素出现等最终结果。blob-report 产物,合并 Job 下载全部产物后执行 npx playwright merge-reports --reporter=html ./all-blobs。
小程序版
微信扫码,随时查命令