Playwright + JS · Lesson 32 of 35

0/35 done

Module 32: Visual Testing

32. Visual Regression Testing & Pixel Diffing

17 minlesson

Try it yourself

Implement isDiffAcceptable:

  1. Accept diffPixels (number), totalPixels (number), and maxAllowedRatio (number, default 0.01).
  2. Return false if totalPixels === 0. Otherwise return diffPixels / totalPixels <= maxAllowedRatio.

The editor has a worked example. Read it, tweak it, then press Mark as complete.

Visual Testing with toHaveScreenshot()

javascript
import { test, expect } from "@playwright/test";

test("landing page visual comparison", async ({ page }) => {
  await page.goto("https://targetqa.com");
  await expect(page).toHaveScreenshot("landing.png", {
    mask: [page.getByTestId("live-clock")],
    maxDiffPixelRatio: 0.02,
  });
});

Update baselines when UI intentionally changes:

bash
npx playwright test --update-snapshots

Key Takeaways & Walkthrough Summary

Functional tests check if elements exist, but visual tests verify that your layout actually looks right. In this lesson, we will explore Playwright's native toHaveScreenshot visual assertions, pixel diffing, baseline snapshots, and how to mask dynamic elements like clocks and timestamps. Let's master visual regression testing!

Part of the Playwright + JS course (Playwright with JavaScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Why do visual tests sometimes fail between local workstations and CI?

Different operating systems render antialiasing and system fonts slightly differently. Visual tests should ideally run in standard Docker containers.

Finished reading?

Review the worked example in the editor, then mark the lesson complete.

JavaScript
Skip