Prompt
Playwright screenshot diff dynamic content
Latest observation
If your Playwright screenshot diff is failing because of dynamic content (timestamps, ads, animations, random IDs, carousels, spinners, etc.), the usual fix is to stabilize the page before taking the screenshot or mask/ignore the unstable parts.
Common approaches
1) Wait until the page is stable
Use network idle, disable animations, and wait for specific UI state.
await page.goto(url, { waitUntil: 'networkidle' });
await page.evaluate(() => document.fonts?.ready);
If content keeps changing, wait for a known selector:
await expect(page.locator('[data-testid="loaded"]')).toBeVisible();
2) Disable animations and transitions
Playwright supports this directly:
await expect(page).toHaveScreenshot({
animations: 'disabled',
});
This helps with CSS transitions, hover effects, and many loading animations.
3) Mask dynamic elements
If only a few parts are unstable, hide them from the screenshot:
await expect(page).toHaveScreenshot({
mask: [
page.locator('.timestamp'),
page.locator('.live-counter'),
page.locator('.ad-banner'),
],
});
You can also use CSS to hide them before screenshot:
await page.addStyleTag({
content: `
.timestamp, .live-counter, .ad-banner {
visibility: hidden !important;
}
`,
});
4) Replace dynamic values with fixed ones
If the page renders text like current time or random data, inject deterministic values in test mode.
Example:
await page.addInitScript(() => {
const fixedNow = 1700000000000;
Date.now = () => fixedNow;
new Date = () => new Date(fixedNow);
});
Or stub API responses:
await page.route('**/api/time', route =>
route.fulfill({
json: { time: '2024-01-01T00:00:00Z' },
})
);
5) Freeze media and video
If videos or GIFs are causing diffs, hide them:
await page.addStyleTag({
content: `
video, img[src*=".gif"] {
visibility: hidden !important;
}
`,
});
6) Use stylePath or test-specific CSS
If you have a reusable CSS file for test-only overrides:
await expect(page).toHaveScreenshot({
animations: 'disabled',
stylePath: 'tests/screenshot-stable.css',
});
Example: stable screenshot test
test('homepage matches screenshot', async ({ page }) => {
await page.goto('https://example.com', { waitUntil: 'networkidle' });
await page.addStyleTag({
content: `
.clock, .ticker, .ads { visibility: hidden !important; }
`,
});
await expect(page).toHaveScreenshot({
animations: 'disabled',
fullPage: true,
});
});
Best practices
- Prefer mocking data over masking when possible.
- Hide only the minimal unstable areas.
- Use consistent viewport, timezone, locale, and device scale factor.
- Run screenshots in a consistent environment (CI vs local can differ).
test.use({
viewport: { width: 1280, height: 720 },
timezoneId: 'UTC',
locale: 'en-US',
colorScheme: 'light',
});
If you want, I can also give you:
- a Playwright helper utility for stable screenshots, or
- a debug checklist for flaky screenshot diffs.
Brands