In Cypress, I'm trying to count how many elements (in this case how many buttons in li) contain text. When using "contains", the number of returned items is always equal to one because "contains" only gives the first item in the document containing the search text.
cy.get('li')
.contains('button', 'Submit')
.its('length')
.then(elLength => {
// I want to test here the number of all buttons in li elements containig word 'Submit'
}
Of course, this doesn't work that way, because elLength is always 1 (or 0 if no items found).
Is there any other method in Cypress that can return all elements with text, and I can count them?
Cypress get()
uses the same selectors as jQuery. You can therefor use :contains
to get all elements containing a text.
As Cypress contains()
only includes visible DOM elements, you have to add :visible
to get the same kind of behaviour.
To make sure only one visible button contains "Submit":
cy.get('button:visible:contains("Submit")').should('have.length', 1);
To make sure only one visible button inside a "li" element contains the text "Submit":
cy.get('li button:visible:contains("Submit")').should('have.length', 1);
To count the "li" elements that contain one or more visible "Submit" buttons:
cy.get('li:has(button:visible:contains("Submit"))').should('have.length', 1);
If you know the right amount of buttons that need to have that label, you could try:
cy.get('li').then($el => {
cy.wrap($el).find(".button").then($els => {
expect($els.filter(index => $els.eq(index).is(':contains(Submit)'))).to.have.length(your_amount);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With