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

Use Playwright Test’s locator assertion: await expect(locator).toHaveScreenshot('name.png'). It captures only the element matched by that locator, waits for two consecutive identical captures, and compares the result with a stored expectation. If you only need an image file, call locator.screenshot() instead.

Compare one element with a stored baseline

toHaveScreenshot() is the visual-regression API for a locator. The assertion is provided by the Playwright Test runner, not by the lower-level browser library alone. A complete test looks like this:

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

test('profile card matches its visual baseline', async ({ page }) => {
  await page.goto('https://example.com');

  const card = page.getByTestId('profile-card');
  await expect(card).toHaveScreenshot('profile-card.png');
});

The locator can be created with a test id, role, accessible name, text, or a CSS selector. Prefer a locator that identifies exactly one intended component. If it can match several elements, narrow it with a more specific role, test id, or locator() filter before taking the screenshot.

On a comparison, Playwright waits until two consecutive locator screenshots produce the same result, then compares the final image with the stored expectation. This stability check prevents a capture taken halfway through layout changes from becoming the baseline. On the first intentional baseline creation, run the test with Playwright’s snapshot-update switch:

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.
npx playwright test tests/profile-card.spec.ts --update-snapshots

Review generated images as code: accept a new baseline only when the visual change is expected. A changed baseline should be committed alongside the test change so another machine or a CI run has the same reference.

Capture an element without comparing it

Use Locator.screenshot() when you need an image for documentation, debugging, or another image-processing step rather than a pass/fail assertion:

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

test('save the card image', async ({ page }) => {
  await page.goto('https://example.com');
  const card = page.getByTestId('profile-card');

  await card.screenshot({
    path: 'artifacts/profile-card.png',
    animations: 'disabled',
  });
});

This method captures the page area clipped to the size and position of the element matched by the locator. It does not compare the bytes with a baseline and does not require an assertion. The same screenshot options used by assertions can be supplied explicitly for a direct capture.

Make the element comparison deterministic

Stop animation and transition noise

Screenshot assertions default to animations: 'disabled'. Playwright disables CSS animations, CSS transitions, and Web Animations while it captures the assertion image. Keep that default unless the animation itself is what you are testing. For direct captures, pass the option explicitly as shown above.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Mask changing regions instead of weakening the whole test

Use the mask option for timestamps, rotating avatars, random IDs, ad slots, or other content that is expected to change:

await expect(card).toHaveScreenshot('profile-card.png', {
  animations: 'disabled',
  caret: 'hide',
  mask: [page.getByTestId('last-updated')],
  maskColor: '#FF00FF',
  maxDiffPixelRatio: 0.01,
});

Each locator in mask contributes its bounding box to the covered area. Masking also applies to invisible matched elements unless your locator strategy limits matches to visible content, so make the mask locator as specific as the changing region. A mask hides the pixels; it does not remove the element’s space or allow the component to reflow.

caret: 'hide' keeps a text caret from moving between captures. It is the default for screenshot assertions, but stating it in a shared helper makes the policy clear.

Set a measured tolerance, not a blanket pass

Three options let you account for known rendering noise:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.
  • maxDiffPixels permits a fixed number of different pixels.
  • maxDiffPixelRatio permits a proportion from 0 to 1. For example, 0.01 allows up to one percent of pixels to differ.
  • threshold adjusts the per-pixel comparison threshold.

Start with the strictest setting that passes a stable environment. Increasing a tolerance can hide a real padding, color, or typography regression, so document why a nonzero value is needed and keep it local to the affected component.

Control the environment behind the pixels

A locator assertion compares rendered pixels, not semantic structure. Keep the inputs that produce those pixels fixed:

  • Use the same Playwright and browser versions for baseline generation and verification. The browser binaries installed by your project should be pinned in CI rather than silently updated.
  • Fix the viewport, device scale factor, and screenshot scale. A retina setting changes the number of pixels even when CSS dimensions are unchanged.
  • Install and load the same fonts. A fallback font changes line wrapping, element height, and anti-aliasing.
  • Set locale, timezone, color scheme, and reduced-motion preferences explicitly when the component displays dates, numbers, or theme-dependent colors.
  • Use deterministic test data. Freeze or stub values such as “last updated,” randomized IDs, rotating content, and feature flags; mask only values that cannot reasonably be controlled.
  • Control external requests and third-party widgets where possible. A remote ad, analytics script, or chat launcher can alter the element’s layout even when the component code is unchanged.

These controls are project responsibilities; Playwright exposes screenshot options, but the documentation does not promise automatic normalization of every font, browser, locale, or device difference.

Choose the API that matches the comparison

Need API Result
Compare one element with a stored baseline expect(locator).toHaveScreenshot(name) Locator-sized visual assertion
Save one element image locator.screenshot({ path }) Locator-sized image file
Compare a whole page expect(page).toHaveScreenshot(name) Page screenshot assertion; use only when the entire page region is intentional
Compare an arbitrary image buffer expect(await page.screenshot()).toMatchSnapshot(name) Snapshot comparison of supplied image data

For a component test, the locator form is usually the narrowest signal: an unrelated footer or advertisement cannot fail the card’s assertion. Use a page assertion when the page itself is the contract, and use toMatchSnapshot() when another API has already produced the image buffer.

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

Useful version and option notes

  • LocatorAssertions.toHaveScreenshot was added in Playwright v1.23.
  • PageAssertions.toHaveScreenshot was also added in v1.23.
  • maskColor is documented as added in v1.35.
  • stylePath is documented as added in v1.41.
  • The current page-screenshot assertion documentation lists a signal option added in v1.62.

These are API-version annotations, not promises about speed or rendering equivalence. Check the documentation for the Playwright version pinned by your project before sharing a configuration between repositories.

A practical baseline workflow

  1. Give the component a stable locator, such as data-testid="profile-card", and make sure the locator resolves to the intended element.
  2. Navigate to a deterministic fixture or test account, wait for the component’s required data, and set the project’s viewport, locale, theme, and browser consistently.
  3. Run toHaveScreenshot() with animations disabled and masks for values that genuinely cannot be fixed.
  4. Create or update the baseline deliberately with --update-snapshots, then inspect the image rather than accepting every generated file automatically.
  5. Run the same test in CI using the same browser and font setup. Treat a diff as a debugging signal: identify the changed region before changing tolerance.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting element screenshot comparisons

The test says the locator is ambiguous

The locator matched more than one candidate. Add a test id, constrain the role and accessible name, or use a locator filter so the screenshot has one well-defined target. Avoid silently selecting the first match when a duplicate indicates a real page problem.

The assertion times out while waiting for a stable image

Two consecutive captures never became identical. Look for a CSS animation, a transition, a continuously updating clock, a streaming response, a blinking caret, or a third-party widget inside the element. Disable the animation, stub the data, or mask the changing region. If the component is still loading, wait for its meaningful ready state before the assertion.

The diff contains only a date, ID, or avatar

Prefer deterministic test data. If that is not possible, mask the smallest locator covering the changing value and keep the rest of the element under comparison. A mask that covers the entire card can make the test pass while hiding layout regressions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

The image differs only on CI

Compare browser versions, installed fonts, viewport and device scale factor, locale, timezone, color scheme, and test data first. A screenshot is sensitive to all of them. Make the CI image the canonical baseline environment instead of compensating with a large pixel tolerance.

The direct screenshot works but the assertion API is unavailable

toHaveScreenshot() only works with the Playwright Test runner. If you are using the browser library directly, use locator.screenshot() to obtain the image and provide it to an image comparison tool, or move the test into a Playwright Test project.

A transparent or colored mask surprises reviewers

The mask replaces matched bounding boxes in the comparison image. Set maskColor to a conspicuous color such as #FF00FF so reviewers can see exactly which pixels are intentionally excluded. The option is available in versions documented from v1.35 onward.

Or skip the browser setup

If you need a rendered website image rather than a local Playwright baseline, ScreenshotNeo provides a website screenshot API and MCP server. It can capture one element by CSS selector as well as full pages, and its options include lazy-image loading, dark mode, device presets or custom viewports, retina scale, custom CSS and JavaScript, clicks, waits, hidden selectors, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous jobs, webhooks, bulk capture, usage reporting, and PDF output.

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.

One-call capture with cURL:

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

The same request in Python:

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

And in 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}`);

See the ScreenshotNeo documentation for the element-selector option and the other request parameters. ScreenshotNeo accepts the cookie or consent banner before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be switched off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

Plan Included shots Price
Free 1,000 per month $0, no card
Starter 3,000 $5
Growth 15,000 $15
Pro 60,000 $39
Scale 250,000 $99
Business 1,000,000 $249

Yearly billing gives two months free, and every feature is available on every plan. Start with 1,000 free screenshots a month with no card; paid plans start at $5 for 3,000 shots.

Frequently Asked Questions

Can I compare two elements in one Playwright test?

Yes. Create a separate locator for each component and call toHaveScreenshot() for each one, using a distinct snapshot name. This keeps a failure tied to the component that changed.

How should an element inside an iframe be selected?

Create the locator through the frame that owns the element, then apply the same locator screenshot assertion to that frame-scoped locator. The screenshot still clips to the matched element rather than the whole page.

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.