Search code examples
consolecypress

Watch console for errors


I have an app using canvas elements, which are difficult to test with javascript but it does throw messages to the console.

How can I watch for errors written to the console?

I tried monkey patching the window console, but it's not working.

const messages = []

window.console.error = (msg) => {
  messages.push(msg)
})

// actions causing error

expect(messages.length).to.eq(0)

Solution

  • You can watch console messages with Cypress cy.spy(), ref docs

    let spy;
    Cypress.on('window:before:load', (win) => {
      spy = cy.spy(win.console, "error")  
    })
    
    // actions causing error
    
    cy.then(() => {  
      expect(spy).not.to.be.called
    })