Cross-Browser Screenshot Capture for Test Failures
In this article
Capturing screenshots of test failures across multiple browsers is essential for debugging visual and layout issues that only appear in specific environments. This guide shows you how to automatically save screenshots when a test fails, using popular tools like Selenium, Playwright, and Cypress. You'll need a test automation framework set up, access to the browsers you want to test (Chrome, Firefox, Safari, Edge), and a place to store the screenshots (local folder or CI artifact).
What You'll Need
- A test automation framework (Selenium WebDriver, Playwright, Cypress, etc.)
- Browser drivers installed (e.g., ChromeDriver, GeckoDriver) or Playwright's built-in browser support
- Access to the browsers you want to test (can be local or via cloud services like BrowserStack or Sauce Labs)
- A directory to save screenshots (e.g.,
screenshots/) - Basic knowledge of your test framework's hooks (e.g., afterEach, onFailure)
Step-by-Step
- Set up a screenshot directory. Create a folder in your project, for example
screenshots/. Make sure the path is consistent across your test runs. If you're using a CI system, ensure the directory is writable and can be uploaded as an artifact. - Identify the failure hook in your test framework. Most frameworks provide a way to run code after a test fails. In Selenium with JUnit/TestNG, use
@AfterMethodand check if the test failed. In Playwright, usetest.afterEachand inspect the test status. In Cypress, useafterEachwith a conditional on test state. - Write a screenshot capture function. Create a helper that takes the browser driver or page object and a filename. For Selenium:
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);then copy to your directory. For Playwright:await page.screenshot({ path: 'screenshots/...' });. For Cypress:cy.screenshot('...'). - Include browser name and timestamp in the filename. This prevents overwriting and makes it clear which browser the screenshot is from. Example:
failure-chrome-20250315-143022.png. You can get the browser name from the driver capabilities or the browser object. - Attach the hook to the failure event. In Selenium (TestNG):
@AfterMethod public void takeScreenshotOnFailure(ITestResult result) { if (result.getStatus() == ITestResult.FAILURE) { captureScreenshot(driver, result.getName()); } }For Playwright (Jest or Mocha):test.afterEach(async ({ page }, testInfo) => { if (testInfo.status !== 'passed') { await page.screenshot({ path: `screenshots/${testInfo.title}-${browserName}.png` }); } });For Cypress:afterEach(function () { if (this.currentTest.state === 'failed') { cy.screenshot(`failure-${this.currentTest.title}`); } }); - Run your tests across multiple browsers. Configure your test runner to execute the suite in each browser. For Selenium, use a parameterized test with different browser capabilities. For Playwright, define projects in the config for each browser. For Cypress, use the
--browserflag or run in parallel with different browsers. - Verify the screenshots are saved. After a failed test, check the screenshots folder. Open each image to confirm it shows the failure state. If you're using a cloud grid, ensure the screenshot is downloaded to your local machine or CI artifact.
- Store screenshots as CI artifacts. If you're using Jenkins, GitHub Actions, or GitLab CI, configure the system to upload the screenshots folder as an artifact. This makes them accessible after the pipeline finishes. For example, in GitHub Actions:
- uses: actions/upload-artifact@v4 with: name: screenshots path: screenshots/ - Add context to the screenshot. Optionally, capture the page HTML or console logs alongside the screenshot. This helps debug. In Playwright, you can use
page.content()and save it as an HTML file. In Selenium, you can get the page source. - Clean up old screenshots. To avoid clutter, delete screenshots older than a certain number of days or before each test run. Use a simple script or CI step.
Common Mistakes
- Not checking the test status correctly, so screenshots are taken on success too.
- Using the same filename for every failure, causing overwriting.
- Forgetting to create the screenshots directory, leading to errors.
- Hardcoding browser names instead of retrieving them dynamically.
- Taking screenshots only at the end of the test, missing the actual failure moment (though this is often the best you can do).
- Not handling exceptions in the screenshot code, which can mask the original failure.
Tips
- Use a unique identifier like the test name and timestamp to avoid collisions.
- If you're testing responsive designs, take full-page screenshots (Playwright:
fullPage: true; Selenium: use a library like AShot). - For flaky tests, consider taking a screenshot on retry as well, to see if the failure is consistent.
- Store screenshots in a centralized location (like S3) if you have multiple CI runners.
- Add a visual diff tool (like Percy or Applitools) to automatically compare screenshots across browsers.
- Keep the screenshot capture code in a utility class to avoid duplication.
Troubleshooting
- No screenshots are saved. Check that the failure hook is correctly triggered. Add a log statement to confirm. Also verify the directory path is correct and writable.
- Screenshots are blank or white. This often happens if the browser window is minimized or not in focus. Try running tests in headed mode or use a virtual display. Also ensure the page is fully loaded before capturing.
- Screenshots are not captured in headless mode. Some browsers in headless mode require specific settings. For Chrome, add
--headless=newand ensure the window size is set. For Firefox, use--headlessand set the viewport. - Permission errors when saving. Make sure the user running the tests has write access to the directory. In CI, use a dedicated artifact directory.
- Cross-browser differences in screenshot dimensions. Set a consistent viewport size in your test configuration to minimize differences.
- Tests fail but the hook doesn't run. If you're using a framework where the hook is in a base class, ensure the base class is inherited correctly. Also check for syntax errors in the hook.
Frequently Asked Questions
Can I capture screenshots of the entire page, not just the visible viewport?
Yes. In Playwright, use page.screenshot({ fullPage: true }). In Selenium, you'll need a library like AShot or manually scroll and stitch. Cypress captures the full page by default when using cy.screenshot().
How do I get the browser name in my screenshot filename?
In Selenium, use ((Capabilities) ((RemoteWebDriver) driver).getCapabilities()).getBrowserName(). In Playwright, you can access browserName from the test context (e.g., testInfo.project.name). In Cypress, use Cypress.browser.name.
What if I use a cloud grid like BrowserStack?
Most cloud providers offer built-in screenshot capabilities. For Selenium, you can use the same TakesScreenshot interface. For Playwright and Cypress, they work the same as local browsers. Additionally, cloud providers may have their own dashboard to view screenshots.
Can I capture screenshots for mobile browsers?
Yes, if you're using emulation or real devices. The same code works, but ensure the device viewport is set correctly. For real devices, use Appium or cloud device farms.
How do I avoid screenshots on expected failures (e.g., negative tests)?
In your test, if you expect a failure, catch the exception and mark the test as passed or skip. Only take screenshots when the test status is actually failed, not when it's skipped or expected to fail.
Is it better to take screenshots before or after the test teardown?
Take them as soon as the failure is detected, typically in the failure hook. If you wait until after teardown, the browser may be closed or the page state may be lost.