How to do `cy.notContains(text)` in cypress?

18.3k views Asked by At

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')?

4

There are 4 answers

0
jjhelguero On BEST ANSWER

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:

// code to delete hello

cy.contains('.selector', 'hello').should('not.exist')

Or you can further narrow it down to a particular area of the app:

// code to delete hello

cy.get('.element-had-hello').should('not.include.text', 'hello')
2
Fody 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)
      })
  })
0
Alapan Das On

You can use contains with a combination of selector and text. Firstly check it exists and then after deletion check, it doesn't exist.

cy.contains('selector', 'hello').should('exist')
//Actions to perform Deletion
cy.contains('selector', 'hello').should('not.exist')
2
hanshenrik 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