Search code examples
javascriptcypress

Checking console messages in Cypress


I have local file where I can check if correct messages have been sent through console. I can see the messages through cypress and count them but it seems that I can't check the actual message.

Code Example:

it(`Checking Error Text in:`, () => {

cy.visit('../testmessages.html', {
onBeforeLoad(win) {
    cy.stub(win.console, 'log').as('consoleLog')},
})

cy.get('button').click()
cy.get("@consoleLog").should('be.calledThrice')

//here I would like to confirm that message contains "Id" etc 
})})})

Solution

  • Technically, if you use cy.stub() you can't see the message in the console any more, because it blocks the call.

    A cy.spy() would be better, then any console.log() you add for debugging aren't swallowed up by the stub.

    If you save the result of the cy.spy(), you can use methods on it to extract the call data collected.

    let spy;
    Cypress.on('window:before:load', (win) => {
      spy = cy.spy(win.console, 'log');
    });
    
    cy.visit('../testmessages.html')   
    cy.get('button').click()            // console.log('hello', 'world')
    
    cy.then(() => {
      const calls = spy.getCalls();
      expect(calls.length).to.eq(3)
      expect(calls[1].args).to.deep.eq(['hello', 'world'])
    })