I can check if text exists in cypress with cy.contains('hello'), but now I delete hello from the page, I want to check hello doesn't exist, how do I do something like cy.notContains('hello')?
How to do `cy.notContains(text)` in cypress?
18.3k views Asked by Alien At
4
There are 4 answers
2
On
cy.contains('hello').should('not.exist) isn't going to work if there's more that one occurrence of "hello".
You may prefer to check the actual element instance has been removed from the DOM
cy.contains('hello')
.then($el => {
// delete the element
cy.wrap($el)
.should($el => {
// has this element been removed?
expect(Cypress.dom.isAttached($el)).to.eq(false)
})
})
2
On
I prefer a slightly different syntax to the existing answers:
cy.root().should('not.contain.html', '<b>Fatal error</b>');
here you can use not.contain.html to search for html, or not.contain.text to search for text, for example to test a PHP application, i use
Cypress.Commands.add('visit2', (url, options) => {
const ret = cy.visit(url, options);
cy.root()
.should('not.contain.html', '<b>Fatal error</b>') // <b>Fatal error</b>: Uncaught ArgumentCountError: strlen() expects exactly 1 argument, 0 given
.should('not.contain.html', '<b>Warning</b>') // <b>Warning</b>: Cannot modify header information - headers already sent by (output started at /in/tbUXQ:4) in <b>/in/tbUXQ</b> on line <b>4</b><br />
.should('not.contain.html', '<b>Notice</b>') // <b>Notice</b>: Undefined variable: a in <b>/in/tbUXQ</b> on line <b>4</b><br /> cy.should('not.contain', '<b>Parse error</b>'); // <b>Parse error</b>: syntax error, unexpected '}' in <b>/in/tbUXQ</b> on line <b>4</b><br />
.should('not.contain.html', '<b>Parse error</b>'); // <b>Parse error</b>: syntax error, unexpected '}' in <b>/in/tbUXQ</b> on line <b>4</b><br />
return ret;
});
to detect common-ish PHP application errors
For the simple problem of checking 'hello' doesn't exist, you can use
.contains('hello')followed a.should(). So it would look something like this for the whole page:Or you can further narrow it down to a particular area of the app: