Yu Zhang
Yu Zhang

Reputation: 2149

With Cypress, how to assert that a function has been called with an argument that contains a given text string?

I need to verify a given error message appears in the dev console when a given attribute is missing from an initialization JSON.

So far, I have set up a spy to watch over the win.console.error:

const onBeforeLoad = win => {
    cy.spy(win.console, 'error').as('consoleError');
}

And in my test, the assertion:

cy.get('@consoleError').should('have.been.calledWith', 'aGivenErrorMsg');

The test would fail as the actual error message I could see from Cypress log has additional texts which is appended by Cypress, the whole error text message is:

aGivenErrorMsg at consoleError [as error] (https://test.com/__cypress/runner/cypress_runner.js:123270:26)

And this additional appended text would make my test fail.

The most efficient way to make my test work is to somehow verify that the error message generated by Cypress contains the error message I am interested in.

How do I do it?

Upvotes: 3

Views: 1288

Answers (1)

Carpenter
Carpenter

Reputation: 181

Try using calledWithMatch instead of calledWith.

cy.window().then(win => {
  cy.spy(win.console, 'error').as('consoleError')

  win.console.error('Error message with additional texts')

  // cy.get('@consoleError').should('have.been.calledWith', 'Error message')   // failing
  cy.get('@consoleError').should('have.been.calledWithMatch', 'Error message') // passing
})

For reference:

Assert argument of stubbed function with regex

Sinon assertions

Upvotes: 4

Related Questions