How do I assert a failure from a Cypress Custom Command? Let’s say I have a custom command with a complex set of tests that can fail due to some elements not being found, can I assert the failure of that line in a test file?
e2e/test.cy.ts:
cy.someComplexCommand().should('fail')
support/commands.ts:
Cypress.Commands.add('someComplexCommand', () => {
/* Some detailed DOM-traversing test */
})
The above is obviously sudo-code. The use case for this is that I have a complicated command that searches for a particular row in a table based on its’ text content. While I use this most of the time to assert that something exists in the table, there are some tests that need to assert that it doesn’t exist (like when I have just deleted the table row in the UI). Rather than write another command or more code in the test body, I’d prefer to keep it DRY and re-use the existing command, asserting a failure. Is this possible?
I’ve searched and there doesn’t seem to be a lot of detail about asserting failures in Cypress.
Real world example
support/commands.ts:
Cypress.Commands.add('getTableRowContainingText', (text: string): Cypress.Chainable<JQuery<HTMLElement>> => {
return cy.get('table')
.first()
.find('tbody > tr > td')
.filter(`:contains(${text})`)
.first()
.parent('tr')
})
e2e/test.cy.ts:
cy.getTableRowContainingText('not-there').should('not.exist')
The above test fails because when a table is empty, my UI doesn’t show a table at all:

