How to Set Up Playwright toHaveScreenshot in CI
toHaveScreenshot compares a live page against a committed baseline named per platform, so baselines must be generated on the same OS the CI job uses.
Add a toHaveScreenshot assertion, generate baselines with --update-snapshots on a runner-matching platform, commit them, then let CI compare on every push.
Steps
- Write a test that calls
await expect(page).toHaveScreenshot(). - Generate baselines on the runner OS (Linux) via
--update-snapshots. - Commit the
*-linux.pngfiles under the test snapshot folder. - Run
npx playwright testin CI; it fails when pixels drift beyond threshold.
Test
tests/home.spec.ts
import { test, expect } from '@playwright/test';
test('homepage renders', async ({ page }) => {
await page.goto('/');
await expect(page).toHaveScreenshot('homepage.png');
});Workflow
.github/workflows/ci.yml
jobs:
visual:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
- run: npx playwright install --with-deps chromium
- run: npx playwright testGotchas
- Baselines carry a platform suffix (e.g.
-linux); baselines made on macOS will not match a Linux runner. - Generate and commit baselines from the same environment CI uses, or run them in Docker to match exactly.
Related guides
How to Get Consistent Visual Rendering With Docker in CIEliminate anti-aliasing and font differences in visual tests by running Playwright inside the official Docker…
How to Approve and Update Visual Baselines in CIUpdate visual baselines safely with a manually triggered workflow that regenerates snapshots and commits them…