Check if an error has been written to the console

udo picture udo · Dec 22, 2018 · Viewed 8.3k times · Source

I'm trying to find a way to check if an error has been written to the console when running a cypress unit test.

I know how to log something to the console

cy.log('log this to the console');

but not how to check if an error has been written to it.

any suggestions how to read errors from the (browser) console log?

note: probably not the "smart" way to test but sometimes my js libraries which I use would "complain" and write the errors to the browser log. this is to simplify testing.

Answer

dwelle picture dwelle · Dec 24, 2018

Edit: the following does not directly log to terminal when in headless mode, but it nonetheless fails the test on AUT's console.error and displays the error message indirectly, even in the headless terminal, which may be what you want.

I'm not sure exactly what you mean, but let's go through all the places where an output can be logged in cypress, and how to handle several cases.

First, an overview:

enter image description here

  1. To log into the command log, you use:

    // from inside your test
    cy.log('foo');
    
  2. To log into devTools console:

    // from inside your test
    console.log('bar');
    
  3. To log into terminal, you need to log from within the Cypress' node process:

    // from within e.g. your plugin/index.js file
    console.log('baz');
    

How to log AUT's errors to Terminal, Command Log, and fail the test

(note, AUT here stands for Application under test, meaning your application).

I'm also using ansicolor package to make the error red-colored in the terminal, which is optional.

// plugins/index.js
const ansi = require(`ansicolor`);
module.exports = ( on ) => {
    on(`task`, {
        error ( message ) {
            // write the error in red color
            console.error( ansi.red(message) );
            // play `beep` sound for extra purchase
            process.stdout.write(`\u0007`);
            return null;
        }
    });
};

Note: using internal cy.now() command to work around Cypress' tendency to throw Cypress detected that you returned a promise when it (IMO) shouldn't.

(adapted from https://github.com/cypress-io/cypress/issues/300#issuecomment-438176246)

// support/index.js or your test file
Cypress.on(`window:before:load`, win => {

    cy.stub( win.console, `error`, msg => {
        // log to Terminal
        cy.now(`task`, `error`, msg );
        // log to Command Log & fail the test
        throw new Error( msg );
    });
});