Visual regression tests need a reference image before they can flag layout changes. In Playwright Test, that reference is a snapshot file created by a toHaveScreenshot() assertion and stored beside the test file.
The first snapshot update run writes the expected PNG into a *-snapshots directory. Later test runs take a fresh screenshot from the same assertion and compare it with that baseline.
Browser rendering changes with operating system, browser channel, fonts, viewport size, and headless mode. Generate baselines in the same environment that will run the comparison, and use the snapshot update flag only when the current page rendering is ready to become the new expected image.
import { expect, test } from '@playwright/test';
test('home page visual baseline', async ({ page }) => {
await page.setContent(`
<main style="font-family: system-ui, sans-serif; padding: 48px;">
<h1>Playwright fixture ready</h1>
<p>Visual baseline target</p>
</main>
`);
await expect(page.getByRole('heading', { name: 'Playwright fixture ready' })).toBeVisible();
await expect(page).toHaveScreenshot('home-page.png', {
maxDiffPixels: 100
});
});
Replace page.setContent() with page.goto() and normal setup steps when the baseline should come from an application route. Keep volatile timestamps, random IDs, animations, and third-party widgets out of the captured area or mask them before accepting the baseline.
$ npx playwright test tests/visual.spec.ts --project=chromium --update-snapshots Running 1 test using 1 worker A snapshot doesn't exist at tests/visual.spec.ts-snapshots/home-page-chromium-linux.png, writing actual. ✓ 1 [chromium] › tests/visual.spec.ts:3:5 › home page visual baseline (391ms) 1 passed (869ms)
--update-snapshots accepts the current rendering as the reference image. Review the page state before running it against an existing baseline, because changed snapshots can also be overwritten.
$ ls -lh tests/visual.spec.ts-snapshots total 16K -rw-r--r-- 1 user user 13K Jul 7 02:20 home-page-chromium-linux.png
Playwright adds the project or browser and platform suffix to the requested snapshot name. A named home-page.png assertion can become home-page-chromium-linux.png under the test file's snapshot directory.
$ npx playwright test tests/visual.spec.ts --project=chromium Running 1 test using 1 worker ✓ 1 [chromium] › tests/visual.spec.ts:3:5 › home page visual baseline (194ms) 1 passed (809ms)