如何消除Playwright有头与无头模式下的截图差异?
Playwright截图测试1px高度差异解决方法
一、消除差异根源
统一渲染参数
无头/有头模式默认配置差异会导致渲染尺寸偏移,显式固定视口、设备像素比:
test('fixed viewport test', async ({ page }) => { await page.setViewportSize({ width: 1280, height: 720 }); await page.setDeviceScaleFactor(1); // 强制统一缩放比例 // 测试逻辑 await page.locator('.target-element').toHaveScreenshot(); });
禁用字体渲染差异
系统字体平滑、子像素定位可能导致1px高度差,通过浏览器启动参数禁用:
// playwright.config.js module.exports = { use: { launchOptions: { args: [ '--disable-font-subpixel-positioning', '--disable-font-antialiasing', '--force-device-scale-factor=1' ] } } };
等待元素完全稳定
元素动画、异步加载可能导致尺寸未固定时截图,添加稳定等待:
await page.locator('.target-element').waitFor({ state: 'stable' }); await page.locator('.target-element').toHaveScreenshot();
二、强制忽略差异
自定义裁剪对比逻辑
若无法消除尺寸差,手动裁剪多余1px后对比像素:
const fs = require('fs'); const PNG = require('pngjs').PNG; const pixelmatch = require('pixelmatch'); test('custom compare test', async ({ page }) => { const element = page.locator('.target-element'); const actual = await element.screenshot(); const expected = await fs.readFile('./tests/screenshots/expected.png'); const img1 = PNG.sync.read(actual); const img2 = PNG.sync.read(expected); const minHeight = Math.min(img1.height, img2.height); // 裁剪到最小高度,去掉多余1px img1.data = img1.data.slice(0, img1.width * minHeight * 4); img2.data = img2.data.slice(0, img2.width * minHeight * 4); const diff = new PNG({ width: img1.width, height: minHeight }); const diffPixels = pixelmatch(img1.data, img2.data, diff.data, img1.width, minHeight, { threshold: 0.1, maxDiffPixels: 10 }); expect(diffPixels).toBeLessThanOrEqual(10); });
需先安装依赖:npm install pngjs pixelmatch --save-dev
仅截取目标元素
避免整页截图的滚动条/底部区域差异,只截取指定元素:
await page.locator('.target-container').toHaveScreenshot({ fullPage: false });
内容的提问来源于stack exchange,提问作者xyarriddi
相关产品推荐
相关产品推荐

