Samelogic Logo
ComparePricing

Playwright Screenshots That Help You Debug Failures

Learn Playwright screenshot commands, failure settings, file paths, visual comparisons, and when a trace gives the missing context.

Playwright Screenshots That Help You Debug Failures

A Playwright screenshot can capture the current viewport, the full scrollable page, or one element. Playwright Test can also attach a screenshot automatically when a test fails. The useful choice depends on the question the next person needs to answer.

Use a viewport screenshot for the screen the user saw. Use fullPage: true when the relevant state may sit below the fold. Use a locator screenshot when one component is the subject. Configure screenshot: 'only-on-failure' when you want automatic evidence from failed tests without saving an image for every passing run.

That covers the commands. The harder question is whether the resulting image explains the failure. We ran a controlled browser experiment to show where each screenshot scope helps and where a trace or request record becomes necessary.

Take a basic Playwright screenshot

The shortest form saves the visible viewport to the path you provide.

Playwright screenshots example 1

(TypeScript)

await page.screenshot({ path: 'artifacts/checkout.png' });

If you omit path, Playwright returns a buffer instead of writing a file. That is useful when a reporter, object store, or image comparison service should receive the bytes directly.

Playwright screenshots example 2

(TypeScript)

const image = await page.screenshot();
await testInfo.attach('checkout', {
  body: image,
  contentType: 'image/png',
});

A path should be unique when tests run across projects or workers. A fixed path such as screenshot.png can be overwritten by a later browser or parallel test. testInfo.outputPath() creates a path inside that test's output directory and avoids collisions.

Playwright screenshots example 3

(TypeScript)

const path = testInfo.outputPath('checkout.png');
await page.screenshot({ path });

This path behavior matters in CI. If the image is created but the test output directory is not uploaded as an artifact, the screenshot still disappears when the worker exits.

Choose viewport, full page, or element capture

Each scope answers a different question.

Screenshot scope

Playwright call

Best question

Common weakness

Viewport

page.screenshot()

What was visible when the test stopped?

Content below the fold is absent

Full page

page.screenshot({ fullPage: true })

Did another section of the page expose the mismatch?

Tall images can bury the failing area

Element

locator.screenshot()

What did this component render?

Surrounding page state is removed

Failure attachment

Configured in use.screenshot

What was visible when the assertion failed?

The image may show the symptom but not its cause

Visual comparison

expect(page).toHaveScreenshot()

Did rendered pixels change from the approved baseline?

A pixel difference does not explain the state transition

For a full-page screenshot:

Playwright screenshots example 4

(TypeScript)

await page.screenshot({
  path: testInfo.outputPath('full-page.png'),
  fullPage: true,
});

For a single component:

Playwright screenshots example 5

(TypeScript)

await page
  .getByRole('region', { name: 'Billing settings' })
  .screenshot({ path: testInfo.outputPath('billing-settings.png') });

Prefer the smallest scope that still includes the evidence. A focused component is faster to scan than a long page, but it should not remove the workspace name, permission banner, locale, or other nearby state that changes the interpretation.

Configure screenshots on failure

Playwright Test supports automatic screenshot capture through the use section of the config. The direct choice for most suites is only-on-failure.

Playwright screenshots example 6

(TypeScript)

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

export default defineConfig({
  use: {
    screenshot: 'only-on-failure',
    trace: 'retain-on-failure',
  },
});

Current Playwright also supports on-first-failure, which is useful with retries because it captures the first failed attempt rather than waiting for the final result. Keep the trace strategy aligned with the same diagnostic goal. A screenshot gives the final visual state. A retained trace adds actions, DOM snapshots, console output, requests, responses, and source locations.

Do not add a custom afterEach hook unless the built-in modes cannot express what you need. A custom hook can capture a named region, mask sensitive content, or attach extra metadata, but it also adds failure handling that your team must maintain.

Our controlled screenshot experiment

We created a synthetic renewal-settings page with no customer data. The visible page said the active workspace was Northwind. Pressing Save settings sent a request for Acme and rendered Saved to Acme. The assertion expected Saved to Northwind, so the test stopped on a real state mismatch.

The same Playwright 1.63.0 run produced four PNG files and one retained trace.

Artifact

Dimensions

File size

What it showed

Viewport screenshot before save

1280 × 720

15,758 bytes

Northwind workspace and the top of the settings flow

Full-page screenshot before save

1280 × 2073

48,924 bytes

The complete scrollable page, including irrelevant lower space

Settings-card screenshot before save

804 × 333

12,343 bytes

The focused billing component without the page-level workspace heading

Automatic failure screenshot

1280 × 720

18,558 bytes

Northwind at the top and Saved to Acme after the failed action

Retained trace

Not a PNG

78,681 bytes

The action sequence and diagnostic browser context for the failed run

The failure screenshot was the best single image because it kept the page-level Northwind context and the Acme result together. The element screenshot was smaller, but it removed the workspace heading that made the result contradictory. The full-page image preserved everything and made the relevant state harder to find.

The request record contained the decisive payload:

Playwright screenshots example 7

(JSON)

{
  "method": "POST",
  "url": "/api/save",
  "body": {
    "workspace": "acme",
    "renewalDate": "2026-09-30"
  }
}

The image proved that the browser displayed conflicting workspace states. It did not prove which request produced the result. That is why the trace and request record mattered to the engineer receiving the failure.

Screenshots and visual comparisons are different jobs

page.screenshot() records pixels at one moment. expect(page).toHaveScreenshot() compares the rendered page or element with a stored reference image.

Use a visual comparison when the question is whether layout, color, spacing, typography, or another rendered detail changed. Use a diagnostic screenshot when the question is what the user or test saw at a particular failure point.

Playwright warns that screenshot baselines can vary across operating systems, browser versions, fonts, settings, hardware, power conditions, and headless modes. Generate and compare baselines in a consistent environment. Then mask or style genuinely dynamic regions rather than raising the difference threshold until meaningful changes disappear.

For a deeper workflow on reducing false pixel noise, read Visual Regression Testing Without Noisy Screenshot Diffs.

When a screenshot is not enough

A screenshot is strong evidence for rendered state. It is weak evidence for the path that produced that state.

Add a trace, focused request record, console output, or deliberately recorded browser path when the receiver needs to know:

  • which action first changed the page;

  • whether an earlier workspace, role, locale, or permission remained active;

  • which request and response produced the visible state;

  • whether a redirect, popup, iframe, or new tab changed the execution path;

  • why the same final screen behaves differently after a fresh page load;

  • whether a retry removed the condition that caused the first failure.

Start with the screenshot because it is easy to scan. Then give the receiver the smallest additional artifact that answers the missing question. Our Playwright Trace Viewer workflow shows how to move from the last visible symptom to the first contradiction. If a test passes alone and fails in a suite, use the browser-context isolation workflow before increasing timeouts.

A practical screenshot policy for Playwright suites

A useful default policy is short enough for a team to follow:

  1. Save screenshots automatically on failure, not on every passing test.

  2. Keep the viewport stable and record the browser, project, and environment.

  3. Use unique output paths so parallel projects cannot overwrite one another.

  4. Capture a focused element only when its surrounding state is not part of the explanation.

  5. Add full-page capture when the relevant evidence can appear outside the viewport.

  6. Retain a trace for failures where actions, requests, console output, or page history matter.

  7. Upload the test output directory in CI and verify the receiver can open it.

  8. Mask secrets and personal data before screenshots leave the test environment.

The goal is not to collect the largest bundle. It is to preserve enough context for the person fixing the issue to act without recreating the entire browser path.

Hand off the browser path when the image stops short

Screenshots work best as a fast visual anchor. For state-dependent failures, the receiving engineer often needs the earlier browser steps too.

The team behind Samelogic built CSS Selector & XPath Finder for deliberately initiated browser capture. Start capture before repeating the bounded flow, play the steps back, jump to the failing moment, and send the available browser context to the teammate reviewing or fixing it. It is not passive session replay, and it does not replace Playwright screenshots, traces, or visual comparisons.

Use the screenshot for what it proves. Use the recorded path when the cause lives before the final frame.

Sources

Related workflows

Move from editorial context into the selector, Playwright, and bug-reproduction pages that turn exact UI evidence into action.

Capture browser proof before the handoff gets vague.

Select the exact element, record the replay, and give QA, product, and engineering a test artifact they can act on without another clarification loop.

Install the Chrome Extension
Visual
Semantic
Behavioral

Used by teams at

  • abbott logo
  • accenture logo
  • aaaauto logo
  • abenson logo
  • bbva logo
  • bosch logo
  • brex logo
  • cat logo
  • carestack logo
  • cisco logo
  • cmacgm logo
  • disney logo
  • equipifi logo
  • formlabs logo
  • heap logo
  • honda logo
  • microsoft logo
  • procterandgamble logo
  • repsol logo
  • s&p logo
  • saintgobain logo
  • scaleai logo
  • scotiabank logo
  • shopify logo
  • toptal logo
  • zoominfo logo
  • zurichinsurance logo
  • geely logo