User Agents

Web browsers and everyday web tech, explained

Cucumber JS Screenshot on Failure & Browser Restart

· 4 min read · Browsers

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

Capturing screenshots and restarting the browser after a Cucumber JS test failure helps diagnose issues and prevents cascading failures in subsequent scenarios. This guide explains how to automatically take a screenshot when a scenario fails and then restart the browser session, ensuring each test runs in a clean environment. This is essential for reliable browser automation, especially in CI/CD pipelines where visual evidence and test isolation improve debugging and stability.

What You'll Need

  • A working Cucumber JS project with WebDriver (e.g., Selenium, Puppeteer, or Playwright)
  • Node.js installed (version 14 or higher recommended)
  • Basic familiarity with Cucumber hooks (Before, After, AfterStep)
  • File system write permissions to save screenshots
  • A test browser driver (e.g., ChromeDriver for Selenium)

Step-by-Step

  1. Create a hooks.js file in your features/support directory if it doesn’t already exist. Cucumber JS automatically loads files in this folder, making it ideal for defining global hooks.
  2. Import required modules at the top of the file. You’ll need fs for saving files and path for constructing file paths:
    const fs = require('fs');
    const path = require('path');
    
  3. Define a directory to store screenshots. Create it if it doesn’t exist:
    const screenshotDir = path.join(__dirname, '../screenshots');
    if (!fs.existsSync(screenshotDir)) {
      fs.mkdirSync(screenshotDir, { recursive: true });
    }
    
  4. Add an AfterStep hook to capture a screenshot only when a step fails. Use the Status object from Cucumber to check the result:
    const { AfterStep } = require('@cucumber/cucumber');
    const { Status } = require('@cucumber/cucumber');
    
    AfterStep(async function ({ result }) {
      if (result.status === Status.FAILED) {
        const screenshot = await browser.takeScreenshot();
        const fileName = `screenshot-${Date.now()}.png`;
        const filePath = path.join(screenshotDir, fileName);
        fs.writeFileSync(filePath, screenshot, 'base64');
        console.log(`Screenshot saved: ${filePath}`);
      }
    });
    
    Replace browser.takeScreenshot() with your WebDriver’s actual method (e.g., browser.saveScreenshot(filePath) in WebdriverIO).
  5. Add an After hook to restart the browser after each scenario, regardless of outcome. This ensures test isolation:
    const { After } = require('@cucumber/cucumber');
    
    After(async function ({ result }) {
      await browser.reloadSession(); // WebdriverIO example
      // For Puppeteer: await browser.close(); await launchBrowser();
      // For Selenium WebDriver: await driver.quit(); await initDriver();
    });
    
    The exact method depends on your test framework. In WebdriverIO, reloadSession() restarts the browser efficiently.
  6. Ensure your browser instance is accessible globally or via the Cucumber world object. In WebdriverIO, browser is global. For custom setups, use setWorldConstructor to attach the driver to this in hooks.
  7. Run your Cucumber tests using your standard command (e.g., npx cucumber-js). Trigger a failure intentionally (e.g., assert a non-existent element) to verify the screenshot is captured and the browser restarts before the next scenario.
  8. Verify the screenshots folder contains PNG files with timestamps and that each scenario starts with a fresh browser session. Check logs for file paths and any errors during screenshot or restart.

Common Mistakes

Not awaiting asynchronous calls like takeScreenshot() or quit() leads to race conditions and missed screenshots. Always use async/await. Using hard-coded paths without checking directory existence causes permission or file-not-found errors. Always ensure the target directory exists. Capturing screenshots on every step instead of only on failure generates unnecessary files and slows tests. Use result.status === Status.FAILED to filter. Forgetting to reinitialize the browser after quit() causes subsequent scenarios to fail immediately. In frameworks like Selenium, you must explicitly start a new driver instance.

Tips

Name screenshots meaningfully using scenario titles or IDs for easier debugging. You can access the scenario name via the hook parameter. Reuse browser sessions between scenarios only if state doesn’t interfere; otherwise, restarting is safer. In CI environments, archive the screenshots directory as artifacts for post-failure review. Use relative paths for portability across machines. Log the full file path of saved screenshots to aid in locating them quickly.

Troubleshooting

If no screenshot is saved, check that the failure actually triggers the AfterStep hook. Add a console.log(result.status) to confirm it’s FAILED. If the browser fails to restart, ensure the driver is properly quit and reinitialized. In WebdriverIO, reloadSession() handles this automatically. For custom drivers, verify your init function is called. Permission errors when saving files usually mean the script lacks write access to the target directory—run with appropriate permissions or change the output path. If screenshots are blank or black, this may occur in headless mode with certain browsers; enable --screenshot or --disable-gpu flags as needed. If tests hang after restart, ensure all asynchronous cleanup completes before the next scenario starts—use await on all driver commands.

Frequently Asked Questions

Can I capture screenshots only on failure?

Yes, by checking result.status === Status.FAILED in the AfterStep hook.

How do I make screenshots easier to identify?

Include the scenario name and timestamp in the filename, extracted from the hook’s parameters.

Does restarting the browser slow down tests?

Slightly, but it improves reliability by preventing state leaks. Use session reuse only when safe.

Which WebDriver methods support screenshot capture?

Selenium, WebdriverIO, and Puppeteer all support screenshot methods like takeScreenshot() or screenshot().

What if my browser variable isn’t global?

Attach it to the Cucumber world object using setWorldConstructor so hooks can access it.

Can I automate archiving screenshots in CI?

Yes, configure your CI pipeline (e.g., GitHub Actions, Jenkins) to save the screenshots folder as a build artifact.