Selenium Screenshots on Mocha Test Failure
When a Mocha test fails, a screenshot of the browser state at that exact moment is invaluable for debugging. This guide shows you how to automatically capture a Selenium WebDriver screenshot whenever a Mocha test fails, saving you time and making failures far easier to diagnose. You'll need a working Mocha test suite with Selenium WebDriver already set up.
What You'll Need
- Node.js and npm installed.
- A Mocha test suite (using
mochaas a dev dependency). - Selenium WebDriver (
selenium-webdrivernpm package) and a browser driver (e.g., chromedriver) configured. - Basic familiarity with Mocha's
afterEachhook and async/await.
Step-by-Step
- Create a screenshot directory – In your project root, create a folder to store screenshots, e.g.,
screenshots/. Ensure it exists before tests run; you can create it programmatically in your test setup. - Set up a global WebDriver instance – In your test file (or a helper module), create a driver instance that all tests share. For example:
const { Builder } = require('selenium-webdriver'); let driver; before(async () => { driver = await new Builder().forBrowser('chrome').build(); }); after(async () => { await driver.quit(); }); - Add an
afterEachhook to check test status – Mocha'safterEachruns after every test. Usethis.currentTestto check if the test failed. If it failed, take a screenshot with a filename that includes the test name and timestamp. - Write the screenshot capture code – Inside
afterEach, ifthis.currentTest.state === 'failed', calldriver.takeScreenshot()which returns a base64-encoded string. Save it to a file using Node'sfsmodule: - Generate a unique filename – Use the test title and a timestamp to avoid overwriting. Sanitize the test title to remove characters that are invalid in filenames (e.g., spaces, slashes).
- Write the screenshot file – Use
fs.writeFileSyncto save the base64 string as a PNG file. Example:const fs = require('fs'); const path = require('path'); afterEach(async function() { if (this.currentTest.state === 'failed') { const screenshot = await driver.takeScreenshot(); const filename = `${this.currentTest.title.replace(/[^a-z0-9]/gi, '_')}_${Date.now()}.png`; fs.writeFileSync(path.join('screenshots', filename), screenshot, 'base64'); console.log(`Screenshot saved: ${filename}`); } }); - Run your tests – Execute
npx mocha(or your npm test script). When a test fails, you'll see a log message with the screenshot filename. - Verify the screenshot – After the run, navigate to the
screenshots/folder and open the PNG to confirm it captures the browser state at the moment of failure.
Common Mistakes
- Forgetting to check
this.currentTest.state– If you take a screenshot on every test, you'll waste time and disk space. Always check for failure. - Using a single filename – Overwriting the same file with each failure means you lose evidence. Include a timestamp or unique identifier.
- Not sanitizing filenames – Test titles often contain spaces, colons, or slashes that break file paths. Replace non-alphanumeric characters with underscores.
- Screenshots taken after driver quit – Ensure the
afterEachhook runs before theafterhook that quits the driver. Mocha runs hooks in order:afterEachruns after each test, andafterruns once after all tests. - Async issues – If you don't await the screenshot and file write, the test may finish before the file is saved. Always use
await.
Tips
- Use a helper module – Put the screenshot logic in a separate file (e.g.,
screenshot.js) and import it in multiple test files to avoid duplication. - Include the test suite name – If you have multiple describe blocks, prepend the suite name to the filename for better organization.
- Add a timestamp with milliseconds – Using
Date.now()gives you a unique value even if two tests fail in the same millisecond (unlikely but possible). - Store screenshots in a CI artifact – If you run tests in CI, configure the pipeline to upload the screenshots folder as an artifact for easy access.
- Use a library like
mochawesome– If you want a more integrated reporting solution, consider using a reporter that automatically embeds screenshots on failure.
Troubleshooting
- Screenshot file is empty or corrupt – Ensure you're writing the base64 string correctly. The
takeScreenshot()method returns a base64-encoded PNG. When writing, use thebase64encoding option infs.writeFileSync. - Screenshot not taken at all – Check that your
afterEachhook is in the correct scope. If you place it inside adescribeblock, it only runs for tests within that block. Put it at the top level to cover all tests. - Driver is already quit – If you see an error like "Cannot call takeScreenshot after quit", ensure your
afterhook (which quits the driver) is defined after theafterEachhook. Mocha runs hooks in order of definition, so defineafterEachbeforeafter. - Permission errors on screenshot directory – Make sure the directory exists and is writable. You can create it in a
beforehook usingfs.mkdirSync('screenshots', { recursive: true }). - Tests are failing but no screenshot appears – Double-check that
this.currentTest.stateis indeed 'failed'. In some cases, if a test throws an uncaught exception, the state might be 'failed' but the hook might not run properly. Add a console log to verify the state.
Frequently Asked Questions
Can I take a screenshot on test success as well?
Yes, you can modify the condition to check for 'passed' or simply remove the state check to capture screenshots on every test. However, that will generate many files; it's usually better to only capture on failure.
How do I take a screenshot of a specific element instead of the full page?
Selenium's takeScreenshot() captures the full viewport. To capture a specific element, you can use a library like html2canvas in the browser, or use Selenium's ElementScreenshot feature if available (e.g., in Firefox). Alternatively, you can crop the full screenshot using an image processing library.
Does this work with parallel test execution?
Yes, but you need to ensure each worker has its own driver instance and unique screenshot filenames. Using a timestamp plus a worker ID (e.g., from the process.env) can prevent collisions.
Can I store screenshots in a cloud storage service?
Yes, after saving the file locally, you can upload it to services like AWS S3 or Google Cloud Storage using their SDKs. This is useful for CI environments where local storage is ephemeral.
What if my test fails before the driver is initialized?
If the failure happens in a before hook, the afterEach hook won't run because no test executed. In that case, you can add a separate after hook that checks if the driver exists and takes a screenshot if needed.
How do I attach screenshots to Mocha's HTML report?
If you use a reporter like mochawesome, you can add the screenshot path to the test context and it will be embedded in the report. For other reporters, you may need to customize the reporter or use a plugin.