Overview

While developing your website, you might put some console.log statements in your code to help debug and then forget to remove those and now, you want to see all the console messages that gets logged into the DevTools console across different pages of your website.

Or maybe, you've put those console statements intentionally while testing your website to see if you get the correct data in the browser. Well, you can automate this process now with Nightwatch.

With Chrome DevTools Protocol support now available in Selenium 4, Nightwatch now supports capturing the console messages being logged to the DevTools console of your browser.

This command only works with Chromium based browsers such as Google Chrome and Microsoft Edge.

Capture console messages

Capturing console messages being logged into the DevTools console of your browser allows you to access those messages in your test itself, where you can check if you are getting the expected data in your browser or if any unexpected console statement is present in your code which should not be logged into the browser console.

All you need to do is call the browser.captureBrowserConsoleLogs() command with the required parameters before navigating to your website.

captureBrowserConsoleLogs() accepts a callback function, which will receive an event object as an argument whenever a new console message is logged. The specifications of the received event object are as follows:

Name type description
type string Type of the call.
E.g.: log, debug, info, error, etc.
timestamp number Time at which the console message was logged.
args
array[object] value property of object contains the log.
E.g. usage: args[0].value.
More details on the specifications of object available here.

Example

tests/capture-console-messages.js
describe('capture console events', function() {
  it('captures and logs console.log event', function() {
    browser
      .captureBrowserConsoleLogs((event) => {
        console.log(event.type, event.timestamp, event.args[0].value);
      })
      .navigateTo('https://www.google.com')
      .executeScript(function() {
        console.log('here');
      }, []);
  });
});

Output of the example above:

  Running Capture console messages:
───────────────────────────────────────────────────────────────────────────────────────────────────
error 2022-06-10T13:38:22.082Z here
No assertions ran.