Playwright:Web测试与自动化框架介绍

Playwright:Web测试与自动化框架介绍

技术背景

Playwright 是一个用于 Web 测试和自动化的框架,它允许使用单一 API 对 Chromium、Firefox 和 WebKit 进行测试。该框架旨在实现跨浏览器的 Web 自动化,具备常青、强大、可靠和快速的特点,支持在 Linux、macOS 和 Windows 系统上对多种浏览器进行无头执行。

实现步骤

安装

Playwright 有自己的端到端测试运行器 Playwright Test,以下是安装步骤:

  1. 使用 init 命令
    • 在项目根目录运行:
1
npm init playwright@latest
- 或者创建新项目:
1
npm init playwright@latest new-project
此命令会创建配置文件,可选择添加示例、GitHub Action 工作流和第一个测试示例 `example.spec.ts`。
  1. 手动添加依赖并安装浏览器
1
2
3
npm i -D @playwright/test
# 安装支持的浏览器
npx playwright install
也可以选择仅安装特定浏览器,或不安装浏览器而使用现有浏览器通道。

核心代码

页面截图

1
2
3
4
5
6
import { test } from '@playwright/test';

test('Page Screenshot', async ({ page }) => {
await page.goto('https://playwright.dev/');
await page.screenshot({ path: `example.png` });
});

移动和地理位置模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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' });
});

在浏览器上下文中执行脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
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);
});

拦截网络请求

1
2
3
4
5
6
7
8
9
10
import { test } from '@playwright/test';

test('Intercept network requests', async ({ page }) => {
// 记录并继续所有网络请求
await page.route('**', route => {
console.log(route.request().url());
route.continue();
});
await page.goto('http://todomvc.com');
});

最佳实践

  • 使用自动等待:Playwright 会在执行操作前等待元素可操作,结合丰富的自省事件,消除不稳定测试的主要原因——人为超时。
  • 利用浏览器上下文:为每个测试创建浏览器上下文,实现测试的完全隔离,且开销为零。还可以保存上下文的认证状态,避免每个测试中的重复登录操作。
  • 借助强大工具:使用 Codegen 录制操作生成测试代码,利用 Playwright 检查器检查页面、生成选择器,使用 Trace Viewer 捕获信息以调查测试失败。

常见问题

  • 浏览器安装问题:如果遇到浏览器安装失败,可检查网络连接,或手动指定要安装的浏览器。
  • 测试执行缓慢:确保测试环境稳定,避免不必要的等待时间,合理使用自动等待功能。

Playwright:Web测试与自动化框架介绍
https://119291.xyz/posts/playwright-web-testing-and-automation-introduction/
作者
ww
发布于
2025年7月19日
许可协议