Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk5 min

How to Compare Screenshots in Playwright

Compare Playwright screenshots with toHaveScreenshot(), review and version baselines, and control visual-test noise with stable environments and appropriate tolerances.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Playwright Test’s toHaveScreenshot() assertion to compare a page or component against a reviewed baseline image. The first run creates the baseline; later runs compare captures against it. Keep capture conditions consistent, investigate visual differences before adjusting tolerances, and update a baseline only when the design change is intentional.

Compare a page with a screenshot baseline

toHaveScreenshot() is Playwright Test’s screenshot-specific visual assertion. It captures the page, compares the result with a reference image, and reports visual differences when the configured limits are exceeded. Use the page assertion for a whole page and the corresponding locator assertion when the component itself is what you need to verify. The assertion requires the Playwright Test runner.

import { test, expect } from '@playwright/test';

test('homepage visual baseline', async ({ page }) => {
  await page.goto('/');
  await expect(page).toHaveScreenshot('homepage.png');
});

On the first run, Playwright retries the capture until two consecutive screenshots match, then saves the last one as the reference. Inspect that generated image before treating it as expected output. Snapshot names normally include the browser and platform, or the configured project name, so references can remain distinct across rendering environments.

Review and update baselines safely

  1. Run the visual test once to generate the reference image.
  2. Open and review the image to confirm it represents the intended UI.
  3. Commit the approved reference alongside the test so it is available to later runs.
  4. When a visual change is expected, run npx playwright test --update-snapshots, inspect the updated image, and commit it only after approval.

Do not use snapshot updates to make an unexplained failure disappear. A baseline is reviewed test data, not disposable output.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose screenshot comparison tolerances

Playwright exposes three related controls. They measure different things: threshold affects how different an individual pixel may be, while maxDiffPixels and maxDiffPixelRatio cap the total amount of image difference.

Option What it controls Useful when
threshold Per-pixel perceived color difference. Playwright documents a default of 0.2; lower is stricter and higher is more permissive. You need to tune sensitivity to small color changes. This is a pixel-level tolerance, not a limit on the number of differing pixels.
maxDiffPixels Maximum absolute count of differing pixels. You want a fixed pixel budget. The guide’s 100-pixel example is illustrative, not a universal recommendation.
maxDiffPixelRatio Maximum fraction of the screenshot’s pixels that may differ. A proportional cap makes more sense than a fixed count when image dimensions vary.

Set a small, meaningful tolerance for the visual risk you can accept. Before raising it, check whether the difference comes from unstable data or capture conditions. Defaults can change; confirm exact behavior in the documentation for the Playwright version installed in your project.

You can configure expect.toHaveScreenshot defaults globally or per project when the same comparison policy makes sense across a suite. A named reference can use PNG by default; Playwright also documents lossless WebP when the snapshot filename ends in .webp.

Make captures repeatable

Visual comparisons only give useful signals when the reference and new capture are made under comparable conditions. Playwright warns that “Browser rendering can vary based on the host OS, version, settings, hardware, power source (battery vs. power adapter), headless mode, and other factors.” The statement is from the Microsoft Playwright visual comparisons documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Generate and compare baselines in the same pinned or otherwise stable CI environment where possible.
  • Keep the browser, operating system, fonts, viewport, and project configuration consistent. For materially different browser or platform projects, retain separate expected baselines rather than treating their rendering as interchangeable.
  • Use deterministic test data and wait for the UI state being tested. Make sure required fonts and assets have loaded before the screenshot.
  • Neutralize animation or other known volatility when it is irrelevant to the assertion. Playwright documents stylePath for injecting CSS to filter dynamic elements during capture.
  • Account for pointer position. Hover effects are captured when present, so move the pointer away or deliberately establish the desired hover state before asserting.

These are stabilization practices derived from the documented sources of rendering variation; there is no single capture recipe that fits every app.

Use the assertion that matches the output

For screenshot comparisons, use toHaveScreenshot() on the page or on the relevant locator. Playwright’s snapshot assertion documentation advises using the screenshot-specific assertion rather than toMatchSnapshot() for image comparison. toMatchSnapshot() remains suitable for strings or other snapshot data, including arbitrary buffers when that is the actual data under test.

Rank #4
The Web Testing Handbook
  • Used Book in Good Condition

Troubleshoot visual test failures

Symptom Likely cause What to check
The image differs only on a developer machine or in CI. Different OS, browser version, rendering settings, fonts, hardware, power state, or headless mode. Run both baseline generation and comparison in the same stable environment; check that the intended Playwright project is selected.
Small regions change between otherwise identical runs. Dynamic content, animation, late-loading assets, or nondeterministic test data. Stabilize the data and UI state, wait for assets that matter, and use stylePath to suppress irrelevant dynamic areas where appropriate.
A button or menu looks different in the screenshot. The pointer was in a different position, triggering a hover style. Move the pointer away before capture, or deliberately set the hover state the test is intended to verify.
Many tests suddenly pass after increasing tolerances. The tolerance may be hiding a real layout or rendering change. Inspect actual and expected images first. Tune the per-pixel threshold separately from the total-pixel or ratio cap.
The failure is legitimate after a planned UI change. The reference still represents the old design. Run npx playwright test --update-snapshots, review the replacement image, then commit it with the change.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

For a one-off screenshot returned from an API, ScreenshotNeo accepts a URL and returns an image or PDF. Its endpoint and options are documented at ScreenshotNeo documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers report the page verdict and billing status. Its MCP server provides screenshot and page-info tools for AI agents. The free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 shots. This is a capture API, not a replacement for Playwright’s versioned visual assertions and reviewed baselines.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Sign up free for ScreenshotNeo to get 1,000 screenshots a month with no card.

Further reading

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.