ScreenshotNeo

BlogHow-to

How to Include Playwright Screenshots in Test Report Steps

Attach Playwright screenshots to individual test steps with step.attach(), choose the right scope, and make them visible in HTML reports.

By the ScreenshotNeo team30 September 20268 min read

How to Include Playwright Screenshots in Test Report Steps

Use the callback argument from test.step(), capture the page as a buffer, and call step.attach() with contentType: 'image/png'. This associates the image with that specific step instead of the entire test.

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

test('checkout shows confirmation', async ({ page }) => {
  await page.goto('https://example.com/checkout');

  await test.step('verify confirmation page', async step => {
    const screenshot = await page.screenshot();

    await step.attach('confirmation screenshot', {
      body: screenshot,
      contentType: 'image/png',
    });

    await expect(
      page.getByRole('heading', { name: 'Order confirmed' })
    ).toBeVisible();
  });
});

TestStepInfo.attach() was added in Playwright 1.51. It accepts either body or path, never both. The awaited call copies the attachment to a reporter-accessible location, so a temporary file can be removed after the call completes. See the TestStepInfo API for the exact contract.

Step-level and test-level attachments

Playwright has two attachment scopes:

A screenshot buffer becomes evidence attached to one test step.
A screenshot buffer becomes evidence attached to one test step.
Scope API Use it when
Individual step step.attach() The screenshot explains one action or assertion inside test.step().
Whole test testInfo.attach() The image represents the final state, a failure, or evidence for the complete test.

The callback receives a TestStepInfo object. Name the step clearly, then attach evidence while the page is in the state that the step describes.

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

test('profile update', async ({ page }, testInfo) => {
  await page.goto('https://example.com/profile');

  await test.step('save profile changes', async step => {
    await page.getByLabel('Display name').fill('Ada Lovelace');
    await page.getByRole('button', { name: 'Save' }).click();

    const image = await page.screenshot({ fullPage: false });
    await step.attach('saved profile', {
      body: image,
      contentType: 'image/png',
    });
  });

  const finalImage = await page.screenshot({ fullPage: true });
  await testInfo.attach('complete profile page', {
    body: finalImage,
    contentType: 'image/png',
  });
});

The TestInfo API documentation describes the test-level form. Do not substitute it when the report needs the image nested under a particular step.

Complete setup with the HTML reporter

  1. Install Playwright Test and its browsers in your project.
  2. Use Playwright 1.51 or newer for step attachments.
  3. Put the screenshot call inside the test.step() callback.
  4. Run the test with the HTML reporter.
  5. Open the generated report.
npx playwright test --reporter=html
npx playwright show-report

The HTML reporter writes a self-contained report folder, normally playwright-report. Its output directory and opening behavior can be configured in your Playwright setup or with the documented environment variables. Consult the Playwright reporters documentation for those settings.

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

export default defineConfig({
  reporter: [['html', {
    outputFolder: 'playwright-report',
    open: 'never',
  }]],
});

Run npx playwright show-report playwright-report when you want to inspect a report from a specific directory. In continuous integration, archive that directory as a build artifact so the attachments remain available after the job finishes.

Screenshot input: buffer or file path

A buffer is usually the simplest option because page.screenshot() returns one when no path is supplied. It avoids naming temporary files and makes the attachment operation synchronous from your test’s point of view.

await test.step('capture viewport', async step => {
  const png = await page.screenshot({
    type: 'png',
    animations: 'disabled',
  });

  await step.attach('viewport', {
    body: png,
    contentType: 'image/png',
  });
});

Use a path when another tool already created the image or when you need to keep the file independently of the report.

import path from 'node:path';

await test.step('attach existing artifact', async step => {
  const file = path.join('artifacts', 'confirmation.png');
  await page.screenshot({ path: file, type: 'png' });

  await step.attach('confirmation file', {
    path: file,
    contentType: 'image/png',
  });
});

Do not provide both body and path. Also provide an explicit content type for an in-memory PNG so reporters and downstream tooling can interpret it correctly.

Choosing the right screenshot scope

Capture only the evidence that makes the step understandable. Smaller images are faster to copy and easier to inspect.

Viewport screenshot

const image = await page.screenshot({
  fullPage: false,
  type: 'png',
});

This is useful for a visible toast, modal, navigation state, or the portion of a form that changed.

Full-page screenshot

const image = await page.screenshot({
  fullPage: true,
  type: 'png',
});

Use fullPage: true for long documents or pages where content below the fold is the evidence. Long images can make reports slower to load and harder to scan, so prefer an element capture when one component is sufficient.

Element screenshot

const image = await page
  .getByTestId('order-summary')
  .screenshot({ type: 'png' });

await step.attach('order summary', {
  body: image,
  contentType: 'image/png',
});

Locator screenshots are appropriate for a card, table, dialog, or error message. Use stable locators such as roles, labels, or test IDs rather than brittle CSS paths.

Controlling visual noise

const image = await page.screenshot({
  animations: 'disabled',
  caret: 'hide',
  scale: 'css',
  type: 'png',
});

Disable animations when motion would make evidence inconsistent. Keep PNG for readable UI text and lossless debugging; choose another format only when your reporter and review workflow support it.

Attach screenshots on failure

Attaching every image can increase report size. A common pattern is to capture step evidence only for important checkpoints and attach a final screenshot when a test fails.

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

test('checkout flow', async ({ page }, testInfo) => {
  await page.goto('https://example.com/checkout');

  try {
    await test.step('submit order', async step => {
      await page.getByRole('button', { name: 'Place order' }).click();
      const image = await page.screenshot();
      await step.attach('after submit', {
        body: image,
        contentType: 'image/png',
      });
    });
  } finally {
    if (testInfo.status !== testInfo.expectedStatus) {
      const failureImage = await page.screenshot({ fullPage: true });
      await testInfo.attach('failure state', {
        body: failureImage,
        contentType: 'image/png',
      });
    }
  }
});

Keep the screenshot operation inside the try or finally path where the page is still available. If the browser has already crashed, no capture method can produce an image.

Reporter behavior and CI details

Playwright documents that “Some reporters show test step attachments.” An attachment can therefore be correctly recorded while being presented differently, or not visibly, in another reporter. Verify the reporter you use before relying on a particular layout.

The built-in HTML reporter is the clearest way to inspect nested step evidence. In CI, publish the complete report directory, including its data files and attachments. Copying only an HTML shell can produce missing images or broken links.

Common errors and fixes

Symptom Cause Fix
step.attach is not a function The installed Playwright version predates step attachment support. Upgrade to Playwright 1.51 or newer and reinstall the package and browsers if your project requires it.
Image is attached to the test, not the step testInfo.attach() was called instead of the callback’s step.attach(). Move the call inside test.step('...', async step => { ... }).
Reporter cannot identify the image The content type was omitted or incorrect. Set contentType: 'image/png' for PNG bytes.
API rejects the attachment options Both body and path were supplied. Choose exactly one input form.
Attachment is missing from a report The selected reporter does not render step attachments, or the CI artifact is incomplete. Try the HTML reporter and archive the entire report output directory.
Screenshot captures the wrong state The page was still loading, an animation was active, or the assertion ran before the UI settled. Wait for a meaningful locator, disable animations, and capture after the action that defines the step.
Full-page image is huge The page contains long content or many high-resolution images. Capture the relevant locator, use viewport scope, or reduce the number of checkpoints.
Choose full-page, viewport, or element scope, and remove distracting overlays before capture.
Choose full-page, viewport, or element scope, and remove distracting overlays before capture.

Reliability and performance checklist

  • Use deterministic test data and stable locators so the captured state is meaningful.
  • Wait for the specific heading, status, or component that proves the step completed.
  • Prefer element or viewport captures for routine steps; reserve full-page images for document evidence.
  • Disable animations and hide the caret when visual noise affects review.
  • Use unique, descriptive attachment names. Names such as confirmation screenshot are easier to find than image1.
  • Attach at checkpoints that explain a user journey, rather than after every click.
  • Keep report artifacts for the same browser, commit, and test run together.
  • Expect screenshot capture to add browser work and report storage. Measure your suite’s runtime and artifact size after adding frequent captures.

Visual comparison is a different feature

An attached screenshot is evidence for a report. It does not compare the image with an expected baseline. For visual regression, use Playwright’s screenshot assertions such as toHaveScreenshot(); attach a separate image when a human needs context around the assertion.

Or skip the browser setup

If you need a clean image from a URL outside the test browser, ScreenshotNeo provides a single screenshot API request. Its capture process accepts cookie and consent banners like a visitor, then removes more than 60 known consent platforms, newsletter popups, and chat widgets before the shot. Each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and whether the request was billed.

See the ScreenshotNeo API documentation for all options, including full-page and element captures, device presets, dark mode, custom CSS and JavaScript, waits, request blocking, headers, cookies, geolocation, PDF output, caching, signed links, asynchronous jobs, bulk capture, and usage data.

cURL

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

Python

import requests

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

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}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const buffer = Buffer.from(await res.arrayBuffer());
require('node:fs').writeFileSync('shot.webp', buffer);

An MCP server also exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients. Free accounts include 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

Cost and operational notes

Playwright screenshots consume your own CI browser time and artifact storage. ScreenshotNeo charges only for clean shots; failed loads and the other non-clean outcomes listed above are free, and headers let you audit the result. Its plans are Free (1,000 per month), Starter ($5 for 3,000), Growth ($15 for 15,000), Pro ($39 for 60,000), Scale ($99 for 250,000), and Business ($249 for 1,000,000). Yearly billing gives two months free, and every feature is available on every plan.

FAQ

Can I attach a JPEG instead of a PNG?

Yes. Capture the requested format and set the matching MIME type, such as image/jpeg. PNG is the documented example and is usually best for UI text.

Can one step have multiple screenshots?

Yes. Call step.attach() more than once with distinct names, for example a viewport image and an element image.

Why does the image not appear in my reporter?

Step attachment rendering depends on the reporter. Playwright explicitly says some reporters show test step attachments; use the HTML reporter when you need a browsable view.

Should I attach before or after the assertion?

Attach after the action and any waits that establish the evidence. Put it before the assertion if you want the exact state that the assertion will inspect, or after it if the assertion itself changes the page.

Can I reuse the screenshot buffer elsewhere?

Yes. A buffer can be attached, written to disk, or passed to an image-diff tool. The screenshot operation and visual comparison remain separate concerns.