Playwright + TS · Lesson 32 of 36
Module 32: Visual Testing
Try it yourself
Implement isDiffAcceptable:
The editor has a worked example. Read it, tweak it, then press Mark as complete.
In this lesson
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");
});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
});
});When the design changes intentionally, update the baselines:
npx playwright test --update-snapshotsFunctional 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.
Different operating systems render system fonts and antialiasing slightly differently. Visual regression tests should ideally run inside standard Docker containers for pixel consistency.
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.