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

Use Mocha’s afterEach() hook to save a screenshot when the current test fails, while the Selenium WebDriver session is still open. In JavaScript, driver.takeScreenshot() returns a promise containing a base64-encoded PNG; write that value to a file with base64 encoding. This captures the browser’s current page state, not necessarily a full-page image in every browser or driver.

Capture the failed test in Mocha’s afterEach() hook

Mocha runs afterEach() after each test and before the suite-level after() teardown hook. That makes it the right place to inspect the test result and capture the page before quitting the browser. See Mocha’s hook documentation and Selenium’s JavaScript WebDriver API.

The example below is for a suite that creates and owns one driver. It assumes the project uses Mocha’s BDD interface and a Selenium JavaScript WebDriver version with takeScreenshot(). Add the hook to the suite where driver is defined, or adapt it to your project’s shared driver fixture.

import fs from 'node:fs/promises';
import path from 'node:path';

const screenshotDir = 'artifacts/screenshots';
let driver;

function safeName(title) {
  return title.replace(/[^a-z0-9-_]+/gi, '_').slice(0, 120) || 'unnamed-test';
}

afterEach(async function () {
  const test = this.currentTest;
  if (test?.state !== 'failed' || !driver) return;

  await fs.mkdir(screenshotDir, { recursive: true });
  const image = await driver.takeScreenshot();
  const filename = `${safeName(test.fullTitle())}.png`;
  await fs.writeFile(path.join(screenshotDir, filename), image, 'base64');
});

after(async function () {
  if (driver) await driver.quit();
});

This is an implementation pattern, not a claim that the snippet has been run against your installed versions. Make sure the file uses a module format supported by your Node.js project, and that afterEach and after are available through your chosen Mocha setup. The regular function declaration matters: Mocha supplies the current test through the hook context, while an arrow function does not receive Mocha’s own this.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Why the hook checks the test state

this.currentTest identifies the test associated with the hook, and its state is checked for failed before any file work occurs. Without that guard, the hook would save an image after successful tests too, which can generate unnecessary artifacts and obscure the failures you need to investigate. Confirm the hook context and state behavior with the Mocha version and configuration in your project.

Why the browser must still be open

The screenshot call needs a live WebDriver session. Selenium documents that quit() ends the session, so put the capture in afterEach() and leave driver.quit() for the later suite teardown. A screenshot attempt after quitting cannot retrieve the failed page. Selenium’s API describes screenshot capture as best effort and returns a base64-encoded PNG; browser and driver behavior can affect what appears in the image.

Save and identify screenshot files reliably

The example creates artifacts/screenshots recursively so the first failure does not fail simply because the output directory is missing. It sanitizes the test’s full title for use in a filename and limits its length. The 'base64' argument tells Node’s file-writing API to decode the string as image bytes rather than saving the base64 text itself. Selenium’s browser-interaction documentation demonstrates writing a screenshot this way: Working with windows and tabs.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Avoid collisions with retries and parallel workers

A test title alone may not uniquely identify an artifact. A retried test can fail more than once, and separate workers can run tests with identical full titles. In those setups, add a retry number, worker identifier, timestamp, or other unique value to the filename. For example, the naming policy can include test.currentRetry() where appropriate for your Mocha version, plus a worker-specific value supplied by your test runner. Ensure the added values are safe for filenames. This is practical artifact-management guidance; the cited framework documentation does not prescribe a naming scheme.

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

If your CI system collects artifacts, configure it to retain the screenshot directory when a job fails. Keep the path stable across local runs and CI so developers know where to find the image. Consider retention and storage limits before keeping every artifact indefinitely.

What this screenshot does—and does not—show

A WebDriver screenshot records the browser’s current page view at the time takeScreenshot() runs. It is useful for checking visible layout, overlays, navigation state, and other visual clues around a failed assertion. It does not automatically explain why the test failed, and it may not include the entire document: full-page behavior depends on the browser and driver implementation. If a failure changes the page immediately, capture in the hook before other teardown code navigates away or alters the browser state.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

For a more complete failure artifact, you can save additional diagnostics in the same hook, such as the current URL or test title, subject to your project’s privacy and logging rules. Screenshots may contain account details, personal information, tokens, or other sensitive content visible in the browser. Restrict access to test artifacts and avoid capturing production user data.

Choose a custom hook or an existing package

Approach When it fits Trade-offs to check
Custom afterEach() hook You want a small implementation that fits the driver and artifact conventions already in your test suite. You control filenames, output paths, and which diagnostics to collect, but you must handle directory creation, unique names, cleanup, and any extra logs yourself.
Package already used by the suite Your project already uses mocha-webdriver and its debug-capture configuration is relevant. The npm listing describes automatic logs and screenshots after failed test cases when debug capture and MOCHA_WEBDRIVER_LOGDIR are configured. Check the current package documentation, maintenance, configuration, and compatibility with your installed Mocha and Selenium versions before relying on it: mocha-webdriver on npm.

Do not add a package solely to avoid a short hook without first checking how it fits your existing driver lifecycle, retry strategy, parallel workers, output directory, and CI artifact collection. The package listing is a lead to investigate, not proof of compatibility with a particular project or current release.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Troubleshoot missing or unusable screenshots

No file appears

  • Confirm the test actually failed and that the hook runs for the suite in question. A hook in one suite does not automatically apply to every unrelated suite.
  • Check that driver is defined in the hook’s scope and still refers to the active session.
  • Inspect the test output for errors from mkdir, takeScreenshot(), or writeFile(). The hook can itself fail if the session has ended or the path is not writable.
  • Verify the working directory used by the test runner. The relative path artifacts/screenshots is relative to the process working directory, which may differ between a local shell and CI.

The hook says the test state is unavailable

Use a regular function () {} for the hook so Mocha can provide its context, and verify that the project uses the BDD interface assumed by the example. Check the installed Mocha API and test organization if hooks are wrapped by a custom runner or shared fixture.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

The PNG is invalid or contains encoded text

Write the returned string with the 'base64' encoding argument, as shown. Omitting it can save the base64 representation as text rather than decoding it into PNG bytes. Do not add a data-URL prefix unless your own code has introduced one; Selenium’s documented return value is the base64 image data.

The screenshot shows the wrong page or is blank

Check whether another teardown step navigates, closes a tab, or quits the driver before capture. Keep screenshot capture early in the failure teardown sequence, then inspect how the test leaves the browser and whether the active window is the expected one. Selenium describes this operation as best effort, so a screenshot is not guaranteed to resolve every browser or driver issue.

Artifacts overwrite one another

Add a unique component to the filename when retries or parallel workers are enabled. A sanitized test title prevents many unsafe filename characters, but it does not prevent duplicate titles from colliding.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server, useful when you need a screenshot of a URL without setting up Selenium for that capture. It is not a substitute for the live browser session in a failing end-to-end test: use the hook above when you need the precise state produced by that test. ScreenshotNeo’s URL-based capture can be called like this; see the ScreenshotNeo documentation for API details.

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 the shot; each cleanup step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server lets AI agents use screenshot tools, and the free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan.

Keep the failure artifact useful

Start with the smallest reliable change: add a failure-only afterEach() hook, save the base64 PNG before teardown, and ensure filenames remain unique under the way your suite actually runs. If you are diagnosing a test, preserve that test’s Selenium session state; a separate URL screenshot service is for captures where a fresh page load is what you want.

Frequently Asked Questions

Does Selenium’s JavaScript screenshot API return JPEG or PNG?

The documented takeScreenshot() result is base64-encoded PNG data.

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

Can I capture screenshots after every test instead of only failures?

Yes. Remove the failed-state guard in the hook, but expect a file for each test and plan artifact volume and retention accordingly.

Can I use the hook if each test creates its own WebDriver?

Yes, but reference the driver associated with the current test rather than a suite-level shared variable, and capture it before that test’s teardown quits the session.

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.