Check there were no errors in the browser console with Protractor

All we need is an easy explanation of the problem, so here it is.

I’m using Protractor to test AngularJS

I want to check that at the end of the test no uncaught exceptions occurred and were printed to the browser console.

Is there a simple way to do that?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

If you’re using Protractor with Jasmine, use the following code:

afterEach(function() {
    browser.manage().logs().get('browser').then(function(browserLog) {
        expect(browserLog.length).toEqual(0);
    });
});

This will pass the test case if there are no console errors. If there are any console errors, the test will fail.

Instructions on how to access the content of the browser’s console can be found in the How can I get hold of the browser’s console section of the FAQ.

Method 2

Protractor 2.0.0 has introduced a new console plugin specifically for the task.

Add the following to the protractor configuration:

plugins: [{
    path: '/path/to/node_modules/protractor/plugins/console/index.js',
    failOnWarning: true,
    failOnError: true
}],

Method 3

With a little effort we can tweak the accepted answer to work with Cucumber.js, in case you’re not using Protractor with the default testing framework.

this.After(function(callback) {
    browser.manage().logs().get('browser').then(function(browserLog) {
        if (browserLog.length !== 0) {
            var failMessage = "There was output in the browser console:" +
                              browserLog.map(JSON.stringify).join(";\n");
            callback.fail(failMessage);
        }
        else {
            callback();
        }
    });
});

You’ll want to check out the documentation on After hooks, which are Cucumber’s equivalent to Jasmine’s afterEach.

Method 4

How @velochy stated there is now an own package for the module: https://www.npmjs.com/package/protractor-console-plugin

You can use it in your protractor.conf:

  plugins: [{
    package: 'protractor-console-plugin',
    failOnWarning: {Boolean}                (Default - false),
    failOnError: {Boolean}                  (Default - true),
    logWarnings: {Boolean}                  (Default - true),
    exclude: {Array of strings and regex}   (Default - [])
  }]

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply