Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Compare Chromium Screenshots for Visual Regression Testing

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Visual regression testing catches unintended UI changes by comparing screenshots of your web pages before and after code changes. This guide shows you how to set up and run visual regression tests specifically for Chromium-based browsers (Chrome, Edge, Brave) using a practical, step-by-step approach. You'll learn how to capture baseline screenshots, run comparisons, and interpret the results—no paid tools required.

What You'll Need

  • A Chromium-based browser (Chrome, Edge, or Brave) installed on your machine.
  • Node.js (version 14 or later) installed—this is the runtime for the tools we'll use.
  • A code editor (VS Code, Sublime, or any text editor).
  • Basic familiarity with the command line (terminal or PowerShell).
  • Your web application running locally or accessible via a URL.

Step-by-Step

  1. Set up a new project directory. Open your terminal and run:
    mkdir visual-regression-testing
    cd visual-regression-testing
    npm init -y
    This creates a fresh folder and a package.json file.
  2. Install Playwright. Playwright is a browser automation library that works perfectly with Chromium. Run:
    npm install @playwright/test
    This installs the test runner and browser control APIs.
  3. Install the Chromium browser. Run:
    npx playwright install chromium
    This downloads the Chromium binary that Playwright will use. Note: this is separate from your regular Chrome installation.
  4. Create a test file. In the project root, create a file named visual.spec.js. This will hold our test logic.
  5. Write the baseline capture script. Open the file and add the following code:
    const { test, expect } = require('@playwright/test');
    
    const BASE_URL = 'http://localhost:3000'; // Change this to your app's URL
    const VIEWPORT = { width: 1280, height: 720 };
    
    async function captureScreenshot(page, name) {
      await page.screenshot({ path: `screenshots/${name}.png`, fullPage: true });
    }
    
    test('capture baseline', async ({ browser }) => {
      const page = await browser.newPage({ viewport: VIEWPORT });
      await page.goto(BASE_URL, { waitUntil: 'networkidle' });
      await captureScreenshot(page, 'baseline-home');
      await page.close();
    });
    This script navigates to your app and saves a full-page screenshot as baseline-home.png.
  6. Run the baseline capture. In the terminal, run:
    npx playwright test visual.spec.js --grep "capture baseline"
    After it runs, you'll see a screenshots folder with the baseline image.
  7. Create the comparison test. Add a second test to the same file:
    test('compare against baseline', async ({ browser }) => {
      const page = await browser.newPage({ viewport: VIEWPORT });
      await page.goto(BASE_URL, { waitUntil: 'networkidle' });
      await captureScreenshot(page, 'current-home');
      await page.close();
    
      const baseline = 'screenshots/baseline-home.png';
      const current = 'screenshots/current-home.png';
      const { compare } = require('pixelmatch');
      const fs = require('fs');
      const PNG = require('pngjs').PNG;
    
      const img1 = PNG.sync.read(fs.readFileSync(baseline));
      const img2 = PNG.sync.read(fs.readFileSync(current));
      const diff = new PNG({ width: img1.width, height: img1.height });
      const numDiffPixels = compare(img1.data, img2.data, diff.data, img1.width, img1.height, { threshold: 0.1 });
    
      fs.writeFileSync('screenshots/diff.png', PNG.sync.write(diff));
      console.log(`Difference: ${numDiffPixels} pixels`);
      expect(numDiffPixels).toBeLessThan(100); // Adjust threshold as needed
    });
    This test takes a fresh screenshot, compares it to the baseline using pixelmatch, and saves a diff image.
  8. Install pixelmatch and pngjs. Run:
    npm install pixelmatch pngjs
    These libraries handle image comparison and PNG encoding.
  9. Run the comparison test. Execute:
    npx playwright test visual.spec.js --grep "compare against baseline"
    The test will pass if the pixel difference is below your threshold; otherwise it fails and you get a diff image.
  10. Review the diff image. Open screenshots/diff.png in any image viewer. Red or highlighted areas indicate where the two screenshots differ.

Common Mistakes

  • Forgetting to wait for network idle. If your page loads assets asynchronously, screenshots may capture incomplete content. Always use waitUntil: 'networkidle' or a specific selector wait.
  • Hardcoding viewport sizes. Different screen sizes produce different layouts. Always set a fixed viewport in your test to ensure consistent results.
  • Ignoring dynamic content. Dates, timers, or random data will cause false positives. Use Playwright's page.clock or mock APIs to stabilize content.
  • Setting the pixel threshold too low. Even minor anti-aliasing differences can cause hundreds of pixels to differ. Start with a threshold of 0.1% of total pixels and adjust based on your app.

Tips

  • Use a dedicated test environment. Run tests against a staging server with known data, not production, to avoid unexpected changes.
  • Store baselines in version control. Commit baseline images so you can track when they change intentionally.
  • Automate with CI. Integrate the test into your CI pipeline (GitHub Actions, Jenkins) to catch regressions automatically on every commit.
  • Group related pages. Instead of one test per page, loop through an array of routes to test multiple pages in a single run.
  • Use Playwright's built-in screenshot options. You can mask elements (e.g., ) to ignore known volatile areas.

Troubleshooting

  • Test fails with "Cannot find module 'pixelmatch'" — Make sure you installed the dependencies in the same directory as your test file. Run npm install pixelmatch pngjs again.
  • Chromium fails to launch — Ensure you ran npx playwright install chromium. If it still fails, check that your system has the required libraries (on Linux, run npx playwright install-deps).
  • Screenshots are blank or black — This usually means the page didn't load. Check the URL and ensure your app is running. Also try waitUntil: 'load' instead of 'networkidle'.
  • Diff image is all red — The screenshots are completely different. Check if the viewport size matches, if the page scrolled differently, or if there's a popup/modal covering the page.
  • Test passes but I know there's a visual bug — Your pixel threshold may be too high. Lower it gradually until the test catches the issue. Also check that you're comparing the right elements—maybe the bug is in an area you're masking.

Frequently Asked Questions

Can I use this with Chrome instead of Chromium?

Yes. In your Playwright config, set channel: 'chrome' to use your installed Chrome browser instead of the bundled Chromium.

How do I test multiple pages at once?

Create an array of routes and loop through them in a single test, or use test.describe to generate separate tests for each page.

What if my app has animations?

Disable animations in your test by injecting CSS: await page.addStyleTag({ content: '* { animation: none !important; transition: none !important; }' }); before taking the screenshot.

How do I handle responsive design?

Run the same test with multiple viewport sizes using test.use({ viewport: { width: 375, height: 667 } }) for mobile, and a desktop size for desktop.

Can I compare screenshots from different branches?

Yes. Run the baseline capture on the main branch, then switch to your feature branch and run the comparison test. The baseline image remains unchanged.

What does the pixel threshold mean exactly?

It's the maximum number of pixels that can differ before the test fails. A value of 100 means up to 100 pixels can differ without failing. Adjust based on the size of your page and tolerance for minor rendering differences.