Skip to content
Latchkey

How to Mask Dynamic Regions in Visual Tests

Dynamic content like clocks and avatars breaks pixel comparison, so mask those locators to paint them over before the screenshot is diffed.

Pass a mask array of locators to toHaveScreenshot; Playwright overlays a solid box on each so the changing content is excluded from the comparison.

Steps

  • Identify regions that change every load (dates, ads, avatars).
  • Pass those locators in the mask option.
  • Optionally set maskColor for consistency.
  • Regenerate baselines after adding a mask.

Test

dashboard.spec.ts
await expect(page).toHaveScreenshot('dashboard.png', {
  mask: [
    page.locator('.timestamp'),
    page.locator('[data-testid="avatar"]'),
  ],
  maskColor: '#FF00FF',
});

Gotchas

  • A mask covers a rectangle; a moving element may still shift layout under the box.
  • Adding or moving a mask changes pixels, so update baselines afterward.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →