ScreenshotNeo

BlogHow-to

How to Use Playwright Screenshot Snapshots with a Custom Test Name

Name a Playwright screenshot baseline with toHaveScreenshot(), or build a reusable path from the test title with snapshotPathTemplate.

By the ScreenshotNeo team4 October 20266 min read

To give a Playwright screenshot snapshot a custom name, pass a filename to toHaveScreenshot():

await expect(page).toHaveScreenshot('checkout-summary.png');

To include the test title in the snapshot path automatically, configure snapshotPathTemplate with {testName}. These controls do different jobs: the assertion argument supplies the snapshot name, exposed as {arg} in the template; {testName} comes from the test title, including parent describe titles and excluding the test file name.

This guide covers both naming methods, runnable examples, baseline updates, version considerations, troubleshooting, and when an external screenshot API may be a better fit.

1. Choose the naming method

What you need Use What it controls
A semantic name for one screenshot assertion toHaveScreenshot('checkout-summary.png') The explicit filename or relative path passed to the assertion.
A consistent folder and filename pattern based on test titles snapshotPathTemplate with {testName} The generated snapshot path, including title and other configured tokens.
Separate names for states captured by the same test Distinct assertion names, such as before.png and after.png Identifies each baseline separately.
Get the expected path for a named screenshot testInfo.snapshotPath(name, { kind: 'screenshot' }) Resolves the path using the screenshot snapshot configuration.

For a single descriptive baseline, an explicit assertion filename is usually enough. Use a path template when a naming or directory policy should apply across tests.

2. Give one screenshot assertion a custom name

Here is a complete Playwright Test example:

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

test('checkout totals update', async ({ page }) => {
  await page.goto('/checkout');
  await expect(page).toHaveScreenshot('checkout-totals.png');
});

The argument is the snapshot name. Playwright stores screenshots as PNG by default; a .webp extension selects WebP. You can also pass a relative path if you want a named subdirectory. Keep names stable and descriptive, and use different names when the test captures multiple meaningful states.

On the first run, Playwright creates the reference screenshot. Later runs compare the current screenshot to that reference. Review and commit intended baseline changes with the code that caused them. Run npx playwright test --update-snapshots when you deliberately want to update references.

3. Put the test title in the snapshot path

Set snapshotPathTemplate in the Playwright configuration when the test title should be part of the path:

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

export default defineConfig({
  snapshotPathTemplate: '{testDir}/__screenshots__/{testName}/{arg}{ext}',
});

Then name the assertion as usual:

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

test.describe('checkout', () => {
  test('totals update', async ({ page }) => {
    await page.goto('/checkout');
    await expect(page).toHaveScreenshot('totals.png');
  });
});

With this template, {testName} is the sanitized test title, including parent describe titles but not the test file name. {arg} is the assertion path without its extension, and {ext} includes the extension. In this example, those assertion tokens resolve to totals and .png.

Relative template paths resolve from the configuration directory. Other available tokens include {testFilePath}, {testFileDir}, {testFileName}, {testFileBaseName}, {testDir}, {snapshotDir}, {projectName}, and {platform}. When a token is empty, a single preceding character can be made conditional on its presence. See Playwright’s snapshotPathTemplate configuration reference for token details.

Choose tokens that make paths useful in your repository. Including project or platform can separate baselines when your configuration intentionally maintains separate references for those environments. Avoid adding path components without a reason: long paths are harder to navigate and may hit filesystem path limits.

4. Resolve a configured screenshot path in code

Use testInfo.snapshotPath() when code needs to determine where a screenshot reference belongs under the configured path rules:

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

test('checkout totals update', async ({ page }) => {
  const expectedScreenshot = test.info().snapshotPath(
    'checkout-totals.png',
    { kind: 'screenshot' },
  );

  console.log(expectedScreenshot);
  await page.goto('/checkout');
});

The kind: 'screenshot' option selects the screenshot path template associated with toHaveScreenshot(). The API documents this option as added in Playwright v1.53. Consult the TestInfo API reference if you need the exact behavior for your installed version.

5. Use the screenshot assertion for visual comparisons

For a page screenshot assertion, use await expect(page).toHaveScreenshot(). Playwright waits until consecutive screenshots match before comparing the final capture with the expected baseline. The assertion is part of the Playwright Test runner. The visual comparisons guide explains snapshot generation and comparison.

toMatchSnapshot() is a separate assertion intended for values such as strings or buffers. A screenshot buffer can technically be passed to it with a name, but for page screenshot comparisons, toHaveScreenshot() is the purpose-built assertion. See the toHaveScreenshot API.

6. Keep screenshot baselines repeatable

Visual baselines depend on the rendering environment. Operating system, browser version, settings, hardware, power source, and headless mode can all affect pixels. Generate and compare references in a consistent environment, including the same browser and project configuration in local development and CI where possible.

  • Commit reviewed baseline images so changes are visible in code review.
  • Update snapshots only when the visual change is intentional; inspect the diff first.
  • Keep test data and page state deterministic, including dates, animations, and network responses where relevant.
  • Use the documented stylePath option to hide or filter volatile elements during capture when appropriate.
  • Use descriptive names when one test captures more than one screen or state.

Playwright’s screenshot comparison guide describes baseline generation and rendering consistency considerations. Documentation is rolling; verify that the installed package supports a configuration option before relying on it. The documented versions include toHaveScreenshot(name) from v1.23, snapshotPathTemplate from v1.28, and the snapshotPath kind option from v1.53.

7. Troubleshooting

Symptom Likely cause Fix
The snapshot is still named automatically. The assertion has no explicit name, or you expected snapshotPathTemplate to replace the assertion argument. Pass a filename to toHaveScreenshot(). Configure a path template separately if you also need title-based directories.
The test title is missing from the path. The template does not include {testName}, or the installed Playwright version does not support the option. Add {testName} to snapshotPathTemplate and check the package version against the configuration reference.
The generated path differs from the one expected. The template tokens, relative base directory, project, or platform differ from your assumption. Inspect the configured template and resolve the path with test.info().snapshotPath(name, { kind: 'screenshot' }) on a version that supports it.
Playwright reports a visual diff on a machine that should match. Rendering environment or dynamic page content changed. Align browser, OS, settings, and test data. Filter volatile content using supported screenshot options such as stylePath.
A baseline file was unexpectedly replaced. The test was run with snapshot update mode. Review the changed image and rerun without --update-snapshots after accepting or reverting the update.
toHaveScreenshot is unavailable. The test is not using Playwright Test’s assertion setup, or the installed version is too old. Use @playwright/test and its expect, and confirm the installed version supports the assertion.

8. Or skip the browser setup

If you need a screenshot of a live URL without maintaining a Playwright browser setup, ScreenshotNeo provides a one-request screenshot API and an MCP server for developers. For a screenshot comparison workflow, Playwright remains the right place to define and check versioned test baselines; ScreenshotNeo is useful when you need to capture pages as image or PDF outputs.

Install the Python dependency with python -m pip install requests, then run this example:

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)

Equivalent cURL and Node.js examples are below. See the ScreenshotNeo documentation for API parameters and setup.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
  • Cookie banners are accepted and removed before capture; newsletter popups and chat widgets are removed too. Each step can be turned off.
  • Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing. Response headers report the page verdict and billing status.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.
  • The free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots.

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

9. FAQ

Does the test name include its parent describe titles?

Yes. The {testName} token includes parent describe titles and excludes the test file name.

Can I give two screenshots in one test different names?

Yes. Pass a distinct filename to each toHaveScreenshot() call so each visual state has its own reference.

Can I use WebP snapshots?

Yes. Use a filename with a .webp extension; PNG is the default.

Which Playwright version added custom snapshot paths?

toHaveScreenshot(name) was added in v1.23, snapshotPathTemplate in v1.28, and the snapshotPath kind option in v1.53. Check the API reference for your installed version.