当前位置: 首页 > news >正文

常用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');
});

适用于金融、游戏或聊天应用程序

http://www.xdnf.cn/news/456913.html

相关文章:

  • π0: A Vision-Language-Action Flow Model for General Robot Control
  • PowerBI链接EXCEL实现自动化报表
  • 【Linux系统】从 C 语言文件操作到系统调用的核心原理
  • vscode c++编译onnxruntime cuda 出现的问题
  • VScode各文件转化为PDF的方法
  • 赛博放生:用数字技术重构心灵仪式
  • 各个历史版本mysql/tomcat/Redis/Jdk/Apache下载地址
  • 【深度学习之四】知识蒸馏综述提炼
  • Golang基础知识—cond
  • 51c~C语言~合集5
  • Python Bug 修复案例分析:asyncio 事件循环异常引发的程序崩溃 两种修复方法
  • 深度解析 IDEA 集成 Continue 插件:提升开发效率的全流程指南
  • 2025长三角杯数学建模A题:智能手机产品设计优化与定价问题,赛题发布与思路分析
  • 2025.05.14华为机考笔试题-第一题-100分
  • 边缘计算模块
  • 解密企业级大模型智能体Agentic AI 关键技术:MCP、A2A、Reasoning LLMs-docker MCP解析
  • 开源GPU架构RISC-V VCIX的深度学习潜力测试:从RTL仿真到MNIST实战
  • 1、数据结构与算法(Python版-啃书)-绪论
  • CodeEdit:macOS上一款可以让Xcode退休的IDE
  • React 第四十一节Router 中 useActionData 使用方法案例以及注意事项
  • SQL笔记一
  • C#.NET 或 VB.NET Windows 窗体中的 DataGridView – 技巧、窍门和常见问题
  • 资产管理系统评测:功能、易用性、性价比全面对比
  • [C++面试] lambda面试点
  • 使用gitbook 工具编写接口文档或博客
  • AWS EC2 微服务 金丝雀发布(Canary Release)方案
  • 使用WebSocket实现跨多个服务器传输音频及实时语音识别
  • Linux线程控制
  • 2025年5月华为H12-821新增题库带解析
  • 阿里云CMH镜像迁移与SMC整机迁移对比及功能详解(同地域跨主体账号场景)