Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show error message when element does not exist in DOM in cypress

Tags:

cypress

How can i with cypress show an custom error message when element is not present?

For the snippet below, i would like to display: "No rows are displayed" instead of the provided; "expected #rows to exist in the DOM".

cy.get('#rows').should('exist');
like image 277
jaikl Avatar asked Nov 07 '22 23:11

jaikl


1 Answers

Cypress event handling gives a hook that may be used to customize the error message.

The Cypress log shows errors in the format ${error.name}:${error.message}. You can change both error properties, but the : is hard-coded.

Here are some samples,

describe('custom error', () => {

  // Ref: https://docs.cypress.io/api/events/catalog-of-events.html#Catching-Test-Failures
  it('fails with custom error message', () => {
    cy.on('fail', (error, runnable) => {
      error.name = 'CustomError'
      error.message = 'Incorrect, 1 !== 2'
      throw error // throw error to have test still fail
    })
    cy.wrap(1).should('eq', 2)
  })


  /*
    Ref: https://docs.cypress.io/api/cypress-api/custom-commands.html#Child-Commands
    Add this to /cypress/support/commands.js
  */
  Cypress.Commands.add('onFail', { prevSubject: true }, (chainedSubject, message) => {
    cy.on('fail', (error, runnable) => {
      error.name = 'CustomError'
      error.message = 'Incorrect, 1 !== 2'
      throw error // throw error to have test still fail
    })
    return chainedSubject
  })

  it('fails with custom message via command', () => {
    cy.wrap(1).onFail(customError).should('eq', 2)
  })


  /*
    Ref: https://docs.cypress.io/api/cypress-api/custom-commands.html#Overwrite-Existing-Commands
    Add this to /cypress/support/commands.js
  */
  Cypress.Commands.overwrite('should', (originalFn, actual, assertion, expected, options) => {
    if (options && options.message) {
      cy.on('fail', (error, runnable) => {
        error.name = 'CustomError'
        error.message = options.message
        throw error // throw error to have test still fail
      })
    }
    return originalFn(actual, assertion, expected, options)
  })

  it.only('fails with custom message via overwrite of should', () => {
    cy.wrap(1).should('eq', 2, { message: 'Incorrect: 1 !== 2'})
  })


  it('fails with standard message', () => {
    cy.wrap(1).should('eq', 2)
  })
})

It also works with cy.get()

This test uses a cy.get() and it also emits a custom message

it('fails with a custom message when using cy.get()', () => {
  cy.visit('https://docs.cypress.io/api/commands/get.html')
  cy.get('h1').onFail('Failed to find this text').should('contain', 'NoSuchText')    
})
like image 106
Richard Matsen Avatar answered Dec 14 '22 23:12

Richard Matsen