Checking a single item text in Cypress is easy:
cy.contains(selector, text)
if you know the precise text or part of itcy.contains(selector, regex)
if you know a text patterncy.get(selector).should('have.text', text)
if you want to confirm the entire precise text
All the above commands work with a single item. What about checking the text from multiple items? When working on my course Cypress vs Playwright I really admired the built-in Playwright assertion toHaveText()
. It can check a single or multiple elements against full text or a regular expression
1 | // checks a single element |
I wish Cypress had something similar. Using cypress-map we could check the multiple elements text, but it requires more commands
1 | cy.get(selector) |
If we want to handle regular expressions or a mixture of strings and regular expressions it becomes even more verbose.
should read assertion
No worries, it is easy to add Cypress custom assertions, so now the "cypress-map" plugin includes the should read
assertion. Let's see how we can use it.
We can check a single element's exact text:
1 | // import cypress-map plugin |
Here is the assertion passing
We can check all items using an array of strings
1 | cy.get('li').should('read', [ |
We can check a single element using a regular expression
1 | cy.get('li') |
We can even check multiple elements using a mixture of strings and regular expressions
1 | it('check items using a mixture', () => { |
Reads pretty well.