Nothing found, try being more general or more specific

Protractor - capturing console.errors from browser

When writing protractor UI tests, I wanted to capture all console.log and console.errors to get an early glimpse of possible bugs that occur underneath visible functionality. 

Official protractor 3 spec HOWTO's clearly specify to use built-in methods. The problem is - they don't work. At least in Firefox which has most stable driver so far. They do spit out over 900 useless logs related to css, graphics and fonts, but not what I really need.

browser.manage().logs().get('browser').then(function(browserLog) {
  console.log(browserLog);
});
39276998b2.png

Solution

First what I did is override window.console to store errors in global variable. Later I check if something is in them..

injectConsoleTracing = function () {
    browser.executeScript('window.errs=typeof(errs)=="undefined" ? [] : window.errs; window.console.error = function(msg){window.errs.push(msg); }; ');
    browser.executeScript('window.logs=typeof(logs)=="undefined" ? [] : window.logs; window.console.log = function(msg){window.logs.push(msg); }; ');
};

expectNoConsoleErrors = function () {
    browser.executeScript('return window.errs;').then(function (v) {
        expect(v).toEqual([]);
    });
    browser.executeScript('return window.logs;').then(function (v) {
        expect(v).toEqual([]);
    });
};

This injectConsoleTracing should be executed before page is loaded with angular, so instead of browser.get, I use browser.driver.get:

browser.driver.get(BASE_URI + '#/' + url);
injectConsoleTracing();
browser.waitForAngular().then(function () {
    testMethod(); //your code here
    expectNoConsoleErrors();
});

Note that I have not tested it with non-single-page sites where refresh is done often. In those cases window.errs will get lost and you would need to re-inject tracing over and over for each page but as a quick and easy hack, it works

Also note, that browser.executeScript is async in nature, so if you put this check at the end of async jasmine test (that uses done() to mark as complete), then you might get an error of expectation being executed after test was completed:

Error: 'expect' was used when there was no current spec, this could be because an asynchronous test timed out
    at Env.expect (/Users/artjom/.nvm/versions/v5.5.0/lib/node_modules/protractor/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:845:15)