Should read assertion

This assertion comes from the cypress-mapopen in new window plugin. It is useful for checking the text content of list of elements against strings or regular expressions.

📺 Watch this recipe explained in the video Custom Should Read Assertion From Cypress-map Pluginopen in new window.

<ul id="todos">
  <li>Write code</li>
  <li>Add tests</li>
  <li>Pay $10 fine</li>
</ul>

Let's confirm the exact text of the first LI element:

cy.get('li').first().should('have.text', 'Write code')

We can confirm partial text match using cy.contains or include.text assertion:

cy.contains('li', 'Add').should('have.text', 'Add tests')
cy.get('li').first().should('include.text', 'Write c')

To confirm multiple exact text matches, you can use the should read custom assertion from the cypress-map plugin:

cy.get('li').should('read', [
  'Write code',
  'Add tests',
  'Pay $10 fine',
])

The assertion ensures there is the exact number of elements and the text inside each element is the same as the given string. It will fail if the numbers are different

// 🚨 fails on purpose, since there are 3 LI elements
cy.get('li').should('read', ['Write code', 'Add tests'])

With should read, you can use either exact text matches or match against regular expressions. For example, if we do not know the precise fine amount, we could use:

cy.get('li').should('read', [
  'Write code',
  'Add tests',
  /^Pay \$\d+ fine$/,
])