8

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?

Klompus
  • 130
  • 1
  • 9
Vali Munteanu
  • 469
  • 3
  • 15
  • You could try to listen on `error` events on `window` (https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror). But that does not "read" console. You could try to override global `console` object to "catch" errors before they are printed in browser's console, but you would have to override it before any other scripts are initialized: ```const _err = console.error; console.error = (...args) => _err('Caught!', ...args);``` – ahwayakchih Oct 24 '19 at 12:43

1 Answers1

11

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

})
Richard Matsen
  • 20,671
  • 3
  • 43
  • 77