Home > Software engineering >  Asserting a DOM element if it has a specific text
Asserting a DOM element if it has a specific text

Time:01-14

I'm starting out in Cypress, I'm trying to select an element with this text:

Username is missing

My code is:

cy.get('[data-id="error"]').should('have.text', 'is missing')

Is there a way that I can just use a specific part of a string (in this case, 'is missing') and still be able to use the .should() assertion? I hope to pass the assertion using specific part of a string only.

CodePudding user response:

If you want to assert an partial text with should then you can use include.text

cy.get('[data-id="error"]').should('include.text', 'is missing')

CodePudding user response:

You can use regular expression with match instead of have.text:

For example the text should contain test:

cy.get('[data-id="error"]').should('match', /test/)

Or simply

cy.get('[data-id="error"]').should('contain', 'test')

CodePudding user response:

you can use contain keyword to look string that contain a substring

with should to perform directly the assertion

cy.get('[data-id="error"]').should('contain', 'is missing')

or get only element that contain text with contains

cy.get('[data-id="error"]').contains('is missing')

them perform needed assertion on it

  •  Tags:  
  • Related