Check if an error has been written to the console

前端 未结 4 1817
自闭症患者
自闭症患者 2021-02-04 02:41

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



        
4条回答
  •  萌比男神i
    2021-02-04 03:15

    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:

    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 );
        });
    });
    

提交回复
热议问题