Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
automated testing

How to Attach Puppeteer Failure Screenshots to Cucumber HTML Reports

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

In Cucumber.js, capture the page in an After hook, check that the scenario failed, then attach the screenshot bytes with the image/png media type. The built-in HTML formatter renders attachments in the report. The key requirement is lifecycle: your page must still be open and accessible from the scenario’s World when the hook runs.

Attach a screenshot only when a scenario fails

Use Cucumber.js support code rather than adding screenshot steps to every feature. An After hook runs after each scenario, and its result lets you return immediately for passing, skipped, or otherwise non-failed scenarios. For a failed scenario, await both the screenshot and the attachment so Cucumber has the image before the test case finishes.

const { After, Status } = require('@cucumber/cucumber');

After(async function (testCase) {
  if (testCase.result.status !== Status.FAILED) return;

  // Adapt this property to the page stored by your World.
  const screenshot = await this.page.screenshot({ type: 'png' });
  await this.attach(screenshot, {
    mediaType: 'image/png',
    fileName: 'failure.png',
  });
});

This example assumes your project stores its Puppeteer Page as this.page. That property is not a built-in Cucumber or Puppeteer field: change it to match your World implementation. Likewise, make sure the hook’s this is the scenario World, not an arrow function’s lexical context. A regular function, as above, receives the World as its context.

Puppeteer returns screenshot data as binary by default; the documented binary result is a Uint8Array. Cucumber.js accepts image and binary attachments, including a Buffer. Passing the returned bytes directly avoids a needless base64 conversion. The fileName is useful for identifying the attachment, while the media type tells the formatter how to display it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • 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

Use the failure status deliberately

The status check is what makes this a failure-only capture. Do not test a truthy value or assume every non-passing outcome should be treated as a failure; compare with Cucumber’s Status.FAILED. If your own test runner or wrapper changes the hook argument shape, inspect the result object it supplies and adapt the condition rather than silently omitting the check.

Keep the page alive through the hook

The browser and page must remain available until the After hook has completed. If teardown closes the page first, page.screenshot() cannot capture it. Arrange lifecycle ordering so screenshot capture happens before page or browser shutdown. The specific fixture and World design are project choices; Cucumber’s hook API does not create or retain your Puppeteer page automatically.

Configure the Cucumber HTML report

Select the built-in HTML formatter in the Cucumber.js configuration and give it an output file. For a CommonJS configuration, for example:

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • 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
module.exports = {
  format: [
    'progress',
    ['html', 'cucumber-report.html'],
  ],
};

The HTML formatter renders attachments from the test run. By default, it embeds attachment data in the report, so the HTML file can be moved and viewed without a separate image directory. That portability has a size cost: numerous or large screenshots make the report larger.

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

Externalize image files for a smaller HTML document

If your workflow can keep the generated attachment files alongside the report, configure external attachments instead:

module.exports = {
  format: [['html', 'cucumber-report.html']],
  formatOptions: {
    html: {
      externalAttachments: ['image/*', 'video/*'],
    },
  },
};

The array limits externalization to matching content types. Setting externalAttachments: true externalizes all supported attachment types; log and link attachments are not externalized. With external files, preserve the formatter’s output structure when copying or publishing the report, or its image references may no longer resolve.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • 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.

Choose the capture point: scenario or failing step

An After hook captures the page state at scenario teardown, which is usually appropriate when one final diagnostic image per failed scenario is enough. If you need the state immediately after the step that failed, use an AfterStep hook and check that step’s result before capturing. Cucumber.js documents this result-check pattern for step hooks too.

These are different debugging records, not interchangeable timings. By the time an After hook runs, later cleanup or steps may have changed the page. An AfterStep capture is closer to the failure point, but can produce more attachments if your project’s step behavior or retry strategy permits multiple failures. Select the hook that matches the question your report needs to answer.

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

Pick binary or base64 data

Binary is the straightforward choice when calling Puppeteer directly: await page.screenshot() and give its result to this.attach with mediaType: 'image/png'. Use base64 only when an existing helper already produces that representation or another interface requires text.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • 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
const screenshotBase64 = await this.page.screenshot({
  type: 'png',
  encoding: 'base64',
});

await this.attach(screenshotBase64, {
  mediaType: 'base64:image/png',
  fileName: 'failure.png',
});

The base64: prefix is part of the media type for a base64 string attachment. Do not label a base64 string as ordinary image/png binary, or pass binary bytes as though they were base64 text. A mismatch can prevent the report from decoding the image correctly.

Choose a useful screenshot scope

A default screenshot captures the current visible page. For a failure caused by content below the fold, request a full-page screenshot:

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

Full-page capture can make an image much taller and larger, so use it when page-wide context matters rather than as an automatic default. Puppeteer also supports clipping a region and taking an element screenshot; those options can focus a report on a particular component when the failure is localized. Use the page or element capture options appropriate to the actual failure, and keep the same Cucumber attachment call after obtaining the bytes.

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.
Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【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.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Handle screenshot errors without hiding the test failure

A failure screenshot is diagnostic evidence, not the test’s primary result. A page can close before capture, a browser process can fail, or the capture itself can reject. Decide how your project handles that secondary error, but avoid letting it obscure the original scenario failure.

After(async function (testCase) {
  if (testCase.result.status !== Status.FAILED) return;

  try {
    const screenshot = await this.page.screenshot({ type: 'png' });
    await this.attach(screenshot, {
      mediaType: 'image/png',
      fileName: 'failure.png',
    });
  } catch (error) {
    // Replace with your project's logger. Keep the scenario failure visible.
    console.error('Could not attach failure screenshot:', error);
  }
});

This policy allows the hook to finish when capture fails, while retaining an explicit log of why no image appeared. If your CI system treats hook errors as a distinct failure, adapt the policy to your conventions, but report the screenshot error separately from the assertion or step failure.

Troubleshoot a missing or unusable image

  • No attachment appears: Confirm the hook is loaded as Cucumber support code, the scenario status is FAILED, and the hook reaches this.attach. Check that the screenshot promise and attachment promise are both awaited.
  • The hook cannot find this.page: Replace the example property with the one your World sets, and ensure the page is initialized for that scenario. Avoid an arrow function for the hook if you rely on Cucumber’s World as this.
  • Capture reports a closed target or page: Reorder teardown so the failure hook can capture before closing the page or browser. If closure is intentional, log the capture error without replacing the original failure.
  • The report shows an attachment but not an image: Pass raw screenshot bytes with image/png, or a base64 string with base64:image/png. Ensure the screenshot format and media type agree.
  • The report HTML opens but images are broken: If attachments are externalized, publish or copy their generated files along with the HTML in the formatter’s expected layout. Embedded attachments do not have this separate-file dependency.
  • The report is unexpectedly large: Embedded screenshots increase HTML size. Externalize image or video attachments, or capture viewport-sized images instead of full-page images when full-page context is unnecessary.
  • The screenshot shows an unhelpful state: Check whether later steps or teardown have altered the page before an After hook. Use an AfterStep result check when the exact failing-step state is needed.

Or skip the browser setup

If the goal is a screenshot artifact rather than a Puppeteer page attached to a Cucumber scenario, ScreenshotNeo offers a one-request screenshot API. It does not replace the hook’s access to the live failing page or automatically attach an image to a Cucumber report; use the do-it-yourself hook above when that integration is required. API options and usage are documented at ScreenshotNeo’s API documentation.

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

ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, and failed loads are never billed. An MCP server lets AI agents take screenshots, and the free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for the free plan.

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

Frequently Asked Questions

Can I attach a screenshot from a Puppeteer wrapper instead of calling page.screenshot directly?

Yes. If the wrapper exposes a screenshot method that returns image bytes, await it in the hook and pass the result to Cucumber’s attachment method with the matching image media type.

Will an HTML report with embedded screenshots work when shared as one file?

Embedded attachment data is included in the HTML by default, so it does not depend on separate image files.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.