Sub topic 15
Automating screenshot comparisons
This chapter assumes you can read and write basic JavaScript or TypeScript and have Node.js installed. You should also know the responsive widths your project uses, from the earlier chapter on breakpoints. Playwright is the example tool. Other tools (Cypress plugins, BackstopJS, Percy, Chromatic) follow the same model.
What automation does and does not check
An automated screenshot test takes a picture of a page and compares it with a stored picture called a baseline. If too many pixels differ, the test fails.
The baseline is usually a screenshot of your own earlier build. It is not the design file. A screenshot test therefore answers "did anything change since the last approved version?" and does not answer "does this match the design?"
The two checks work together:
- You do the manual pass from the earlier chapters: DevTools measurements, overlays, contrast, states.
- When the page matches the design, you save screenshots of it as baselines.
- From then on, the automated test catches regressions: a changed padding, a broken breakpoint, a font that failed to load.
A first test
This test captures the home page at three widths and compares each with a baseline. The widths are a phone, a tablet and a desktop.
import { test, expect } from '@playwright/test';
const widths = [375, 768, 1280];
for (const width of widths) {
test(`home page matches baseline at ${width}px`, async ({ page }) => {
await page.setViewportSize({ width, height: 900 });
await page.goto('https://example.com/');
await expect(page).toHaveScreenshot(`home-${width}.png`, {
fullPage: true,
maxDiffPixelRatio: 0.01,
});
});
}Install Playwright with npm init playwright@latest, then run npx playwright test.
The first run fails on purpose, because no baseline exists yet. Playwright writes the images into a *-snapshots folder next to the test file and tells you so. The second run compares against them.
When a failure is a change you want, regenerate the baselines:
npx playwright test --update-snapshotsRead the diff before you do this. Updating without looking turns the test into a rubber stamp.
When a test fails, Playwright saves three images in the test-results folder: the expected image, the actual image and a diff image with the changed pixels highlighted. The HTML report (npx playwright show-report) shows them side by side, with a slider.
Why screenshots flake, and how to stop it
A flaky screenshot test fails without a real change. Teams that get too many false failures stop reading the results, so removing flakiness matters more than anything else in this chapter. Most flakiness comes from five sources.
| Source | Symptom | Fix |
|---|---|---|
| Animations and transitions | Element caught mid-fade | `animations: 'disabled'` |
| Web fonts not loaded yet | Fallback font in some runs | Wait for `document.fonts.ready` |
| Dynamic content | Dates, ads, avatars, counters change | `mask` those elements or use fixed test data |
| Text caret blinking | Tiny diff in focused inputs | `caret: 'hide'` (the default) |
| Different operating system | Every run differs slightly in text | Run baselines in the same environment as CI |
The next test applies these fixes.
import { test, expect } from '@playwright/test';
test('pricing page is stable at 375px', async ({ page }) => {
await page.setViewportSize({ width: 375, height: 900 });
await page.goto('https://example.com/pricing');
await page.evaluate(() => document.fonts.ready);
await expect(page).toHaveScreenshot('pricing-375.png', {
fullPage: true,
animations: 'disabled',
mask: [page.locator('time'), page.locator('[data-testid="ad-slot"]')],
});
});mask paints a solid colored box over each matching element before comparing, so changing content inside it does not matter. The box is part of the screenshot, so the element's size and position are still checked.
You can set shared options once in playwright.config.ts instead of repeating them:
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
expect: {
toHaveScreenshot: {
maxDiffPixelRatio: 0.01,
animations: 'disabled',
},
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
],
});With two projects, Playwright stores a separate baseline per browser. That gives you a cheap cross-browser check, but it doubles the number of images you review.
Choosing tolerances
Playwright has two settings that control how strict the comparison is. They are easy to confuse.
thresholdis between 0 and 1 and sets how different two pixels must be, in color, before they count as changed. The default is 0.2.maxDiffPixelRatioandmaxDiffPixelsset how many changed pixels you accept before the test fails.
A ratio of 0.01 means that 1% of the pixels may differ. On a long full-page screenshot, 1% can hide a lot. A 1280 by 6000 page has 7.68 million pixels, so 1% is about 76,800 pixels, enough for a whole button to change color unnoticed.
Two habits keep this under control:
- Prefer element screenshots (
expect(locator).toHaveScreenshot()) for components. A small image has a small tolerance in absolute terms. - Start strict, with a ratio of 0 or very close to it, in a controlled environment. Loosen only when you can name the reason.
What to capture
Screenshots cost review time, so choose them deliberately.
- Breakpoints: one screenshot at the width inside each range from your responsive chapter, plus the widths just either side of each boundary if the layout has broken there before.
- States: hover, focus and error states are worth a test each, because they are easy to break and rarely seen. Trigger them first, for example
await page.getByRole('button').hover(), then take the screenshot. - Edge cases: a page rendered with long names, an empty list or a missing image. Feed it fixed test data so the result is repeatable.
- Not worth it: pages dominated by live data, third-party widgets, and anything you would mask almost entirely.
Common errors
- Baselines committed from a developer's machine. They fail in CI on every run. Generate them in CI or in the same container.
- Updating all baselines to turn the build green. This hides real regressions. Review each diff image, and review baseline changes in the pull request the same way as code.
- One giant full-page screenshot per page. A single failure gives you a huge diff that is hard to read. Split by section or component.
- Testing against a live site. A change in production data breaks the test. Use a local or staging build with fixed data.
- Treating a pass as design approval. A passing test only says the page matches a previous screenshot. If the first baseline was wrong, the test protects the wrong thing.
Exercises
Exercise
A teammate generates baselines on macOS and commits them. The CI job runs on Linux and every screenshot test fails by a small amount, mostly around text. The pages did not change. What is the cause, and what do you do?
Show answer
Text rendering and anti-aliasing differ between operating systems, and Playwright keeps separate baselines per platform (names end in -darwin or -linux). Here the Linux job has no matching baseline, or the comparison is against images made elsewhere. Generate the baselines in the CI environment, or in a Docker image that matches it, commit them, and run the tests there from then on.
Exercise
A page has 1280 by 5000 pixels and you set maxDiffPixelRatio: 0.02. Roughly how many pixels can differ before the test fails, and why might that be a problem?
Show answer
The page has 6,400,000 pixels, so 2% is 128,000 pixels. That is large enough for a whole banner or button to change without failing the test. Use a much smaller ratio, or take element-level screenshots so that the same ratio allows far fewer changed pixels.