常用Playwright代码片段-Part4
1.衡量绩效指标
捕获加载时间和性能数据
test('should measure page load time', async ({ page }) => {await page.goto('https://example.com');const metrics = await page.evaluate(() => JSON.stringify(window.performance));console.log(metrics);
});
2.在 UI 测试中自动确认电子邮件
使用虚假的 SMTP 服务器来自动执行电子邮件验证
import nodemailer from 'nodemailer';
const transporter = nodemailer.createTransport({host: 'localhost',port: 1025, // Example SMTP serversecure: false
});
test('should receive verification email', async () => {const mailOptions = {from: 'no-reply@example.com',to: 'testuser@example.com',subject: 'Verify Your Email'};await transporter.sendMail(mailOptions);
});
3.在 Docker 中运行测试
使用Dockerized Playwright获得干净的环境
docker run --rm -v $(pwd):/app mcr.microsoft.com/playwright npx playwright test
4.生成多种格式的报告
Playwright 支持多种测试报告
npx playwright test --reporter=html,junit
或者配置playwright.config.js
:
{"reporter": [["list"], ["json", { "outputFile": "results.json" }]]
}
5.处理多因素身份验证(MFA)
对于具有 MFA 的应用程序,请使用OTP 或会话令牌
test('bypass OTP', async ({ page }) => {await page.route('**/otp-verification', async (route) => {await route.fulfill({ status: 200, body: JSON.stringify({ success: true, otp: '123456' }) });});
});
6.使用 Playwright 和 Appium 实现移动测试自动化
对于混合应用程序,将Playwright 与 Appium结合起来进行更深入的移动测试
import { remote } from 'webdriverio';
const driver = await remote({capabilities: {platformName: 'Android',deviceName: 'emulator-5554',browserName: 'chrome'}
});
await driver.url('https://example.com');
7.使用 Cron Job 安排测试
以固定的时间间隔自动执行测试
crontab -e 0 0 * * * cd /path-to-tests && npx playwright test
8.混合测试:Playwright + API 请求
无需始终与 UI 交互,使用API 请求来加快测试设置速度示例:通过 API 登录,然后导航至 UI
test('Login via API, then test UI', async ({ request, page }) => {const response = await request.post('https://example.com/api/login', {data: { username: 'testuser', password: 'password123' }});const { token } = await response.json();
// Use token in UI sessionawait page.context().addCookies([{ name: 'auth_token', value: token, domain: 'example.com' }]);await page.goto('https://example.com/dashboard');await expect(page.locator('[data-testid="welcome-message"]')).toBeVisible();
});
9.使用 Playwright 模拟 API 调用
模拟服务器响应以测试 UI 行为,无需实际后端依赖示例:模拟 API 响应
test('Mock API response', async ({ page }) => {await page.route('**/api/user', async (route) => {route.fulfill({status: 200,contentType: 'application/json',body: JSON.stringify({ name: 'Mock User', age: 30 })});});
await page.goto('https://example.com/profile');await expect(page.locator('[data-testid="user-name"]')).toHaveText('Mock User');
});
10.测试 WebSockets 和实时更新
测试实时更新的 UI (例如聊天、股票价格)示例:拦截 WebSocket 消息
test('Test real-time WebSocket data', async ({ page }) => {const ws = await page.waitForEvent('websocket');ws.on('framereceived', async (frame) => {console.log('WebSocket Data:', frame.payload);});await page.goto('https://example.com/realtime-dashboard');
});
适用于金融、游戏或聊天应用程序