Skip to main content

How to Take A Screenshot on Failure

Intro​

With browser tests it can often be challenging to track down the issue that caused a failure.

By itself, a failure message along with a stack trace is hardly enough to go on, especially when you run the test again and it passes. You may or may not be able to recreate that initial error message, and might be left wondering what it was, and whether it will cause issues in the future.

A Solution​

A simple way to gain insight into your test failures is to capture screenshots at the moment of failure. This is something that is fairly quick to add to your tests, and allows you to review these error messages.

Here is an example.

Example​

In each example we hook into the test framework to find out, after the test runs and before the browser is closed, whether the test failed. If it did, we capture a screenshot with Selenium and save it with a name that includes the test name (e.g., failshot_<test name>.png), so it doesn't get overwritten by other tests.

Then we wire up a test that fails on purpose: it loads the homepage of the-internet and asserts that the heading is blah blah blah.

NOTE: Since these tests fail on purpose, our CI checks that they fail and that the screenshot was saved.

Expected Behavior​

  • Open the browser
  • Load the homepage of the-internet
  • Check the text of the page header and fail
  • Output a failure message in the terminal
  • Capture a screenshot
  • Close the browser

Summary​

Having a screenshot to aid in troubleshooting failing tests along with a stack trace helps in having more insight.

If you want truly unique filenames, then you can add a unique ID (or a timestamp) to the filename. This will prevent screenshots from getting overwritten when the same test fails more than once.

Happy Testing!

Authors​

Dave Piacente
Original creator of Elemental Selenium
Diego Molina
Elemental Selenium maintainer