Skip to main content

How to Capture Console Logs and JavaScript Errors

Intro​

A page can look fine while it is broken: a script fails, logs an error to the console, and a button stops working. Our tests check what they see on the page, so they don't notice until much later, if at all. And when a test fails, the console of the browser often has the reason.

How do we get the console messages and the JavaScript errors of the page in our tests?

A Solution​

Use WebDriver BiDi. With BiDi, the browser sends events to the test while the test runs: here, each console message (console.log, console.warn, console.error, ...) and each JavaScript error that the page does not catch. The test adds a handler for each kind, and the handlers get the messages as they happen.

Older versions of this tip read the logs through the JSON Wire Protocol log endpoint of Selenium Server. That endpoint is gone in the W3C protocol, and BiDi works with a local browser, a Grid, and any browser that supports BiDi (Chrome, Edge and Firefox).

With the messages in hand, the test can fail when the page logs an error, or print them to explain a failure.

Let's continue with an example.

Example​

Expected Behavior​

  • Chrome starts with WebDriver BiDi turned on
  • The test adds a handler for console messages and one for JavaScript errors
  • The test loads the page and clicks the buttons that log to the console and throw an error
  • The handlers get 3 console messages and 1 error, and the test checks them
  • Chrome closes

Summary​

Console messages and JavaScript errors tell us what goes wrong inside the page. A common use is to collect the errors during every test, and fail the test (or print them) when there are any. Keep in mind that third-party scripts log too, so check the messages that come from our own code.

Happy Testing!

Authors​

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