Cypress: How to check if the element has a text but the text is not specific?

Viewed 3631

Is there any other ways to check if an element has text?

cy.get('h1').should('have.text','Enter your text')

I have this code but i don't want the text to be exact what i want to check. I just want to check if the element has text on it or not.

2 Answers

Another way, test for any text of non-zero length

cy.visit('http://example.com')
cy.get('h1').invoke('text').should('have.length.gt', 0)  // gt == greater than
cy.get('h1').invoke('text').should('not.be.empty')       // not.be.empty == NOT "" 
cy.get('h1').should('not.have.text', "")                 // also NOT "" 

If you want to validate partial text, you can:

cy.get('h1').should('include.text','partial text')

If you just want to check whether your element has some inner text irrespective of whatever it is you can:

cy.get('h1').invoke('text').should('have.length', 1)

As @kame suggested you can also add an assertion as the length is greater than 0, in case the above doesn't work.

cy.get('h1').invoke('text').should('have.length.gt', 0)
Related