Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Cypress how to count elements containing the text?

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?

like image 289
drazewski Avatar asked Jun 24 '20 10:06

drazewski


2 Answers

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);
like image 74
Hendrik Jan Avatar answered Jan 03 '23 01:01

Hendrik Jan


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);
 })
like image 26
Alex Izbas Avatar answered Jan 03 '23 00:01

Alex Izbas