Playwright Visual Regression Testing in CI Setup
This guide explains how to set up Playwright visual regression testing in a CI pipeline, covering the tools, configuration, and common pitfalls. You’ll learn how to capture screenshots, compare them against baselines, and integrate the tests into GitHub Actions or similar CI systems.
What Is Visual Regression Testing?
Visual regression testing (also called visual snapshot testing) checks that your UI looks the same after code changes. It works by taking a screenshot of a page or component, storing it as a baseline image, and then comparing future screenshots against that baseline. If pixels differ beyond a set threshold, the test fails, alerting you to unintended visual changes.
Playwright is a browser automation library that can take screenshots and compare them. It supports Chromium, Firefox, and WebKit, and can run tests in parallel across multiple browsers. For visual regression, you typically use Playwright’s built-in toHaveScreenshot() assertion, which captures and compares images automatically.
Why Run Visual Tests in CI?
Running visual tests locally is useful, but CI integration is what makes them valuable. In CI, tests run on a clean environment with consistent browser versions and screen sizes, so you catch visual bugs before they reach production. Without CI, developers might skip running visual tests, or results may vary because of local font, OS, or browser differences.
CI also enables automated baseline updates. When you intentionally change a design, you can update baselines in a CI job and commit the new images. This keeps the process reviewable and prevents accidental overwrites.
Setting Up Playwright for Visual Tests
Start by installing Playwright and its test runner:
npm init playwright@latest
This creates a test directory, a configuration file, and example tests. To enable visual comparisons, add a test that navigates to a page and uses the toHaveScreenshot assertion:
import { test, expect } from '@playwright/test';
test('homepage matches baseline', async ({ page }) => {
await page.goto('https://example.com');
await expect(page).toHaveScreenshot('homepage.png');
});
On first run, Playwright will generate a baseline screenshot and save it in a __screenshots__ folder relative to the test file. Subsequent runs compare the live screenshot to that baseline. If they differ, the test fails and a diff image is saved for inspection.
Configuring Playwright for CI
Your playwright.config.ts should set up the browsers, viewport sizes, and other options. For CI, you often want to run tests headlessly and with a fixed viewport to ensure consistency. Here is a minimal configuration:
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './tests',
timeout: 30000,
use: {
browserName: 'chromium',
viewport: { width: 1280, height: 720 },
headless: true,
screenshot: 'only-on-failure',
},
projects: [
{ name: 'chromium', use: { browserName: 'chromium' } },
{ name: 'firefox', use: { browserName: 'firefox' } },
{ name: 'webkit', use: { browserName: 'webkit' } },
],
});
Playwright recommends running tests in a Docker container to match your CI environment. The official image mcr.microsoft.com/playwright includes the browsers and system dependencies. In your CI workflow, you can use this image directly.
Integrating with GitHub Actions
Here is a GitHub Actions workflow that runs Playwright visual tests on every push:
name: Playwright Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.40.0
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
- run: npm ci
- run: npx playwright install --with-deps
- run: npx playwright test
- uses: actions/upload-artifact@v4
if: failure()
with:
name: playwright-report
path: playwright-report/
This workflow installs dependencies, runs the tests, and uploads the report if any fail. The report contains the diff images, which you can download to see what changed.
Handling Baselines and Updates
When you intentionally change a design, you need to update the baseline screenshots. Playwright provides a flag for this:
npx playwright test --update-snapshots
This overwrites the stored baselines with the current screenshots. In CI, you can run this command in a dedicated job and commit the updated images. However, be careful: always review the diff images before committing to ensure you are not masking a real bug.
A common practice is to use a separate branch for baseline updates, then merge it after review. This prevents accidental updates on the main branch.
Common Problems and Solutions
Visual tests can be flaky. Here are typical issues and how to fix them:
- Font differences: CI machines may not have the same fonts as local machines. Use a font-loading library or ensure the same fonts are installed. Playwright can also wait for fonts to load using
page.waitForLoadState('networkidle'). - Animations: Disable CSS animations and transitions in tests to avoid timing issues. You can inject a style tag that sets
animation: none !important. - Viewport size: Always set a fixed viewport in the config. If the viewport changes, screenshots will differ.
- Color rendering: Different browsers may render colors slightly differently. Use a tolerance threshold in the assertion:
toHaveScreenshot('homepage.png', { maxDiffPixelRatio: 0.01 }).
Costs and Alternatives
Playwright is free and open source. Running visual tests in CI uses compute time, which may have costs if you use a paid CI service. You can reduce costs by running tests only on pull requests, or by using a matrix strategy to run only the browsers you need.
Alternatives to Playwright for visual regression include Percy (a commercial service), Applitools (also commercial), and open-source tools like BackstopJS or Cypress’s visual testing plugins. Playwright’s built-in support is often sufficient and avoids extra dependencies.
Frequently Asked Questions
How do I ignore a specific element in the screenshot?
You can mask elements using the mask option in toHaveScreenshot. For example, await expect(page).toHaveScreenshot('home.png', { mask: [page.locator('.ad-banner')] }). This will cover the element with a colored box before capturing.
Can I run visual tests only on certain browsers?
Yes. Use the --project flag to specify a browser, e.g., npx playwright test --project=chromium. In CI, you can run a matrix job with separate steps for each browser.
What is the best threshold for pixel differences?
It depends on your app. Start with maxDiffPixelRatio: 0.01 (1% of pixels) and adjust based on false positives. For text-heavy pages, you may need a lower threshold, while for images, a higher one.
How do I store baselines in the repository?
Baselines are stored as PNG files in a __screenshots__ folder next to your tests. You commit them to the repository. When you update them, commit the new images as well.
Why do my tests pass locally but fail in CI?
This usually happens due to environment differences: missing fonts, different OS rendering, or browser version mismatches. Use the Playwright Docker image in CI to replicate your local environment. Also, ensure you run npx playwright install --with-deps to get the exact browser versions.
Can I use visual regression testing on a component level?
Yes, Playwright supports component testing. You can mount a component, take a screenshot, and compare it. This is useful for design systems and shared UI components.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.