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.
Steps to Open the Console Log in Google Chrome With the Chrome browser open, right-click anywhere in the browser window and select Inspect from the pop-up menu. By default, the Inspect will open the "Elements" tab in the Developer Tools. Click on the "Console" tab which is to the right of "Elements".
The error() method writes an error message to the console.
log() very useful as they can see the printed message on the command line. However, Cypress doesn't directly support the use of console. log().
This does exactly what I needed of catching any error in the console and do an assertion of the logs count. Just add the following in cypress/support/index.js
Cypress.on('window:before:load', (win) => { cy.spy(win.console, 'error'); cy.spy(win.console, 'warn'); }); afterEach(() => { cy.window().then((win) => { expect(win.console.error).to.have.callCount(0); expect(win.console.warn).to.have.callCount(0); }); });
There have been some updates since the previous answers.
Because the window is re-created with each cy.visit
, Cypress recommends stubbing as a part of the cy.visit
command.
cy.visit('/', { onBeforeLoad(win) { cy.stub(win.console, 'log').as('consoleLog') cy.stub(win.console, 'error').as('consoleError') } }) //... cy.get('@consoleLog').should('be.calledWith', 'Hello World!') cy.get('@consoleError').should('be.calledOnce')
For more details see the official FAQ for stubbing out the console: https://docs.cypress.io/faq/questions/using-cypress-faq.html#How-do-I-spy-on-console-log
And the recipe repository: https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/stubbing-spying__console
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With