Playwright Visual Options
Playwright Visual Comparison Options
Visual comparison options are settings you pass to toHaveScreenshot() to make screenshot tests more reliable, so they do not fail for no real reason.
They build on the screenshot tests from Visual Comparisons.
You can allow small differences, hide parts of the page that change, and keep one baseline per system.
Start with the most common problem: a few pixels that differ for no real reason.
Allow Small Differences
By default, one pixel with a clearly different color is enough to fail the test.
Very small color changes, below the threshold option (0.2 by default), do not count.
If tiny differences are fine for you, set a limit:
Example
await expect(page).toHaveScreenshot({ maxDiffPixels: 100 });
await expect(page).toHaveScreenshot({ maxDiffPixelRatio: 0.01 });
maxDiffPixelsallows up to that number of different pixelsmaxDiffPixelRatioallows a part of all pixels, as a number from 0 to 1 (0.01 is 1%)
To use a limit for every screenshot test, set it in the config:
Example
playwright.config.js
// @ts-check
import { defineConfig } from '@playwright/test';
export default defineConfig({
expect: {
toHaveScreenshot: { maxDiffPixels: 100 },
},
});
Hide Parts That Change
Some parts of a page are different on every visit: dates, prices, ads, user names.
The mask option covers them with a pink box before the comparison:
Example
test('hide parts that change', async ({ page }) => {
await page.goto('shop.html');
await expect(page.getByTestId('product')).toHaveCount(5);
await expect(page).toHaveScreenshot({
mask: [page.getByTestId('product')],
});
});
Every element the locators match is covered, so their content no longer affects the result.
Wait for the page to be ready first (here: all 5 products loaded), so the screenshot is taken at the same moment every time.
You can change the box color with maskColor.
Baselines Depend on OS and Browser
Look at a baseline file name from Visual Comparisons: todo-page-looks-right-1-chromium-win32.png.
It contains the project name (chromium) and the operating system (win32).
Browsers and operating systems draw fonts and edges a little differently.
A screenshot from Windows will not match one from Linux pixel for pixel, so Playwright keeps a separate baseline for each.
This matters when your tests run in CI, which is usually Linux:
- Baselines made on your Windows or Mac computer end with
-win32or-darwin, and CI looks for-linux - The best fix is to make and update baselines on the same kind of system as CI, for example in the Playwright Docker image (a ready-made Linux system with Playwright and its browsers installed)
Tip: Write only a few visual tests, and keep each one small.
A locator screenshot of one part of the page is more stable than a full-page screenshot, and the failure tells you exactly what changed.