关于 playwright
用于编写和运行 Playwright 端到端浏览器测试的技能指南,涵盖跨浏览器测试、可复用页面对象,以及通过跟踪记录和截图调试。
主要功能
- 01Chromium、Firefox 和 WebKit 测试
- 02自动等待定位器与断言
- 03多页面与浏览器上下文
- 04带跟踪记录和截图的 CI 项目
- 05页面对象模式指南
适用场景
- 01测试网站登录流程
- 02在 CI 中运行浏览器测试
- 03通过跟踪记录和截图调试失败
- 04用页面对象组织可维护的测试
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ partme-ai/ full-stack-skills --skill playwright安装后在 Claude Code 中输入/playwright确认已加载。
附带文件LICENSE.txt
详细介绍
适用场景
当用户想要执行以下操作时,使用此技能:
- 使用 Playwright(Chromium、Firefox、WebKit)编写端到端浏览器测试
- 使用自动等待定位器和内置断言
- 处理多个页面、标签页和浏览器上下文
- 配置 Playwright 项目,以便在 CI 中运行并生成跟踪记录和屏幕截图
- 实现页面对象模型模式,编写易于维护的测试
使用方法
工作流
- 初始化 Playwright:运行
npm init playwright生成配置和示例测试 - 编写测试:使用自动等待定位器(
getByRole、getByLabel、getByText) - 运行测试:运行
npx playwright test,可选择无头、有头或 UI 模式 - 调试失败的测试:使用跟踪记录、屏幕截图和 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. 页面对象模型
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或夹具准备状态 - 在 CI 中安装浏览器和依赖项(
npx playwright install --with-deps) - 测试失败时保留跟踪记录和屏幕截图,以便调试
- 使用 Playwright 内置的
expect断言——它们会自动重试
资源
- 官方文档:https://playwright.dev/docs/intro
- API 参考:https://playwright.dev/docs/api/class-playwright
- 最佳实践:https://playwright.dev/docs/best-practices
关键词
playwright、E2E、端到端测试、跨浏览器、自动等待、定位器、getByRole、跟踪记录、页面对象模型、Chromium、Firefox、WebKit
评论
支持 Markdown