Playwright 端到端测试最佳实践概述Playwright 提供跨浏览器(Chromium/Firefox/WebKit)自动化能力与强大的溯源工具。本文示例基于稳定 API,涵盖项目配置、用例编写与网络 Mock。项目配置// playwright.config.ts
import { defineConfig } from '@playwright/test'
export default defineConfig({
testDir: './tests',
use: {
baseURL: 'http://localhost:3000',
trace: 'on-first-retry',
video: 'retain-on-failure',
screenshot: 'only-on-failure',
},
projects: [
{ name: 'chromium', use: { browserName: 'chromium' } },
{ name: 'firefox', use: { browserName: 'firefox' } },
{ name: 'webkit', use: { browserName: 'webkit' } },
],
})
基本用例// tests/home.spec.ts
import { test, expect } from '@playwright/test'
test('home page loads', async ({ page }) => {
await page.goto('/')
await expect(page.getByRole('heading', { name: '欢迎' })).toBeVisible()
})
网络 Mock 与溯源// tests/users.spec.ts
import { test, expect } from '@playwright/test'
test('users list mocked', async ({ page }) => {
await page.route('**/api/users', route => {
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([{ id: 1, name: 'Ada' }]),
})
})
await page.goto('/users')
await expect(page.getByText('Ada')).toBeVisible()
})
Trace 要点:在失败重试时开启追踪,便于定位 DOM、网络与快照;必要时手动 `await page.context().tracing.start/stop`。CI 集成建议并行化:按项目维度并行执行,缩短总耗时。产物保留:失败用例保留视频与截图,便于回放与缺陷复现。验证要点配置与 API 为稳定特性;用例可在本地与 CI 一致运行。通过 Trace 查看失败细节,配合网络 Mock 提升可控性与测试速度。

发表评论 取消回复