Visual regression testing compares a new screenshot of a page with an approved one, called the baseline, and fails when too many pixels differ. The hard part is the tolerance. In our test, the common settings let a wrong price through, while strict settings caught every change without a single false alarm, once we had removed the things that made the page change on its own.
This guide gives working code, the results for seven deliberately broken builds of one page, and the order to fix flaky pixels in. A flaky pixel is one that differs between two runs even though nobody changed the code.
The smallest working test
Playwright's test runner has this built in. toHaveScreenshot takes the capture, compares it with the stored baseline and writes the expected, actual and diff images when it fails. Here is the config we used:
const { defineConfig } = require('@playwright/test');
module.exports = defineConfig({
testDir: './tests',
reporter: 'line',
use: { baseURL: 'http://localhost:4599', viewport: { width: 1280, height: 520 } },
expect: { toHaveScreenshot: { timeout: 5000 } },
});
And this is the test we ended up with. The reasons for each line come from the measurements below:
const { test, expect } = require('@playwright/test');
test('pricing page', async ({ page }) => {
await page.clock.setFixedTime(new Date('2026-10-31T09:00:00Z'));
await page.goto(`/?build=${process.env.BUILD || 'base'}`);
await expect(page.locator('.card', { hasText: 'Pro' }).locator('.price')).toHaveText('$29/mo');
await expect(page.getByRole('link', { name: 'Choose Pro' })).toBeVisible();
await expect(page).toHaveScreenshot('pricing.png', { threshold: 0.02, maxDiffPixels: 0 });
});
The build parameter belongs to our test page, which serves each broken version at its own address. In your project, the page under test is simply whatever the branch builds.
Create the baseline with npx playwright test --update-snapshots, then commit the image it writes. Ours was named pricing-darwin.png: the platform is part of the name because, as Playwright's docs say, rendering differs across browsers and platforms, so each needs its own baseline.
How we tested
We wrote a 1280×520 pricing page, 665,600 pixels in all, with three plan cards, a spinner animation and a clock that updates every 50 ms. Then we made seven builds, each with one change, and compared each one with the baseline.
Two settings control the tolerance, and they do different jobs:
threshold decides whether one pixel counts as different, from 0 (strict) to 1 (lax). Playwright's default is 0.2.
maxDiffPixels and maxDiffPixelRatio decide how many differing pixels are allowed before the test fails.
Which settings miss which bugs
Each cell shows the number of differing pixels when the test failed, or "passed" when the bug got through. The last two columns set only threshold, and the maxDiff columns use the default threshold.
| Change in the new build | Default | maxDiffPixels: 100 | maxDiffPixelRatio: 0.01 | threshold: 0.05 | threshold: 0.02 |
|---|
Button colour #2563eb to #2a6af0 | passed | passed | passed | passed | 15,361 |
Body text #374151 to #4b5563 | passed | passed | passed | 2,965 | 3,283 |
| Card borders removed | passed | passed | passed | 3,884 | 3,884 |
Price $29 to $39 | 90 | passed | passed | 90 | 90 |
| 14 px check icon hidden | 36 | passed | passed | 36 | 36 |
| Layout pushed down 1 px | 4,854 | 4,854 | passed | 14,164 | 14,718 |
| Call-to-action button removed | 15,552 | 15,552 | 15,552 | 17,791 | 17,851 |
Three things stand out.
Pixel counts don't measure importance. A wrong price changed 90 pixels. A harmless 1 px shift changed 4,854, about 54 times as many. Any allowance big enough to absorb the shift also absorbs the wrong price, as the maxDiffPixelRatio: 0.01 column shows: on this page 1% is 6,656 pixels, and only the removed button exceeded it.

The image above is the 1 px shift, drawn by pixelmatch at threshold 0.1. Nearly every piece of text lights up, so one small layout change hides anything else that changed in the same commit. Red marks differing pixels and yellow marks pixels pixelmatch judged to be anti-aliasing, the blended edge pixels that smooth text and curves, which it leaves out of the count by default.
The default threshold is blind to subtle colour drift. Three of our seven changes passed at 0.2, including the removal of every card border. A colour shift affects a lot of pixels, but each one by too little to count, so no pixel allowance helps. Only a lower threshold caught them, and the button colour needed 0.02.
The ratio in the error message is rounded. Playwright reported the 90-pixel price change as "90 pixels (ratio 0.01 of all image pixels)". The real ratio is 0.00014. Use the pixel count when choosing a limit.
Remove the flakiness instead of tolerating it
Tolerance is usually added because a test was flaky. The better fix is to remove the cause. We captured the unchanged page 20 times, each in a fresh browser context, and compared captures 2 to 20 with the first using pixelmatch at threshold 0.1:
| Setup | Runs that differed | Differing pixels |
|---|
Plain page.screenshot() | 19 of 19 | 90 to 187 |
animations: 'disabled' | 19 of 19 | 31 to 417 |
| Animations disabled and clock element masked | 0 of 19 | 0 |
| Animations disabled and time fixed | 0 of 19 | 0 |
With animations disabled, the second row is the clock alone, and it reached 417 pixels, more than four times the wrong-price diff. A tolerance wide enough to survive the clock can't see that bug.
Work through the causes in this order:
- Fix the time.
page.clock.setFixedTime sets what Date.now() and new Date() return, and timers keep running. Call it before goto.
- Stop animations.
toHaveScreenshot already does this: its animations option defaults to "disabled", and caret defaults to "hide".
- Mask what you can't fix. The
mask option covers given elements with a coloured box (pink by default), which suits ads and third-party widgets. The stylePath option applies a stylesheet during capture, if you would rather hide them.
- Use the same environment every time. See the next section.
toHaveScreenshot also helps you find unstable pages. It waits until two consecutive captures match, so on our page with the live clock it never got as far as a comparison:
Error: expect(page).toHaveScreenshot(expected) failed
Timeout: 5000ms
Failed to take two consecutive stable screenshots.
If you see this message, something on the page is still changing. Find it and freeze it, rather than raising the timeout. Once we had fixed the time, the test in this guide passed 20 times out of 20 at threshold: 0.02 with maxDiffPixels: 0 (run with --repeat-each=20). Fifty captures compared with pixelmatch at threshold 0 were also identical.
Never compare across environments
The biggest source of noise we measured was the machine. We rendered the same page on the Mac and in a Debian 12 container, with the clock and spinner hidden, and compared them with pixelmatch:

| Compared with the Mac baseline | Threshold 0 | Threshold 0.1 | Threshold 0.2 |
|---|
| Same browser, run again | 0 | 0 | 0 |
Playwright's channel: 'chromium' (new headless mode) | 2,374 | 0 | 0 |
| System Chrome 156 | 2,374 | 0 | 0 |
| Debian 12 container, Chromium 155 | 15,113 | 13,443 | 11,982 |
The Linux row combines several differences: the operating system, a Chromium one version older and a missing font. The page asks for Arial, the container doesn't have it, and fc-match showed it falling back to DejaVu Sans. So treat that row as a typical bad case rather than a pure measure of the operating system. At the default threshold it is still about 133 times the wrong-price diff, and no sensible tolerance could bridge it.
Inside the container, the results were as clean as on the Mac: two captures of the same build had 0 differing pixels at threshold 0, and the price change showed up as 115 pixels.
The other rows matter when you upgrade. Playwright runs the older headless shell by default, and channel: 'chromium' switches to Chrome's new headless mode. The two are separate implementations, and Playwright's own advice when moving between them is that "Screenshots are different. We recommend to update all screenshot expectations." On our page the difference was small enough that a threshold of 0.1 hid it, but it would fail a test run at 0.
The practical rules:
- Create baselines where the tests run. If that's CI on Linux, generate them there, not on a laptop. Playwright's docs give the same advice.
- Pin the browser version and install the fonts your pages use, then rebuild the baselines on purpose when you upgrade.
- Keep browser upgrades in their own commit, so a wall of red can't hide a real change.
Diffing without a test runner
For a monitoring script or another language's test suite, you can compare two PNG files directly. This is the script we used, with pixelmatch and pngjs:
import { readFileSync, writeFileSync } from 'node:fs';
import { PNG } from 'pngjs';
import pixelmatch from 'pixelmatch';
const [beforePath, afterPath, diffPath, threshold = '0.1'] = process.argv.slice(2);
const before = PNG.sync.read(readFileSync(beforePath));
const after = PNG.sync.read(readFileSync(afterPath));
if (before.width !== after.width || before.height !== after.height) {
console.error(`Sizes differ: ${before.width}x${before.height} vs ${after.width}x${after.height}`);
process.exit(2);
}
const { width, height } = before;
const diff = new PNG({ width, height });
const count = pixelmatch(before.data, after.data, diff.data, width, height, { threshold: Number(threshold) });
writeFileSync(diffPath, PNG.sync.write(diff));
console.log(`${count} of ${width * height} pixels differ (${(100 * count / (width * height)).toFixed(3)}%)`);
process.exit(count ? 1 : 0);
$ node diff.mjs shots/base.png shots/price-digit.png shots/diff-price.png
90 of 665600 pixels differ (0.014%)
Check the sizes first, as this script does: pixelmatch needs two images of the same dimensions, and a full-page capture changes height whenever the content does.
Don't copy threshold values between the two tools. pixelmatch's default is 0.1 and Playwright's is 0.2. The current pixelmatch README describes its comparison in the OKLab colour space, while Playwright's docs describe threshold in YIQ, and the counts differ. For the 1 px shift at threshold 0.1, pixelmatch 8 reported 6,388 pixels and Playwright 6,310. Calibrate in the tool you actually run.
What to use
- Freeze first, then go strict. On our page, fixing the time made a threshold of 0.02 with no pixel allowance fully stable, and that combination caught all seven changes. Start there, and loosen a setting only for a cause you have identified.
- Don't rely on pixels for facts. Prices, totals and required buttons deserve ordinary assertions. In our test the price change failed with
Expected: "$29/mo" and Received: "$39/mo", which tells you far more than "90 pixels are different", and it keeps working if someone later loosens the visual settings.
- Have a person read every baseline update.
--update-snapshots accepts whatever the page looks like now, bugs included. Review the changed images in the pull request, as you would review code.
- Test your own pages. Ours is small and simple, with no third-party content. Pages with ads, video or personalised content will need masking, and may not stay stable at 0.02. Run the page against itself 20 times before you trust any setting, which takes seconds and tells you how much noise you really have.