Reputation: 19997
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
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
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