Playwright · Test automation · Frontend · CI/CD

Visual Regression Testing with Playwright: Making toHaveScreenshot Stable

Visual regression testing with Playwright toHaveScreenshot: thresholds, masking dynamic content, font and animation issues, consistent snapshots in Docker and a CI workflow.

Sander Yazıcıoğlu Published: 3 min read Türkçe oku

Visual Regression Testing with Playwright: Making toHaveScreenshot Stable

A functional E2E test answers "did clicking the button create the order?". It does not notice the button sliding off screen, a CSS change breaking a card on another page, or text becoming unreadable after a theme switch. During Angular upgrades and the theme work on this site, those "nobody tested that" breakages were the ones I ran into most. Visual regression testing fills exactly that gap: it compares a screenshot of the page pixel by pixel against an approved baseline.

Playwright does this without any extra service, using toHaveScreenshot. Writing the test is easy; keeping it stable is the hard part. That is what this post covers.

The first test

import { test, expect } from '@playwright/test';

test('home page', async ({ page }) => {
  await page.goto('/');
  await expect(page).toHaveScreenshot('home.png', { fullPage: true });
});

On the first run there is no baseline: Playwright saves the image and marks the test as failed. To create baselines deliberately:

npx playwright test --update-snapshots

Later runs compare the new image against the baseline. When they differ, the report shows expected, actual and diff images side by side.

Understanding the thresholds

Two different settings are often confused:

SettingWhat it measuresWhen to use it
thresholdHow different a single pixel's colour must be to count as changed (0–1, default 0.2)Small colour shifts from anti-aliasing
maxDiffPixelsHow many pixels may differSmall, known variations
maxDiffPixelRatioShare of differing pixels in the whole image (0–1)Large, full-page screenshots

It is tempting to "fix" a flaky test by raising the threshold, but a 5% ratio can hide an entire missing button. Find the source of the flakiness first and tune the threshold last.

Four sources of flakiness

1. Dynamic content

Clocks, dates, random recommendations and ad slots change on every run. Mask them:

await expect(page).toHaveScreenshot('dashboard.png', {
  mask: [page.locator('[data-testid="clock"]'), page.locator('.avatar')],
});

Even better, pin the data: route API responses to a fixed JSON with page.route, and freeze time with page.clock.setFixedTime(...).

2. Animations

By default toHaveScreenshot stops CSS animations and transitions (animations: 'disabled'). Animations driven by JavaScript (canvas, requestAnimationFrame) are not affected. For effects like the matrix rain on this site, switching them off with a flag in the test environment is the cleanest option.

3. Fonts

A screenshot taken before the web font loads is drawn with the fallback font, and everything shifts by a few pixels.

await page.goto('/');
await page.evaluate(() => document.fonts.ready);

A good font loading strategy reduces this problem; details in the web font performance post.

4. Operating system differences

The same page renders differently on macOS and Linux. That is why Playwright adds the browser and platform to the baseline name: home-chromium-linux.png. A baseline generated on a developer's Mac will never match in CI. The fix is to generate baselines and run tests in the same Docker image:

docker run --rm -v $(pwd):/work -w /work \
  mcr.microsoft.com/playwright:v1.49.0-jammy \
  npx playwright test --update-snapshots

Keep the image version identical to the Playwright version in package.json.

How much should you test visually?

Screenshotting every state of every page produces a pile of baselines nobody can maintain. My rule of thumb:

  • Design system components: buttons, form fields, cards; small, component-level images for each variant.
  • Critical pages: home, checkout, login; full page with dynamic areas masked.
  • Themes and languages: light/dark themes and both language versions of the same page. Turkish text tends to be longer than English, so overflow bugs usually show up here.
  • Mobile layout: at least one critical page with a profile such as devices['iPhone 13'].

Capturing a single element is more stable than a full page:

await expect(page.getByRole('navigation')).toHaveScreenshot('nav.png');

CI workflow

  1. On a pull request, tests run inside the Docker image.
  2. If there is a diff, the HTML report is uploaded as an artifact and the reviewer looks at the diff image.
  3. If the change is intentional, the developer updates the baseline with the same image and commits it to the PR.

That way baseline updates become part of code review. For the rest of the pipeline, see the GitHub Actions frontend CI post.

Conclusion

Visual regression tests catch breakages that functional tests cannot see, but they only add value when they are stable. Pin dynamic data, wait for fonts, generate baselines in one environment and tune thresholds last. If you are still choosing a tool, read the Playwright vs Cypress vs Selenium comparison.

All articles →