用途
本技能用于指导使用 Playwright 进行浏览器自动化与端到端(E2E)测试。当用户需要编写端到端浏览器测试、使用自动等待定位器与内置断言、处理多页面/标签页/浏览器上下文、为 CI 执行配置 Playwright 项目(含 trace 与截图),或实现 Page Object Model 模式以保持测试可维护时,可使用本技能。
主要能力
- 编写基于 Playwright 的端到端浏览器测试,覆盖 Chromium、Firefox、WebKit。
- 使用自动等待(auto-waiting)定位器与内置断言。
- 处理多个页面、标签页与浏览器上下文。
- 为 CI 执行配置 Playwright 项目,支持 trace 与截图。
- 实现 Page Object Model 模式,提升测试可维护性。
使用方式
工作流程:
- 初始化 Playwright:
npm init playwright生成配置与示例测试。 - 使用自动等待定位器(getByRole、getByLabel、getByText)编写测试。
- 运行测试:
npx playwright test,支持 headless、headed 或 UI 模式。 - 使用 trace、截图与 Playwright Inspector 调试失败。
1. 基础测试
import { test, expect } from '@playwright/test';
test('homepage has title', async ({ page }) => {
await page.goto('https://example.com');
await expect(page).toHaveTitle(/Example/);
});
test('login flow', async ({ page }) => {
await page.goto('https://example.com/login');
await page.getByLabel('Username').fill('testuser');
await page.getByLabel('Password').fill('secret');
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page.getByText('Dashboard')).toBeVisible();
});
2. Page Object Model
class LoginPage {
constructor(private page: Page) {}
async login(username: string, password: string) {
await this.page.getByLabel('Username').fill(username);
await this.page.getByLabel('Password').fill(password);
await this.page.getByRole('button', { name: 'Sign in' }).click();
}
}
3. 配置
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './tests',
retries: 2,
use: {
baseURL: 'https://example.com',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{ name: 'chromium', use: { browserName: 'chromium' } },
{ name: 'firefox', use: { browserName: 'firefox' } },
{ name: 'webkit', use: { browserName: 'webkit' } },
],
});
4. 运行测试
npx playwright test # Run all tests headless
npx playwright test --headed # Run with browser visible
npx playwright test --ui # Interactive UI mode
npx playwright show-report # View HTML report
最佳实践
- 优先使用基于角色的定位器(getByRole、getByLabel),而非脆弱的 XPath 或 CSS 选择器。
- 保持测试独立且可重复;使用 beforeEach 或 fixtures 准备状态。
- 在 CI 中安装浏览器与依赖(
npx playwright install --with-deps)。 - 在失败时保留 trace 与截图以便调试。
- 使用 Playwright 内置的 expect 断言——它们会自动重试。
适用场景
适用于需要编写和维护端到端浏览器测试、进行跨浏览器验证、在 CI 中运行测试并保留调试信息,以及通过 Page Object Model 组织测试代码的项目。
限制
资料未提供关于收费、价格、平台限制或具体效果的信息,暂未提供。
资源
- 官方文档:https://playwright.dev/docs/intro
- API 参考:https://playwright.dev/docs/api/class-playwright
- 最佳实践:https://playwright.dev/docs/best-practices
关键词
playwright, E2E, end-to-end testing, cross-browser, auto-wait, locators, getByRole, trace, Page Object Model, Chromium, Firefox, WebKit