Playwright 是一个用于 Web 测试和自动化的框架,支持 Chromium、Firefox 和 WebKit 浏览器,并提供统一的 API。它旨在实现快速、可靠、无限的跨浏览器自动化。
基础知识点
- 支持的浏览器:Playwright 支持 Chromium、Firefox 和 WebKit 浏览器,且支持在 Linux、macOS 和 Windows 上运行。
- 无头模式:所有浏览器在所有平台上都支持无头模式执行。
- 测试隔离:每个测试都在独立的浏览器上下文中运行,确保测试之间的隔离。
安装和使用
1. 初始化 Playwright Test
最简单的方式是使用 init
命令:
bash
npm init playwright@latest
或创建新项目:
bash
npm init playwright@latest new-project
2. 手动安装
添加依赖并安装浏览器:
bash
npm i -D @playwright/test
npx playwright install
Playwright 的优势
- 自动等待:Playwright 会等待元素变得可交互后再执行操作,减少了测试的不稳定性。
- 断言:Playwright 的断言是为动态 Web 而设计的,会自动重试直到满足条件。
- 跟踪:可以配置测试重试策略,并捕获执行跟踪、视频和截图以消除测试不稳定性。
示例代码
1. 页面截图
javascript
import { test } from '@playwright/test';
test('Page Screenshot', async ({ page }) => {
await page.goto('https://playwright.dev/');
await page.screenshot({ path: `example.png` });
});
2. 模拟移动设备和地理位置
javascript
import { test, devices } from '@playwright/test';
test.use({
...devices['iPhone 13 Pro'],
locale: 'en-US',
geolocation: { longitude: 12.492507, latitude: 41.889938 },
permissions: ['geolocation'],
})
test('Mobile and geolocation', async ({ page }) => {
await page.goto('https://maps.google.com');
await page.getByText('Your location').click();
await page.waitForRequest(/.*preview\/pwa/);
await page.screenshot({ path: 'colosseum-iphone.png' });
});
3. 在浏览器上下文中执行脚本
javascript
import { test } from '@playwright/test';
test('Evaluate in browser context', async ({ page }) => {
await page.goto('https://www.example.com/');
const dimensions = await page.evaluate(() => {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
deviceScaleFactor: window.devicePixelRatio
}
});
console.log(dimensions);
});
4. 拦截网络请求
javascript
import { test } from '@playwright/test';
test('Intercept network requests', async ({ page }) => {
// Log and continue all network requests
await page.route('**', route => {
console.log(route.request().url());
route.continue();
});
await page.goto('http://todomvc.com');
});
Playwright 的工具
- 代码生成器:可以通过录制操作生成测试代码。
- Playwright Inspector:可以检查页面、生成选择器、逐步执行测试并查看执行日志。
- Trace Viewer:用于捕获测试执行信息,包括视频、截图等,以便于调试测试失败原因。