南京市网站建设_网站建设公司_前端开发_seo优化
2025/12/22 10:48:25 网站建设 项目流程

Playwright 移动端测试(2025 年最新版)

Playwright 原生支持移动端浏览器模拟(Mobile Emulation)和真实 Android 设备测试,无需额外工具即可覆盖手机/平板场景。核心优势:一套代码跨桌面 + 移动浏览器运行,支持触屏手势、横竖屏、地理位置、设备特性等。

1.最常用方式:浏览器模拟移动设备(Emulation)

无需真实设备,速度快,适合 90% 的移动端测试场景。

在 playwright.config.ts 中定义项目

import{defineConfig,devices}from'@playwright/test';exportdefaultdefineConfig({projects:[// 桌面 Chrome{name:'Desktop Chrome',use:{...devices['Desktop Chrome']}},// iPhone 示例{name:'iPhone 14',use:{...devices['iPhone 14']}},{name:'iPhone 14 Landscape',use:{...devices['iPhone 14 landscape']}},// Android 示例{name:'Pixel 7',use:{...devices['Pixel 7']}},// iPad 示例{name:'iPad Pro',use:{...devices['iPad Pro 11']}},],});

Playwright 内置 100+ 设备模型(devices.ts 源文件),常用:

  • iPhone 13/14/15(包括 Pro/Max、landscape)
  • Pixel 5/7
  • Galaxy S23
  • iPad Air/Mini/Pro

运行移动端测试

npx playwrighttest--project="iPhone 14"# 只跑 iPhonenpx playwrighttest--project="Pixel 7"npx playwrighttest# 默认并行跑所有项目
2.测试代码示例(自动适配移动端)
import{test,expect}from'@playwright/test';test('移动端首页响应式验证',async({page})=>{awaitpage.goto('https://your-app.com');// 移动端特有:验证视口大小(自动由设备配置设置)constviewport=page.viewportSize();console.log('当前视口:',viewport);// e.g., { width: 390, height: 844 }// 验证移动端菜单(汉堡菜单)awaitexpect(page.getByRole('button',{name:'菜单'})).toBeVisible();// 模拟触屏点击(等同 click(),但更真实)awaitpage.getByRole('button',{name:'菜单'}).tap();// 模拟手势:滑动(swipe)awaitpage.touchscreen.tap(200,600);// 触摸起点awaitpage.touchscreen.touchMove(200,200);// 向上滑动// 验证横竖屏切换awaitpage.setViewportSize({width:844,height:390});// 切换到横屏awaitexpect(page.getByText('横屏布局')).toBeVisible();});
3.移动端特有功能
// 模拟地理位置test.use({geolocation:{longitude:116.397,latitude:39.909},// 北京permissions:['geolocation'],});// 模拟网络(离线/慢网)test.use({offline:true,// 离线模式// 或慢网javaScriptEnabled:true,// 自定义:通过 context 设置});// 触屏手势(touchscreen)awaitpage.touchscreen.tap(x,y);awaitpage.touchscreen.touchMove(x,y);awaitpage.touchscreen.touchEnd();// 捏合缩放(pinch zoom)awaitpage.touchscreen.touchStart(x1,y1,x2,y2);// 两指
4.真实 Android 设备测试(高级)

Playwright 支持直接连接真实 Android 手机(无需 Appium)。

前提

  • Android 设备开启 USB 调试。
  • 安装 Android SDK Platform-Tools(adb)。

配置示例

import{android}from'@playwright/test';test('真实 Android 设备',async()=>{const[device]=awaitandroid.devices();// 自动发现连接设备constcontext=awaitdevice.launchBrowser();constpage=awaitcontext.newPage();awaitpage.goto('https://your-app.com');awaitpage.screenshot({path:'real-android.png'});awaitcontext.close();});
5.最佳实践总结
  • 优先使用设备模拟(devices[‘iPhone 14’] 等),速度快、覆盖广。
  • 多项目并行:在 config 中定义多个移动设备项目,CI/CD 自动覆盖。
  • 响应式断言:根据 viewportSize() 或设备名动态断言不同布局。
  • 截图对比:移动端测试建议开启screenshot: 'on',失败时对比视觉差异。
  • 真实设备:仅在需要测试硬件特性(如摄像头、传感器)时使用。

运行示例:

npx playwrighttest--project="iPhone 14"--headed# 可视化看移动端效果

移动端测试在 Playwright 中实现非常优雅,一套代码覆盖桌面 + 多款手机/平板。官方设备列表:https://playwright.dev/docs/emulation#devices

如果需要完整响应式测试示例(如媒体查询断言)、自定义设备配置,或真实 Android 连接步骤,随时告诉我!

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询