Masking Dynamic Content in Visual Tests

Masking Dynamic Content in Visual Tests

Content that changes per run can be handled three ways: stub, mask, or exclude. The preference order, the mask ledger, and why a masked region is an untested region.

Content that legitimately changes per run can be handled three ways, in a fixed preference order: stub what you own so it renders deterministically and stays under test, mask what you cannot stub so the pixels are excluded but the surrounding layout stays checked, and exclude the surface when masking would hollow the test out. Every mask is a standing declaration that a region is unverified, so masks earn review scrutiny. The masked element's box still participates in comparison, which is why masking guards the layout perimeter even when it blinds the interior.

Three responses to content that changes

A visual test compares this run's capture against a stored baseline. Any region that renders differently between runs for legitimate reasons — a signed-in user's name, today's date, a live feed of prices, an embedded third-party widget — will fail the comparison unless something is done about it. This article works with three responses, and they are not equivalent. Playwright's screenshot assertion also offers a stylePath stylesheet for hiding or restyling elements and pixel-difference tolerances such as maxDiffPixels (as of November 2026); neither is covered here.

Stub. Replace the source of the variation so the rendered output is deterministic: seeded fixtures instead of live records, intercepted network responses instead of a real API, a frozen clock instead of the wall clock. The content stays visible in the capture and stays under comparison, which means a regression inside it is still caught.

Mask. Paint over the region at capture time so its pixels are excluded from the diff. The layout around the region stays tested; the appearance inside it does not. This is the response for content whose source you genuinely cannot control.

Exclude. Crop the capture, or drop the surface from the visual suite entirely, when neither stubbing nor masking leaves a meaningful assertion behind — when a surface is so dominated by uncontrollable content that what remains under comparison is not worth a standing test.

The preference order is structural, not stylistic. Stub what you own, because owned content should stay under test by default and stubbing is the only one of these three responses that keeps it there. Mask what you genuinely cannot stub. Exclude only when masking would remove so much of the surface that the remaining assertion is not worth running. Working down that order rather than reaching straight for the mask is what keeps a visual suite from slowly turning into a grid of solid boxes.

Stubbing: determinism at the source

Start with network interception: the test replaces live API responses with fixtures, which makes the rendered data both stable and representative — as long as the fixture content is chosen deliberately, because whatever the fixture contains becomes the permanently tested state.

ts
// Playwright network interception (as of November 2026; option names:
// https://playwright.dev/docs/api/class-route#route-fulfill ).
// A relative fixture path resolves from the current working directory,
// and page.goto('/dashboard') assumes a baseURL in the test configuration.
await page.route('**/api/orders*', (route) =>
  route.fulfill({ path: 'fixtures/orders.dense.json' }),
)
await page.goto('/dashboard')
await expect(page).toHaveScreenshot('dashboard.png')

Choose the fixture to exercise the layout you actually worry about: realistic string lengths, a list long enough to wrap or scroll, an empty collection, a value that overflows its container, a name with characters that stress the font stack. A fixture full of tidy three-word titles tests a state that may not match what your users see, and it will pass green while the production layout breaks on a customer whose order history is four screens long.

Dates, relative times, and number formats are handled by freezing the clock and pinning the locale. The environment-level mechanics of that freeze — how the clock is patched, how the timezone is fixed — belong to the determinism concern. The point here is narrower: once the clock is frozen, a rendered timestamp is deterministic content, and deterministic content should stay visible in the capture rather than being masked. Masking a date you have already made deterministic throws away coverage you had for free.

Stubbed content keeps its pixels under test. That is the decisive advantage over masking, and the reason owned content should be masked only as an exception: masking a value you control trades away a real assertion for a solid box, and gets nothing back except a slightly shorter test setup.

Masking: exclusion with a perimeter

When the varying content is genuinely not yours to make deterministic, masking excludes it at capture time.

ts
// mask overlays the listed elements with a solid box before the diff
// (Playwright toHaveScreenshot)
await expect(page).toHaveScreenshot('profile.png', {
  mask: [page.locator('[data-testid="avatar"]'), page.locator('[data-testid="last-seen"]')],
})

The mask hides the interior, but the element's box still participates in layout. Its size and its position are still in the capture, so a regression that moves the masked region, resizes it, or shifts everything around it is still caught. Masking blinds the content, not the perimeter — the layout relationship between the masked element and its neighbors stays under full-strength comparison.

Good mask targets share a shape: their variation is legitimate, and their interior appearance is not the thing being asserted. User avatars and user-generated media. Live metrics and counters that move every few seconds. Timestamps painted by a third-party script. A relative-time string that no frozen clock reaches because it is rendered client-side by code you do not own. In each case, what you care about is that the element is the right size and in the right place, not what it contains this second.

Every mask belongs in a ledger, at least mentally. A mask is a standing statement that this region's appearance is unverified for as long as the mask exists. That makes masks worth reviewing with the same care as a deleted assertion, because functionally that is what a mask is: a small, permanent reduction in what the suite checks. A pull request that adds three masks has removed three regions from coverage, and it should be read that way.

Masks also rot. Selectors drift as markup changes, and in Playwright a mask locator that no longer matches anything is skipped rather than reported as an error (source, not documented, v1.65; as of November 2026 — check your version), so the mask silently stops covering the flaky content. That is the bad case, because the test then starts failing intermittently with no obvious cause and someone burns an afternoon before realizing a mask fell off. Pin masks to stable test attributes rather than to structural selectors or class names that a refactor will move.

Third-party surfaces

Embeds, ad slots, chat widgets, map tiles, and consent banners repaint on their own schedule and can run their own experiments. Their pixels are not yours to assert against, and a fixture for them only freezes a copy of someone else's output: the real embed keeps changing outside your build.

The clean options are all perimeter-preserving. Block the third-party request entirely and assert against what the page renders in its place, such as a reserved empty slot, which still catches layout regressions in the space the embed occupies. Substitute a placeholder element of identical dimensions, so the surrounding layout is tested against the size the embed will actually take. Or mask the region. Each option keeps the surrounding page under full-strength comparison; one difference between them is how much you trust the reserved space to match production.

ts
// block a third-party origin so its request fails; the slot then shows
// whatever the page renders without the embed
await page.route('https://widget.example.com/**', (route) => route.abort())

Consent and cookie banners need special handling because they are overlays: a banner spanning the viewport invalidates every assertion beneath it, since the comparison is now looking at the banner instead of the page. Dismiss or suppress the banner deterministically before capture — set the consent cookie in test setup, or route the banner script to an empty response — so the page underneath is actually visible to the comparison rather than hidden behind a modal that renders differently depending on any experiment the banner vendor is running.

What masking cannot fix

A capture that is mostly mask is a test that mostly is not testing. When masks come to dominate a surface, adding one more is the wrong move. The honest response is to restructure: stub deeper so the content becomes real and deterministic again, or drop to a more isolated level — a component render — where the uncontrollable content is simply not present.

Masking also does not stabilize the environment. Font rendering noise, animation flake, and layout jitter from unsettled web fonts are determinism problems with determinism fixes. Masking those regions away hides genuine instability behind a box and lets it resurface somewhere the mask does not reach.

The review question for every new mask is the same one, asked plainly: what regression class did this just make invisible, and is accepting that blind spot the right call for this surface. A mask added without that question answered is coverage quietly leaking out of the suite, one masked rectangle at a time.

Project Inquiry