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
maskoption. - Optionally set
maskColorfor 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
How to Disable Animations for Visual TestsFreeze CSS animations and transitions before capturing screenshots with Playwright animations: disabled, so m…
How to Fix Flaky Visual Tests by Freezing Time and RandomnessStabilize flaky visual tests by freezing the clock and seeding randomness with Playwright clock and Math.rand…