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

Viewed 1470

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

3 Answers

For the simple problem of checking 'hello' doesn't exist, you can use .contain('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')

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)
      })
  })

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