Lattes

Latte recipes, espresso drinks and coffee how-to

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Selenium Screenshots on Mocha Test Failure

· 5 min read · Espresso Drinks

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 mocha as a dev dependency).
  • Selenium WebDriver (selenium-webdriver npm package) and a browser driver (e.g., chromedriver) configured.
  • Basic familiarity with Mocha's afterEach hook and async/await.

Step-by-Step

  1. 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.
  2. 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();
    });
  3. Add an afterEach hook to check test status – Mocha's afterEach runs after every test. Use this.currentTest to check if the test failed. If it failed, take a screenshot with a filename that includes the test name and timestamp.
  4. Write the screenshot capture code – Inside afterEach, if this.currentTest.state === 'failed', call driver.takeScreenshot() which returns a base64-encoded string. Save it to a file using Node's fs module:
  5. 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).
  6. Write the screenshot file – Use fs.writeFileSync to 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}`);
      }
    });
  7. 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.
  8. 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 afterEach hook runs before the after hook that quits the driver. Mocha runs hooks in order: afterEach runs after each test, and after runs 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 the base64 encoding option in fs.writeFileSync.
  • Screenshot not taken at all – Check that your afterEach hook is in the correct scope. If you place it inside a describe block, 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 after hook (which quits the driver) is defined after the afterEach hook. Mocha runs hooks in order of definition, so define afterEach before after.
  • Permission errors on screenshot directory – Make sure the directory exists and is writable. You can create it in a before hook using fs.mkdirSync('screenshots', { recursive: true }).
  • Tests are failing but no screenshot appears – Double-check that this.currentTest.state is 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.