Playwright + TS · Lesson 32 of 36

0/36 done

Module 32: Visual Testing

32. Visual Regression Testing & Pixel Diff Assertions

17 minlesson

Try it yourself

Implement isDiffAcceptable:

  1. Accept diffPixels, totalPixels, and maxAllowedRatio (default 0.01).
  2. Return false if totalPixels is 0; otherwise return true if diffPixels / totalPixels <= maxAllowedRatio.

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

Visual Testing with toHaveScreenshot()

Playwright has native visual testing built right into expect:

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

test("landing page visual comparison", async ({ page }) => {
  await page.goto("https://targetqa.com");

  // Compares current page screenshot with saved golden snapshot:
  await expect(page).toHaveScreenshot("landing-page.png");
});

Masking Dynamic Content

Real pages contain clocks, timestamps, or live user avatars that change every second and cause false visual diffs. Mask them out!

typescript
test("dashboard with masked dynamic elements", async ({ page }) => {
  await page.goto("/dashboard");

  await expect(page).toHaveScreenshot("dashboard.png", {
    // Replaces dynamic elements with pink bounding boxes during comparison
    mask: [
      page.getByTestId("current-timestamp"),
      page.getByTestId("live-stock-ticker"),
    ],
    maxDiffPixelRatio: 0.02, // Allow 2% pixel tolerance
  });
});

Updating Snapshots

When the design changes intentionally, update the baselines:

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 + TS course (Playwright with TypeScript). 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 fail when run on Linux CI vs macOS/Windows local?

Different operating systems render system fonts and antialiasing slightly differently. Visual regression tests should ideally run inside standard Docker containers for pixel consistency.

Can I visually compare a single component instead of the whole page?

Yes! You can call expect(page.getByTestId('pricing-card')).toHaveScreenshot('card.png').

Finished reading?

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

TypeScript
Skip