🎭 Playwright:跨浏览器自动化测试框架

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:用于捕获测试执行信息,包括视频、截图等,以便于调试测试失败原因。
相关推荐
excel6 分钟前
JavaScript 中 WeakMap、WeakSet、Set、Map、Object、Array 的区别与应用场景
前端
haaaaaaarry43 分钟前
Element Plus常见基础组件(一)
java·前端·javascript·vue.js
qingyingWin1 小时前
原生微信小程序研发,如何对图片进行统一管理?
前端·微信小程序
Goboy1 小时前
分库分表后ID乱成一锅粥
后端·面试·架构
不懂英语的程序猿1 小时前
【JEECG】JVxeTable表格拖拽排序功能
前端·后端
拾光拾趣录1 小时前
前端灵魂拷问:从URL到Redux,17个常见问题
前端·面试
萌萌哒草头将军1 小时前
Prisma ORM 又双叒叕发布新版本了!🚀🚀🚀
前端·javascript·node.js
mldong2 小时前
推荐一款超高颜值的后台管理模板!Art-Design-Pro!开源!免费!
前端·vue.js·架构
草字2 小时前
uniapp 如果进入页面输入框自动聚焦,此时快速返回页面或者跳转到下一个页面,输入法顶上来的页面出现半屏的黑屏问题。
java·前端·uni-app
我是ed.2 小时前
cocos Js 使用 webview 通过 postMessage 进行通信
开发语言·javascript·ecmascript