Capture Browser JS Exceptions
Overview
Since v2.2, Nightwatch allows you to listen to the JavaScript exceptions happening during the run-time of your website and make them available in the test itself via a callback.
This is made possible with the Chrome DevTools Protocol support now available in Selenium 4.
The `captureBrowserExceptions()` command only works with Chromium based browsers such as Google Chrome and Microsoft Edge.
Capture JS exceptions
Use the browser.captureBrowserExceptions()
command with the required parameters before navigating to your website.
captureBrowserExceptions()
accepts a callback function, which will receive an event
object as an argument whenever a new Error
is thrown. The specifications of the received event
object are as follows:
Name | type | description |
---|---|---|
timestamp |
number | Time at which the JS exception was captured. |
exceptionDetails |
object | A JS object with all the details of the exception occurred. Specifications of the object can be read from here. |
Example
tests/catch-js-exceptions.js
describe('catch browser exceptions', function() {
it('captures the js exceptions thrown in the browser', async function() {
await browser.captureBrowserExceptions((event) => {
console.log('>>> Exception:', event);
});
await browser.navigateTo('https://duckduckgo.com/');
const searchBoxElement = await browser.findElement('input[name=q]');
await browser.executeScript(function(_searchBoxElement) {
_searchBoxElement.setAttribute('onclick', 'throw new Error("Hello world!")');
}, [searchBoxElement]);
await browser.elementIdClick(searchBoxElement.getId());
});
});
Output of the example above:
Running captureBrowserExceptions():
───────────────────────────────────────────────────────────────────────────────────────────────────
{
exceptionDetails: {
exceptionId: 1,
text: 'Uncaught',
lineNumber: 0,
columnNumber: 6,
scriptId: '55',
url: 'https://duckduckgo.com/',
stackTrace: { callFrames: [Array] },
exception: {
type: 'object',
subtype: 'error',
className: 'Error',
description: 'Error: Hello world!\n' +
' at HTMLAnchorElement.onclick (https://duckduckgo.com/:1:7)',
objectId: '6711588812373266697.1.1',
preview: [Object]
},
executionContextId: 1
},
timestamp: 2022-06-10T13:14:52.722Z
}
No assertions ran.