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

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

For an ordinary JSON snapshot in Playwright, serialize the value you want to preserve and pass the resulting string to expect(...).toMatchSnapshot('name.json'). Playwright compares that text with a checked-in baseline; it does not use a separate JSON-only snapshot matcher. If you need an accessibility tree as JSON data, use ariaSnapshotJSON() instead. These are different jobs, and neither should be confused with Playwright’s YAML-based accessibility snapshots or image-based visual snapshots.

Choose the right kind of snapshot

“JSON snapshot” can mean a file containing serialized JSON, or a JSON representation of a page’s accessibility structure. Start by deciding what you need to protect: an API or application value, accessible page structure, or rendered pixels. Playwright’s APIs use different representations for each. Playwright documents toMatchSnapshot() as a way to compare text or arbitrary binary data; a .json filename is useful and readable, but does not turn it into a distinct JSON-specific matcher.

What you want to check API Representation
A serialized API response or other JSON value expect(value).toMatchSnapshot('name.json') Text or arbitrary binary data; JSON is serialized by your test
An accessibility tree as a runtime JSON value page.ariaSnapshotJSON() or its locator equivalent JSON value
Accessibility structure compared with a template toMatchAriaSnapshot() YAML template, normally in an .aria.yml file
Rendered page or element appearance toHaveScreenshot() PNG by default, or WebP when the snapshot is named .webp

Use a serialized JSON snapshot when the meaningful contract is the data itself: for example, a stable settings response, a configuration object, or a generated payload. Use an accessibility snapshot when the contract is the page’s semantic structure. Use a screenshot assertion when visual rendering is the behavior under test. A screenshot can show that something changed, but cannot by itself tell you whether the change was a data-field regression or an accessibility issue.

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

Write a JSON snapshot test

This TypeScript example uses Playwright Test’s built-in request fixture to fetch an endpoint, parse the response as JSON, serialize it consistently, and compare it with a named baseline. Replace /api/settings with a route available to your project. The test assumes your Playwright Test configuration provides the appropriate base URL; if it does not, use the full endpoint URL.

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

test('settings response remains stable', async ({ request }) => {
  const response = await request.get('/api/settings');
  expect(response.ok()).toBeTruthy();

  const data = await response.json();
  const stableJson = JSON.stringify(data, null, 2);
  expect(stableJson).toMatchSnapshot('settings.json');
});

The status assertion makes a failed HTTP response fail clearly before the snapshot comparison. Without it, an error payload could become the new expected content and obscure the actual problem. If your endpoint intentionally returns a non-success status, assert the expected status explicitly instead of copying this success check.

Create or intentionally refresh the baseline

Run the test once to create a missing snapshot. When a later change is intentional, update the baseline with:

npx playwright test --update-snapshots
# Short form:
npx playwright test -u

The update option creates missing baselines and updates mismatching ones; matching snapshots are not rewritten. Inspect the resulting diff before accepting it, then commit the test and its snapshot together. Do not treat a green run with an update flag as proof that the new output is correct: the purpose of the review is to decide whether the change is expected.

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

Make serialized JSON stable and reviewable

Snapshot matching is literal text comparison. Equivalent JSON objects can produce noisy diffs if their serialized text changes because of formatting or unstable values. Pretty-printing with JSON.stringify(data, null, 2) gives a consistent indentation style and makes field-level changes easier to inspect. It does not normalize the data for you.

Normalize only values that are genuinely irrelevant

Before serialization, account for fields that vary between otherwise equivalent runs, such as generated timestamps, random identifiers, request IDs, or unstable ordering. If those fields are not part of the behavior the test intends to protect, transform them into stable values or remove them in a deliberate normalization step. For example, if a response includes a generated request ID that is irrelevant to the contract, omit that property from the snapshot input. If ordering is not semantically meaningful, sort the relevant collection by a stable key before serializing.

Keep meaningful differences visible. Normalizing every changing value can make the snapshot pass while hiding a real regression; leaving irrelevant noise in place can make useful changes hard to find. The choice should follow the assertion’s purpose, not simply the desire to avoid updates. If order is meaningful to consumers, preserve it. If a timestamp is itself the behavior being tested, assert it directly with an appropriate range or expectation rather than erasing it from the snapshot.

Name and organize baselines deliberately

Give each artifact a name that identifies the data or scenario, such as settings.json, rather than using a generic name that becomes ambiguous as a test grows. When one test needs multiple snapshots, use distinct names or path segments to communicate what each one represents. Playwright normally stores snapshots in a separate directory beside the test file, commonly named like example.spec.ts-snapshots. Commit the baseline with the test so a clean checkout can compare against the same expected value.

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

Understand accessibility snapshots and visual snapshots

JSON accessibility data is not a JSON snapshot assertion

page.ariaSnapshotJSON() and the locator equivalent return accessibility structure as a JSON value for runtime use. That is useful when a test or tool needs to inspect or process the structure as data. By contrast, toMatchAriaSnapshot() matches an accessibility structure against a template, using YAML syntax by default. The fact that one API can return JSON does not mean the template matcher expects a JSON file. See the Page API documentation and accessibility snapshot guide for the respective APIs and formats.

Use screenshot assertions for rendered appearance

await expect(page).toHaveScreenshot() is for visual regression, not JSON data. The page and locator screenshot assertions wait for two consecutive screenshots to stabilize before comparing. They also provide controls such as disabling animations, masking regions, applying style paths, and setting pixel-difference thresholds. Pick these controls to account for known rendering noise, not to conceal a meaningful visual change. The page assertion API and locator assertion API describe the relevant assertion forms.

Rendering can vary across operating systems, browser versions, dependencies, and other host conditions. Generate and review visual baselines in a consistent browser and rendering environment. This is especially important for image comparisons: a pixel difference can reflect an environment change rather than an application change. That concern is different from a serialized JSON text snapshot, though unstable input data can make the latter noisy too.

Control where snapshots are stored

The default adjacent snapshot directory is suitable for many repositories. For a different layout, Playwright exposes test.info().snapshotPath() to resolve paths for ordinary, screenshot, and aria snapshot kinds. You can configure a project-wide or assertion-specific snapshotPathTemplate when you need snapshots organized differently. Supported template tokens include {testFilePath}, {arg}, {ext}, {platform}, and {projectName}. See the TestInfo API and TestProject API for path resolution and project configuration details.

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.

Choose a layout that remains predictable for contributors and CI. A platform- or project-specific path can be useful when baselines truly differ by environment, but it can also multiply the number of files that need review. Avoid changing the path scheme casually: relocating baselines can look like deleting and recreating every snapshot even when the expected content has not changed.

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

Troubleshoot common snapshot failures

  • Playwright reports a missing snapshot: the baseline has not been created at the expected path, or the test name/path changed. Run the intended test with npx playwright test --update-snapshots, inspect the generated file, and verify its location and naming.
  • The JSON snapshot changes on every run: inspect timestamps, generated IDs, request-specific fields, and collection ordering. Normalize only fields that are outside the behavior being tested, and keep stable formatting.
  • The test snapshots an error response: assert the expected response status before parsing and comparing the body. Check the endpoint, test configuration, and service availability rather than accepting an unexpected error payload as the new baseline.
  • Snapshot update rewrites many files: confirm you ran the intended project and tests, and check whether a test rename or snapshot path-template change altered the target paths. Review the diff before committing; do not blindly accept broad changes.
  • Accessibility output is not accepted as JSON: confirm whether the test is using a JSON-returning ariaSnapshotJSON() API or the YAML-template matcher toMatchAriaSnapshot(). They serve different purposes and have different representations.
  • Screenshot assertions differ across machines: compare browser, operating system, dependency, and rendering environments, then use the screenshot assertion controls for known dynamic areas. Keep visual baselines and their review environment consistent.

Or skip the browser setup

If what you need is a rendered website capture rather than a Playwright-managed JSON baseline, ScreenshotNeo can return a screenshot or PDF from one GET request. It is not a replacement for toMatchSnapshot() when the expected artifact is serialized JSON. Its capture flow can accept cookie/consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before taking a shot; each step can be turned off. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers report the page verdict and billing status. It also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients.

Example cURL request for a WebP capture of Stripe (replace the example target URL or API key as needed):

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 documentation for request options. Its free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, with no card required.

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

Frequently Asked Questions

Does naming a snapshot file with a .json extension make Playwright validate JSON structure?

No. The generic matcher compares the serialized text (or arbitrary binary data); your test is responsible for parsing, normalizing, and serializing JSON.

Should I use an accessibility snapshot instead of a JSON data snapshot?

Only when accessibility structure is the behavior you intend to check. A response or application data contract is a different target from the page’s accessible structure.

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.