Playwright 移动端模拟与响应式测试:窄窗口不等于移动端
背景:移动端适配不能只靠"缩窗口"
做移动端测试时,一个常见误区是:把浏览器窗口拖窄,就算测过移动端了。
实际上,窄窗口和真实移动设备是两回事:
| 维度 | 窄窗口 | 真实移动端 |
|---|---|---|
| User-Agent | 桌面 UA | 移动 UA |
| 视口 | 桌面视口 | 带 devicePixelRatio 的设备视口 |
| 触摸事件 | 无 | touchstart / touchmove |
| 屏幕特性 | 无 | isMobile / hasTouch |
| 媒体查询 | 部分生效 | 完整生效(含 hover: none) |
很多移动端 bug 恰恰藏在"触摸事件"和"hover 状态"里 —— 只改窗口宽度是测不出来的。
二、用设备描述符模拟
Playwright 内置了主流设备的描述符:
const { devices } = require('playwright-core');
const iphone = devices['iPhone 13'];
console.log(iphone);
// {
// userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 ...)',
// viewport: { width: 390, height: 844 },
// deviceScaleFactor: 3,
// isMobile: true,
// hasTouch: true,
// defaultBrowserType: 'webkit'
// }
一次性套用所有参数:
const ctx = await browser.newContext({
...devices['iPhone 13'],
});
注意 ... 展开——别只传 viewport,那样会丢掉 isMobile 和 hasTouch,等于白搭。
常用设备
devices['iPhone 13'] // 390×844 DPR 3
devices['iPhone SE'] // 375×667 DPR 2
devices['Pixel 7'] // 412×915 DPR 2.625
devices['iPad Pro 11'] // 834×1194 DPR 2
devices['Galaxy S9+'] // 320×658 DPR 4.5
完整列表见 require('playwright-core').devices。
自定义设备
如果目标是国产机型或特殊分辨率,手动构造:
const ctx = await browser.newContext({
viewport: { width: 393, height: 873 },
deviceScaleFactor: 2.75,
isMobile: true,
hasTouch: true,
userAgent: 'Mozilla/5.0 (Linux; Android 14; CustomPhone) AppleWebKit/537.36 ...',
});
运行时改变视口
已经登录的会话想切到移动视口,不必重开 context:
await page.setViewportSize({ width: 390, height: 844 });
但要注意:setViewportSize 只改视口尺寸,不会改 UA、isMobile、hasTouch。如果被测逻辑依赖这些,必须重建 context。
三、触摸与手势
点击
开了 hasTouch: true 之后,click() 会自动走触摸路径。但显式用 tap 更贴近真实:
await page.locator('.menu-btn').tap();
滑动
Playwright 没有内置的 swipe,需要用 touchscreen API 手动组合:
// 从上往下滑(下拉刷新)
await page.touchscreen.tap(200, 300); // 先按住
// 或者用鼠标事件模拟(部分场景够用)
await page.mouse.move(200, 300);
await page.mouse.down();
await page.mouse.move(200, 600, { steps: 10 });
await page.mouse.up();
steps: 10 很关键——它把移动拆成多个中间点,否则很多手势识别库会认为这是一次"瞬移"而不是滑动。
双击缩放
await page.touchscreen.tap(200, 300);
await page.waitForTimeout(50);
await page.touchscreen.tap(200, 300);
两次点击间隔要短(<300ms),否则会被识别成两次单击。
长按
await page.touchscreen.tap(200, 300); // 按下并抬起
// 长按需要用 CDP 或底层事件,多数场景可用等待模拟
长按在 Playwright 里没有直接 API,可通过 dispatchEvent 构造 touchstart + 延迟 + touchend。
四、响应式断点测试
除了模拟真机,还要验证不同宽度下的布局。这是纯视觉问题,适合用截图对比:
const BREAKPOINTS = [
{ name: 'mobile', width: 375, height: 667 },
{ name: 'tablet', width: 768, height: 1024 },
{ name: 'desktop', width: 1440, height: 900 },
];
for (const bp of BREAKPOINTS) {
await page.setViewportSize({ width: bp.width, height: bp.height });
await page.waitForTimeout(800); // 等重排完成
await page.screenshot({ path: `out/${bp.name}.png`, fullPage: true });
}
检查要点
光截图不够,还要断言关键元素的状态:
async function checkLayout(page, bp) {
const navVisible = await page.locator('.desktop-nav').isVisible();
const burgerVisible = await page.locator('.burger-menu').isVisible();
if (bp.width < 768) {
if (navVisible) throw new Error('移动端不该显示桌面导航');
if (!burgerVisible) throw new Error('移动端汉堡菜单缺失');
} else {
if (!navVisible) throw new Error('桌面端导航未显示');
if (burgerVisible) throw new Error('桌面端不该显示汉堡菜单');
}
}
布局类 bug 的典型特征:元素"存在但不可见"或"可见但错位"。所以 isVisible() 比 count() 更有用。
五、hover 相关的坑
这是移动端测试里最容易被忽略的一类问题。
桌面端常用 :hover 显示下拉菜单:
.dropdown:hover .menu { display: block; }
到移动端上,没有 hover 状态,这个菜单就永远打不开。
检测方法:在移动视口下检查媒体查询是否命中:
const hasHover = await page.evaluate(() => window.matchMedia('(hover: hover)').matches);
console.log('支持 hover:', hasHover); // 移动端应为 false
正确的移动端写法通常是:
@media (hover: hover) {
.dropdown:hover .menu { display: block; }
}
/* 移动端改用点击触发 */
测试的价值就在于:在真实设备描述符下跑一遍,能立刻暴露这种"只在桌面能用"的交互。
六、视觉对比的几个注意点
移动端截图对比很容易出现假阳性:
- 字体渲染差异 —— 不同系统字体不同,像素级对比必然失败。用容差阈值:
expect(await page.screenshot()).toMatchSnapshot('home.png', {
maxDiffPixelRatio: 0.02, // 允许 2% 差异
});
- 动态内容 —— 时间、随机头像、广告位会不断变化。截图前先隐藏:
await page.addStyleTag({
content: '.timestamp, .ad-banner, .avatar { visibility: hidden !important; }',
});
- 动画未结束 —— 截图前等一下,或者禁用动画:
await page.addStyleTag({
content: '* { animation: none !important; transition: none !important; }',
});
- 滚动位置 —— 用
fullPage: true拍整页,避免因滚动位置不同导致差异。
七、一个实用的移动端检查清单
async function checkMobileReadiness(page) {
const issues = [];
// 1) 视口 meta 标签
const viewportMeta = await page.getAttribute('meta[name=viewport]', 'content');
if (!viewportMeta || !viewportMeta.includes('width=device-width')) {
issues.push('缺少 viewport meta 标签,移动端会按桌面宽度渲染');
}
// 2) 横向溢出
const overflow = await page.evaluate(() =>
document.documentElement.scrollWidth > document.documentElement.clientWidth
);
if (overflow) issues.push('存在横向溢出,页面可以左右滚动');
// 3) 可点击元素是否够大
const tooSmall = await page.evaluate(() => {
const bad = [];
document.querySelectorAll('button, a, [role=button]').forEach((el) => {
const r = el.getBoundingClientRect();
if (r.width > 0 && r.height > 0 && (r.width < 44 || r.height < 44)) {
bad.push(el.className || el.tagName);
}
});
return bad.slice(0, 5);
});
if (tooSmall.length) issues.push('点击区域小于 44px: ' + tooSmall.join(', '));
// 4) hover 依赖
const hasHover = await page.evaluate(() => window.matchMedia('(hover: hover)').matches);
if (!hasHover) {
const hoverOnly = await page.evaluate(() =>
[...document.styleSheets].flatMap((s) => {
try { return [...s.cssRules].map((r) => r.cssText); } catch { return []; }
}).filter((t) => t.includes(':hover')).length
);
if (hoverOnly > 0) issues.push(`存在 ${hoverOnly} 条 :hover 规则,移动端可能失效`);
}
return issues;
}
44px 是业界公认的最小可点击尺寸(Apple HIG 和 Material Design 都采用这个值),小于它在真机上会很难点中。
小结
| 场景 | 做法 |
|---|---|
| 模拟真机 | ...devices['iPhone 13'](注意展开) |
| 只改视口 | setViewportSize()(不改 UA / 触摸) |
| 点击 | tap() 优于 click() |
| 滑动手势 | mouse.move(..., {steps: 10}) 拆成多步 |
| 布局断点 | 逐个视口截图 + isVisible() 断言 |
| hover 依赖 | 检查 (hover: hover) 媒体查询 |
| 截图对比 | 设容差 + 隐藏动态内容 + 禁用动画 |
三条核心认知:
- 窄窗口 ≠ 移动端 —— UA、触摸、DPR 都要一起改,只改宽度是自欺欺人
- 移动端 bug 集中在交互 —— hover 失效、点击区域太小、手势不识别
- 视觉对比要控制变量 —— 字体、动画、动态内容都会制造假阳性
本文为实践总结,示例基于 Playwright 的 devices 与 touchscreen API。
- 点赞
- 收藏
- 关注作者
评论(0)