Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 19997

Idiomatic Cypress way to assert that two elements that contains some text exist in the DOM

Using Cypress, what is the idiomatic way to assert that two elements exist in the DOM for a given selector (that also contain some text)?

Here's how I would do that in JavaScript:

Array.from(document.querySelectorAll("selector")).filter(node => node.textContent.includes("text")).length === 2

Is there an idiomatic way to do this in Cypress?

I've tried:

cy.get('selector')
  .contains('text')
  .should('have.length', 2);

but I'm getting the following error:

cy.contains() cannot be passed a length option because it will only ever return 1 element.

Upvotes: 2

Views: 640

Answers (2)

Dhamo
Dhamo

Reputation: 1251

Alternatively, you can use the below approach without the 'filter' option.

Example:

<table>
  <tbody>
    <tr>
      <td>Same</td>
      <td>Same</td>
      <td>Different</td>
      <td>Same</td>
    </tr>
  </tbody>
</table>
// selects all table cells with text "Same"
cy.get('td:contains("Same")').should('have.length', 3)
// if the text does not have white spaces, no need to quote it
cy.get('td:contains(Same)').should('have.length', 3)
// you can find elements NOT having the given text
cy.get('td:not(:contains(Same))')
  .should('have.length', 1)
  .and('have.text', 'Different')

Read more at here

Upvotes: 2

Alapan Das
Alapan Das

Reputation: 18626

You can use filter() in combination with contains() like this. (Cypress Docs)

cy.get('selector')
  .filter(':contains("text")')
  .should('have.length', 2);

Upvotes: 3

Related Questions