How to create Playwright visual baselines

Visual regression tests compare a newly rendered page with a trusted reference image. Playwright Test creates that reference when a toHaveScreenshot() assertion encounters a missing snapshot.

Each baseline belongs to its test file and rendering environment. A named screenshot is stored in a sibling *-snapshots directory, with browser or project and platform details added to the generated filename.

Fonts, browser builds, operating systems, viewport settings, and animation state can change pixels without an application defect. Generate and verify the baseline in the same runtime used for later comparisons, then keep the PNG with the test source.

Steps to create Playwright visual baselines:

  1. Start tests/visual.spec.ts with the imports and stable page setup.
    tests/visual.spec.ts
    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>
      `);

    For an application route, page.goto() can replace page.setContent() after volatile data and animations are controlled.

  2. Append the named screenshot assertion and closing brace to tests/visual.spec.ts.
    tests/visual.spec.ts
      await expect(page).toHaveScreenshot('home-page.png');
    });
  3. Create the missing baseline by running the completed visual test in missing-snapshot mode.
    $ npx playwright test tests/visual.spec.ts --update-snapshots=missing
    Running 1 test using 1 worker
    
    Error: A snapshot doesn't exist at tests/visual.spec.ts-snapshots/home-page-linux.png, writing actual.
    ##### snipped #####
    1 failed

    The first creation run writes the missing PNG and reports a failed comparison because no golden file existed at the start. The --update-snapshots=missing mode does not replace a changed existing baseline.

  4. Inspect the snapshot directory for the generated baseline file.
    $ ls -lh tests/visual.spec.ts-snapshots
    total 16K
    -rw-r--r-- 1 user user 13K Jul 16 23:38 home-page-linux.png

    The home-page.png assertion becomes home-page-linux.png in this default Chromium run; configured project names and other platforms produce different suffixes.

  5. Run the visual test without snapshot updates to compare the current page with the baseline.
    $ npx playwright test tests/visual.spec.ts
    
    Running 1 test using 1 worker
    
      ✓  1 tests/visual.spec.ts:3:5 › home page visual baseline
    
      1 passed