用途
Playwright 是用于浏览器自动化的端到端(E2E)测试框架。本技能适用于以下场景:搭建测试环境、编写 E2E 测试场景、调试测试失败、配置并行执行,以及在 WSL2 环境下运行浏览器测试。
主要能力
- 跨浏览器:从同一套代码测试 Chrome、Firefox、Safari/WebKit。
- 多语言:支持 JavaScript、TypeScript、Python、Java、.NET。
- 自动等待(Auto-wait):智能等待元素就绪。
- 代码生成(Codegen):在浏览器中点击即可录制测试。
- 并行化:原生、免费的并行执行。
- WSL2 兼容:可与 Windows 上的 Chrome 配合使用。
使用方式
快速开始
- 初始化 Playwright:
# 创建新项目或添加到现有项目
npm init playwright@latest
# 安装浏览器
npx playwright install
- 编写第一个测试(tests/example.spec.ts):
import { test, expect } from '@playwright/test';
test('homepage has title', async ({ page }) => {
await page.goto('https://your-app.com');
await expect(page).toHaveTitle(/Your App/);
});
test('login works', async ({ page }) => {
await page.goto('https://your-app.com/login');
await page.fill('[name="email"]', 'test@example.com');
await page.fill('[name="password"]', 'password123');
await page.click('button[type="submit"]');
await expect(page).toHaveURL(/dashboard/);
});
- 运行测试:
# 运行所有测试
npx playwright test
# 有头模式运行(可见浏览器)
npx playwright test --headed
# 运行指定测试文件
npx playwright test tests/login.spec.ts
# UI 模式(交互式)
npx playwright test --ui
创建 E2E 测试的工作流
- 使用 Codegen 录制:
npx playwright codegen https://your-app.com;保存认证状态:npx playwright codegen --save-storage=auth.json https://your-app.com。 - 组织测试目录(e2e、visual、api、fixtures 等)。
- 使用页面对象(Page Objects)封装页面操作。
- 在 playwright.config.ts 中配置并行执行、重试、报告器与多浏览器项目。
WSL2 配置
- 方案一:使用 Windows Chrome(推荐),设置
CHROME_BIN环境变量指向 Windows 上的 chrome.exe。 - 方案二:远程调试,在 Windows 上以
chrome.exe --remote-debugging-port=9222启动,再用chromium.connectOverCDP('http://localhost:9222')连接。 - 方案三:WSLg(Windows 11 内置),可直接运行有头测试。
最佳实践
- 定位器优先级:Role > Label > Placeholder > Test ID > CSS(尽量避免)。
- 不要添加手动等待,Playwright 会自动等待。
- 并行执行:
test.describe.configure({ mode: 'parallel' });需要顺序时用serial。
CI/CD 集成
提供 GitHub Actions 工作流示例,包含安装依赖、安装浏览器、运行测试,并在失败时上传 playwright-report 产物。
调试
- Trace Viewer:
npx playwright show-trace trace.zip。 - UI 模式:
npx playwright test --ui。 - 有头模式:
npx playwright test --headed --slowmo=500。 - VS Code 集成:安装 “Playwright Test for VS Code” 扩展。
常用命令
npx playwright test:运行所有测试。npx playwright test --headed:有头运行。npx playwright test --ui:交互式 UI 模式。npx playwright codegen <url>:点击录制测试。npx playwright show-report:查看 HTML 报告。npx playwright show-trace <file>:查看 trace 文件。npx playwright install:安装浏览器。npx playwright --version:查看版本。
适用场景
适用于 Web 应用的端到端测试、跨浏览器兼容性验证、视觉回归测试、API 测试,以及需要并行执行和 CI/CD 集成的自动化测试流程。
限制
资料中未提供关于收费、价格、平台限制或具体性能基准的完整信息,部分内容暂未提供。