Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an error has been written to the console

Tags:

cypress

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.

like image 767
udo Avatar asked Dec 22 '18 17:12

udo


People also ask

How do I check the console log?

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".

What function would you call to write an error to the console?

The error() method writes an error message to the console.

Can I use console log in Cypress?

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().


2 Answers

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);   }); }); 
like image 140
Ian Mutawa Avatar answered Oct 15 '22 23:10

Ian Mutawa


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

like image 25
Loren Avatar answered Oct 16 '22 00:10

Loren