32. Visual Regression Testing & Pixel Diff Assertions

Visual Testing with toHaveScreenshot()

Playwright has native visual testing built right into expect:
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!
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:
npx playwright test --update-snapshots

Task

  • 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.
πŸ’‘Common doubts
Did you like the problem?
Lesson 32 of 36
TypeScript
Loading code editor…
Next