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');
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)
})
})
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')
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With