javascriptcypressspy

Cypress: monitor console output


I know Cypress can print debug information in the browser console, but can it read data from console during tests?

I'm working on a three.js powered app, so I can't properly test the 3d aspects of the app, but I would like to listen for javascript errors in the browser console.

Is it at all possible?


Solution

  • You can intercept console messages with Cypress cy.spy(), but if you want to go further into the data - I haven't seen any way to do that.

    The docs could use a bit of a re-jig, so here's how I'm setting up the spy.

    let spy;
    Cypress.on('window:before:load', (win) => {
      spy = cy.spy(win.console, "error")  // can be other methods - log, warn, etc
    })
    
    it('Doing something that should not cause a console error', () => {
    
      // Run test steps here that may cause a console error
    
      cy.wait(100).then(x => {  
        expect(spy).not.to.be.called
      })
    
      // or perhaps this, to auto-retry (have not tried this syntax)
      cy.wrap({}).should(() => {  
        expect(spy).not.to.be.called
      })
    
      // The docs imply you can just do this
    
      expect(spy).not.to.be.called
    
      // ..but that line may run before any other cy command above finish
      // so I'd stick with using cy.wrap({}).then(...) to put it in the command chain
    
      // The spy call count is reset after each test
    
    })