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

Use Playwright Test’s expect(page).toHaveScreenshot() for a route or full page, and expect(locator).toHaveScreenshot() for a component or region. The first run saves a baseline image; later runs capture the same target and compare it with pixelmatch. Reliable results depend on deterministic data, a fixed rendering environment, and a deliberately chosen diff policy.

Choose the comparison scope

Start by defining what your visual contract covers. A page assertion makes failures meaningful when navigation, layout, responsive composition, or the complete route must remain stable. A locator assertion is better when only one component matters and unrelated page content would add noise.

Compare a complete page

Use page when the test should include the header, navigation, content layout, and surrounding page structure:

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

test('homepage visual baseline', async ({ page }) => {
  await page.goto('https://example.com');
  await expect(page).toHaveScreenshot('homepage.png', {
    fullPage: true,
    animations: 'disabled',
    threshold: 0.2,
    maxDiffPixels: 100,
  });
});

Set fullPage: true when the contract includes content below the viewport. Without it, the assertion covers the visible viewport.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Compare one component or region

Use a locator when the visual contract is a card, dialog, table, chart, form control, or other bounded element:

test('pricing card remains stable', async ({ page }) => {
  await page.goto('https://example.com/pricing');
  const card = page.locator('[data-testid="pricing-card"]');
  await expect(card).toHaveScreenshot('pricing-card.png');
});

Prefer a stable test ID or semantic selector over a long CSS path. A locator assertion reduces failures caused by unrelated banners, recommendations, or footer changes.

How baselines and retries work

On the first execution, Playwright creates the expected snapshot in the test snapshot directory. Review that image, then commit it to version control with the test. Every later execution captures the target and compares it with the stored baseline. A changed snapshot is not automatically a defect: inspect the actual, expected, and diff images before deciding.

Before comparison, Playwright waits until two consecutive page screenshots are identical, then compares the final capture. This built-in stabilization helps with settling layout, but it cannot make nondeterministic application data deterministic.

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

Keep baselines portable

Generate and consume snapshots with the same browser project and rendering environment whenever possible. Keep the browser version, operating-system image, viewport, device scale factor, fonts, locale, timezone, and test data consistent between local baseline generation and CI. Differences in any of these can create large, misleading diffs.

Store snapshots in version control. When a design change is intentional, update the baseline in the same change and review the image diff as a normal code-review artifact.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Make captures deterministic

Visual comparison is only useful when pixels represent the state you intend to test. Stabilize the page before asking Playwright to capture it.

Control application data and time

  • Mock changing API responses so the same records render on every run.
  • Freeze clocks when timestamps, countdowns, or date-sensitive labels are not part of the contract.
  • Wait for content that must be present, such as a table, chart, or authenticated state, instead of relying on a fixed delay.
  • Remove random IDs, rotating promotions, and per-run generated text from the rendered state.
  • Wait for fonts and other visual assets that affect layout.

Playwright’s screenshot assertion disables animations by default. Finite animations are fast-forwarded to completion; infinite animations are canceled to their initial state for the screenshot and resumed afterward. Set animations: 'allow' only when motion itself is the behavior under test.

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

Mask pixels outside the contract

Use mask for timestamps, avatars, ads, rotating offers, or other regions whose content is intentionally variable:

test('dashboard layout', async ({ page }) => {
  await page.goto('https://example.com/dashboard');
  await expect(page).toHaveScreenshot('dashboard.png', {
    fullPage: true,
    animations: 'disabled',
    mask: [
      page.locator('[data-testid="live-clock"]'),
      page.locator('[data-testid="user-avatar"]'),
    ],
    maskColor: '#ff00ff',
  });
});

Mask only pixels that are genuinely outside the visual contract. The API can mask invisible elements too, so scope selectors carefully and avoid broad containers that hide real regressions.

Apply a shared style override

stylePath applies a stylesheet during capture. It is useful when many tests need the same treatment for carets, transitions, or known dynamic selectors:

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
await expect(page).toHaveScreenshot('settings.png', {
  stylePath: './visual-test.css',
});

Keep this stylesheet narrow. Hiding a layout element to make tests pass removes the very pixels the test should protect.

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

Configure diff strictness deliberately

Playwright Test uses pixelmatch for screenshot comparison. Its color difference is calculated in YIQ space. Three options control how much change is acceptable:

Option What it limits Use it for
threshold Per-pixel perceived color difference, from 0 (strict) to 1 (lax) Small rendering or anti-aliasing variation
maxDiffPixels Absolute number of changed pixels A fixed pixel budget for a known-size image
maxDiffPixelRatio Fraction of changed pixels A proportional budget across different image sizes

Begin with strict settings, inspect actual diffs, and relax only for measured rendering noise. A high threshold or generous pixel budget can allow a meaningful layout shift to pass. For example:

await expect(page).toHaveScreenshot('checkout.png', {
  threshold: 0.1,
  maxDiffPixels: 50,
  maxDiffPixelRatio: 0.001,
});

Do not increase all three values automatically. Identify whether the problem is color-level noise, a small number of pixels, or a size-dependent fraction, then adjust the corresponding control.

Page versus locator: a practical decision

  • Choose a page assertion when navigation, responsive layout, global spacing, or the entire route is the requirement.
  • Choose a locator assertion when a component is independently owned, reused, or easier to diagnose in isolation.
  • Use both when a release needs a broad route guard and focused tests for high-risk components.

For a full-page test, make the route state explicit: set the viewport and device scale factor in the project configuration, log in through a stable fixture, and seed the same data. For a component test, render or navigate to the smallest state that still exercises the component’s real styles and behavior.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Failure triage workflow

  1. Open the actual, expected, and diff images produced by the test runner.
  2. Classify the change as a real UI regression, an intentional design update, or nondeterministic content.
  3. If it is nondeterministic, fix its source: mock data, freeze time, wait for fonts or required content, or narrow an over-broad selector.
  4. Mask only pixels that are outside the visual contract.
  5. Confirm that the same browser project and rendering environment produced both images.
  6. Update the snapshot only after a human has reviewed the visual diff.

Common symptoms and fixes

Symptom Likely cause Fix
Large areas shift between runs Different fonts, viewport, OS, or device scale factor Pin the rendering environment and install identical fonts
Only timestamps or avatars differ Dynamic application data Freeze or mock the data, or mask the specific locators
Text is captured before it appears Assertion runs before required content is ready Wait for a meaningful selector or stable state rather than adding arbitrary sleep
Animated element produces intermittent diffs Motion or transition is still part of the capture Keep animations: 'disabled' and use stylePath for persistent transitions
Small anti-aliasing differences fail the test Pixel-level rendering noise Measure the diff, then cautiously tune threshold or a small pixel budget
A deliberate redesign fails every test Baseline is outdated Review the diff and commit the new snapshot with the design change

Alternative snapshot matching

You can compare a screenshot buffer with expect(await page.screenshot()).toMatchSnapshot('landing-page.png'). That matcher is useful for arbitrary buffers or non-page snapshot data. For page screenshot comparison, Playwright’s SnapshotAssertions guidance recommends toHaveScreenshot(), because it provides the page/locator screenshot workflow and stabilization behavior directly.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If you need rendered images from URLs rather than assertions inside a Playwright suite, ScreenshotNeo provides a website screenshot API and MCP server. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status.

One GET request returns PNG, JPEG, WebP, or a PDF. The API also supports full-page captures with lazy images loaded, CSS-selector element captures, dark mode, device presets and custom viewports, retina scale, custom CSS and JavaScript, clicks, selector/delay/network-idle waits, request and resource blocking, headers, cookies, user agents, Authorization, timezone and geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Parameter names used by other screenshot APIs also work, which simplifies migration.

ScreenshotNeo includes an MCP server with take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for authentication and options. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to start.

Python and Node.js equivalents

The same endpoint can be called from application code when you need screenshots in a build, report, or content pipeline.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Python

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

Operational and cost considerations

Playwright baselines run wherever your test suite runs, so CI time, browser resources, and snapshot review are the practical costs. Keep visual tests focused on stable contracts rather than every route state. Separate intentional baseline updates from functional changes so reviewers can understand why pixels changed.

For external URL capture, ScreenshotNeo’s plans are Free: 1,000 shots/month; Starter: $5 for 3,000; Growth: $15 for 15,000; Pro: $39 for 60,000; Scale: $99 for 250,000; and Business: $249 for 1,000,000. Yearly billing provides two months free, and every feature is included on every plan.

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

Frequently Asked Questions

Does Playwright compare screenshots pixel by pixel?

Playwright Test uses pixelmatch and applies the configured color threshold plus any absolute or ratio pixel budget. It is a pixel-based comparison, but the policy can allow measured rendering variation.

Where are Playwright screenshot snapshots stored?

Playwright Test stores expected images in the test snapshot directory associated with the test. Keep that directory in version control so CI compares against the reviewed baseline.

Should visual tests run on every operating system?

Usually, generate and compare baselines on one pinned browser and operating-system image. Add other environments only when cross-platform rendering is itself part of the requirement.

When should I use a masked region instead of a tolerance?

Mask a region when its content is outside the visual contract, such as a live clock. Use tolerance settings for small, measured rendering noise in pixels that still belong to the contract.

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

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.