0

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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
KiritoLyn
  • 626
  • 1
  • 10
  • 26

3 Answers3

3

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

jeremy-denis
  • 6,368
  • 3
  • 18
  • 35
  • 2
    please note that `contains` is not the same as `should` ... it returns an element, doesn't check if it exists ... a bit different thing, you can read more about it in here: https://stackoverflow.com/questions/50042670/cypress-test-is-contains-equivalent-to-shouldcontain – Flash Thunder Jan 14 '22 at 15:01
  • ***returns an element, doesn't check if it exists*** does not make any sense. – Seeker Jan 15 '22 at 21:51
2

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')
Flash Thunder
  • 11,672
  • 8
  • 47
  • 91
2

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')
Alapan Das
  • 17,144
  • 3
  • 29
  • 52