Can Cypress give me an error message when there has been an error?

Viewed 158

I have the below snippet from my test case:

cy.get('item_here').should('not.exist');

Can cypress give me a custom error message when the "item_here" does exist?

Thanks,

2 Answers

You can throw your own errors in a callback function for .should().

cy.get(".does-not-exist")
  .should("not.exist")
  .then(($el) => {
    if ($el == null) {
      throw new Error("Item does not exist in DOM");
    }
  });

You can chain a log message on to the existing code, and it will only run if the element does not exist.

cy.get('item_here').should('not.exist')
  .then(() => cy.log('no such element found'))  // Note; this is an additional log

Changing both "success" and "fail" messages is hard because Cypress likes to show the red AssertionError block when anything fails or an error is thrown.

You can use the should() callback version, but please use an expect() inside otherwise you do not have retry,

  cy.get('item_here').should($el => {
    expect($el, 'Cannot be found').to.not.exist    // expect causes retry for 4 seconds
                                                   
    Cypress.log({
      name: 'Missing',
      message: 'Cannot be found'
    })
  })


Related