Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsIn Playwright, “HTML snapshot” can mean either a screenshot of the rendered page or a saved copy of its DOM. Use expect(page).toHaveScreenshot() to catch visual changes, and use page.content() with expect(value).toMatchSnapshot() to compare serialized HTML. These approaches test different things; choose based on whether the regression you care about is visual or structural.
Choose between a visual screenshot and an HTML snapshot
A browser renders HTML, CSS, fonts, images, and other resources into pixels. A visual snapshot checks those pixels. A DOM snapshot checks serialized markup or another string or binary value. Neither replaces the other: a screenshot can reveal a spacing or color change without explaining the markup behind it, while an HTML diff can expose a changed attribute or text even if the visible page looks the same.
| Approach | What it compares | Best for | Typical noise |
|---|---|---|---|
toHaveScreenshot() |
A rendered page or locator image against an image baseline | Layout, styling, visual content, and regressions a user can see | OS, browser version, settings, hardware, power source, headless mode, fonts, and dynamic page content |
toMatchSnapshot() |
A string or binary value against a stored snapshot file | Serialized HTML, text, structured output, or other exact content | Changing markup, timestamps, generated IDs, ads, or other variable data |
Playwright’s snapshot API specifically directs screenshot comparisons to PageAssertions.toHaveScreenshot() (SnapshotAssertions API). For a page-wide visual check, use a page assertion. For a smaller visual contract, use a locator assertion. For DOM content, capture the value you want to govern and assert it as a generic snapshot.
Set up Playwright Test
These examples use the Playwright Test runner and TypeScript. In a project that already has Playwright Test installed, place the test in a file matched by your configured test pattern, such as tests/snapshots.spec.ts, and run it with the project’s Playwright test command. The examples use the official Playwright documentation’s example.com URL as a demonstration target; replace it with a page under test.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
Capture and compare a visual screenshot
Use toHaveScreenshot() when the expected result is a stable rendering. The first run creates the expected image. Later runs take a fresh screenshot and compare it with that baseline.
import { test, expect } from '@playwright/test';
test('page visual baseline', async ({ page }) => {
await page.goto('https://example.com');
await expect(page).toHaveScreenshot('example.png');
});
The screenshot assertion waits for two consecutive page screenshots to produce the same result before comparing the final capture with the expectation (PageAssertions API). This stabilization helps avoid comparing an in-flight render, but it does not make a page with continuously changing content deterministic. Control that content separately—for example, use fixed test data or wait for a meaningful page state before asserting.
Capture one component instead of the whole page
A locator assertion narrows the contract to a component. This can make a failure easier to diagnose and reduce unrelated changes elsewhere on the page from affecting the same baseline.
import { test, expect } from '@playwright/test';
test('checkout summary visual baseline', async ({ page }) => {
await page.goto('https://example.com/checkout');
const summary = page.locator('[data-testid="checkout-summary"]');
await expect(summary).toHaveScreenshot('checkout-summary.png');
});
Use a selector that identifies the intended element reliably. If the locator matches nothing or is not visible, the test cannot produce the intended component screenshot; inspect the selector and the page state before changing comparison tolerances.
Free tools Windows power users keep installed
One-click scans. No signup required.
Capture and compare serialized HTML
For DOM or serialized-content checks, read the page content and pass the string to toMatchSnapshot(). Unlike a screenshot, this assertion compares the captured representation, not the rendered pixels.
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
import { test, expect } from '@playwright/test';
test('serialized HTML snapshot', async ({ page }) => {
await page.goto('https://example.com');
const html = await page.content();
expect(html).toMatchSnapshot('example.html');
});
toMatchSnapshot() accepts strings or binary data and compares the value with a stored snapshot file (SnapshotAssertions API). A whole-page HTML snapshot can be noisy: a timestamp, randomized identifier, rotating advertisement, or analytics-injected node may change even when the behavior you care about has not. If such data is expected to vary, normalize it before asserting or snapshot a narrower value that expresses the contract you actually want to protect.
Normalize only known, irrelevant variation
Do not strip broad sections of the DOM simply to make the test pass. Identify the unstable field, transform that field predictably, and retain the rest of the value so an unexpected content change still fails.
const html = await page.content();
const normalized = html
.replace(/<!-- rendered-at: .*? -->/g, '<!-- rendered-at: NORMALIZED -->');
expect(normalized).toMatchSnapshot('example.html');
This illustrative normalization is appropriate only if the application actually emits that known comment and it is irrelevant to the assertion. Adapt the transformation to the application’s real output; do not use a made-up pattern as a blanket solution.
Recommended Free Tools
Generate, review, and update baselines
- Run in the intended comparison environment. The first execution of a visual assertion writes its reference image. Establish baselines using the same browser and environment that will run subsequent comparisons.
- Inspect the generated file. Review the image or text snapshot to confirm it represents the intended state—not a loading screen, transient error, or incomplete page.
- Commit the snapshot directory with the test. Playwright stores baselines in a directory associated with the test file by default. Keeping baseline changes under version control lets reviewers inspect changes alongside code.
- Regenerate only for an approved change. When a UI or content change is intentional, use Playwright’s documented
--update-snapshotsflow, then review and commit the resulting diff (Playwright Test snapshots guide).
Updating snapshots is not a fix for an unexplained failure. First determine whether the application changed intentionally, the test captured the wrong state, or the rendering environment drifted. Otherwise, accepting a new baseline can turn a real regression into the new expectation.
Keep visual comparisons deterministic
Playwright cautions that browser rendering can vary with host OS, browser version, settings, hardware, power source (battery or adapter), headless mode, and other factors (Playwright Test snapshots guide). A practical response is to pin and keep consistent the conditions your project controls:
Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
- Use the same Playwright browser version and operating-system or container image for baseline generation and comparison.
- Set a stable viewport and use predictable test data.
- Make fonts available consistently, and avoid switching between materially different headless and headed environments for the comparison run.
- Wait for the application state that matters instead of relying on an arbitrary short delay when the page has a reliable readiness signal.
- Control or normalize known dynamic content only when it is outside the purpose of the test.
Keeping these variables fixed reduces avoidable noise; changing them may legitimately require reviewing and regenerating baselines. A stable screenshot is not automatically a correct screenshot, so also verify that the test reaches the intended state.
Organize snapshot files and names
By default, Playwright stores snapshot files in a directory associated with the test file. The snapshotPathTemplate configuration option can organize paths using values such as the test file, project, and assertion kind. Templates can be configured globally or for specific assertion types, including screenshots, ARIA snapshots, and generic snapshots (Playwright Test snapshots guide).
Use stable names that explain the state being asserted, such as empty-cart.png or article.html. Avoid names derived from test order or transient values. If the project has multiple browser projects, make sure the path scheme keeps their baselines distinct where their expected renderings differ; otherwise, one project’s update can obscure another’s expectation.
Choose screenshot tolerances deliberately
Playwright provides threshold, maxDiffPixels, and maxDiffPixelRatio controls for image comparison (SnapshotAssertions API). Keep comparisons strict initially. If a known, acceptable source of rendering variation remains after stabilizing the environment, choose the smallest allowance that matches the risk and document why it exists.
thresholdadjusts the per-pixel color difference threshold used in comparison.maxDiffPixelslimits the allowed count of differing pixels.maxDiffPixelRatiolimits the allowed fraction of differing pixels.
These settings answer different questions: how different a pixel may be, how many pixels may differ, and what fraction of the image may differ. A permissive allowance can conceal a real layout or visual-content regression. Pair any nonzero tolerance with a review rule, and do not raise it merely because a failure is inconvenient.
Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Troubleshoot snapshot failures
The first visual run reports a missing baseline
This is expected when no reference image exists yet. Confirm the test reached the intended page state, let the first run generate the snapshot, inspect the resulting image, and commit it. If the generated image is blank or incomplete, fix navigation or readiness handling before accepting it.
The screenshot differs across machines
Check OS or container image, browser version, headless mode, viewport, fonts, hardware-sensitive rendering, and power conditions. Playwright explicitly identifies these as possible sources of visual variation. Align the comparison environment before adding a tolerance or updating a baseline.
The page screenshot is unstable
The assertion already waits for two consecutive identical screenshots, but continuously changing content can still defeat a stable comparison. Look for animations, rotating content, live timestamps, ads, or data that changes between runs. Prefer controlling test data or waiting for the relevant state; normalize only known irrelevant variation.
The HTML snapshot changes unexpectedly
Inspect the text diff for changed markup, serialized attributes, dynamic IDs, timestamps, or injected content. Decide whether the change is meaningful to the test. If it is not, normalize that specific source or assert a smaller serialized value; if it is meaningful, investigate the application change rather than refreshing the baseline immediately.
The test passes despite a visible regression
A generic HTML snapshot may not represent visual styling, and a screenshot tolerance may be too permissive. Match the assertion to the behavior you need to protect, review the baseline diff, and reassess any configured allowance. For layout and appearance, use a screenshot assertion; for exact markup or content, use a generic snapshot.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteBest Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
The snapshot is saved in an unexpected location
Check the test file’s associated snapshot directory and any configured snapshotPathTemplate. If several projects or assertion types are involved, inspect how the template uses project and assertion-kind values. Keep paths stable and distinct enough to prevent unrelated tests from sharing a baseline accidentally.
Or skip the browser setup
If you need a captured page image rather than a Playwright test baseline, ScreenshotNeo can return a screenshot or PDF with one GET request. For this HTML demonstration, the call captures the rendered page at the supplied URL; it does not create or compare Playwright’s version-controlled snapshot baseline.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp
See the ScreenshotNeo API documentation for request options. Cookie banners and consent overlays, newsletter popups, and chat widgets are removed before the shot; each cleanup step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and billing status. Its MCP server provides screenshot tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots.
Learn about ScreenshotNeo, or sign up free for 1,000 screenshots a month with no card.
Frequently Asked Questions
Can Playwright snapshot an arbitrary JavaScript value, not just page HTML?
Yes. `toMatchSnapshot()` accepts strings or binary data, so you can snapshot a serialized value produced by your test as well as `page.content()`.
Does Playwright compare screenshot baselines pixel by pixel?
It compares screenshots as images using its configured image-comparison policy. The available controls include `threshold`, `maxDiffPixels`, and `maxDiffPixelRatio`; choose them based on known variation and review risk.
Quick Recap
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.

