Zhockos
Zhockos

Reputation: 51

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 
})})})

Upvotes: 2

Views: 1503

Answers (3)

In my case I needed to get warning from my console and also verifying text of those warnings. Below is my code:

Cypress.on('window:before:load', (win)=>{
 cy.spy(win.console, 'warn').as('consoleWarning')
})
//some code here
cy.window().then((win)=>{
 expect(win.console.warn).to.have.callCount(1)
 cy.get('@consoleWarning').should('have.been.calledWith','text')
})

Upvotes: 0

Fody
Fody

Reputation: 31924

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'])
})

Upvotes: 3

DJSDev
DJSDev

Reputation: 993

With a stub, you can check what was passed to the function with something like this

cy.get(@consoleLog).should("have.been.calledWith", "Expected console message");

Upvotes: 0

Related Questions