Custom Cypress Should Read Assertion

Check multiple elements text using `should read` assertion from the `cypress-map` plugin.

Checking a single item text in Cypress is easy:

  • cy.contains(selector, text) if you know the precise text or part of it
  • cy.contains(selector, regex) if you know a text pattern
  • cy.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
2
3
4
5
6
// checks a single element
await expect(selector).toHaveText('Submitted');
// checks several elements
await expect(selector).toHaveText(['Created', 'Submitted']);
// check several elements using the exact text or regular expressions
await expect(selector).toHaveText([/Created/i, 'Submitted']);

I wish Cypress had something similar. Using cypress-map we could check the multiple elements text, but it requires more commands

1
2
3
cy.get(selector)
.map('innerText')
.should('deep.equal', ['Created', 'Submitted'])

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
2
3
4
5
6
7
// import cypress-map plugin
import 'cypress-map'

it('checks a single element', () => {
cy.visit('cypress/prices-list.html')
cy.get('li:eq(1)').should('read', 'Mango $1.01')
})

Here is the assertion passing

Checking single exact text

We can check all items using an array of strings

1
2
3
4
5
cy.get('li').should('read', [
'Oranges $0.99',
'Mango $1.01',
'Potatoes $0.20',
])

Checking all elements

We can check a single element using a regular expression

1
2
3
cy.get('li')
.first()
.should('read', /^Oranges \$\d.\d{2}$/)

Checking an element text using a regular expression

We can even check multiple elements using a mixture of strings and regular expressions

1
2
3
4
5
it('check items using a mixture', () => {
cy.visit('cypress/prices-list.html')
const nameWithPrice = /^\w+ \$\d+\.\d{2}$/
cy.get('li').should('read', ['Oranges $0.99', nameWithPrice, nameWithPrice])
})

Using text or regular expressions

Reads pretty well.