kishore kumar
kishore kumar

Reputation: 131

Error handling using the catch block in cypress

I'm trying to handle an error in Cypress but the Cypress app is throwing error

cy.get('button[name="continue"]',{timeout: 30000})
  .catch((err) => {
    cy.console.log("error caught");
  })

The error I get:

TypeError: cy.get(...).catch is not a function

Upvotes: 12

Views: 63579

Answers (1)

totymedli
totymedli

Reputation: 31182

tl;dr

Cypress has no .catch command, the error message clearly states that.

Exception handling in Cypress

The documentation on error recovery clearly states:

The following code is not valid, you cannot add error handling to Cypress commands. The code is just for demonstration purposes.

cy.get('button').contains('hello')
  .catch((err) => {
    // oh no the button wasn't found
    // (or something else failed)
    cy.get('somethingElse').click()
  })

They deliberately left this out and in the docs they explain it at great length why you shouldn't be able to do it.

If you really want, you can catch uncaught exceptions, just try the suggestions of the Catalog of Events on this matter:

it('is doing something very important', function (done) {
  // this event will automatically be unbound when this
  // test ends because it's attached to 'cy'
  cy.on('uncaught:exception', (err, runnable) => {
    expect(err.message).to.include('something about the error')

    // using mocha's async done callback to finish
    // this test so we prove that an uncaught exception
    // was thrown
    done()

    // return false to prevent the error from
    // failing this test
    return false
  })

  // assume this causes an error
  cy.get('button').click()
})

Upvotes: 18

Related Questions