In Cypress how to count a selection of items and get the length?

Found a solution, This works to check a count of items:

cy.get('.datatable').find('tr').should('have.length', 4)

This does not work with the Cypress.$() method of notation.

Reference: https://docs.cypress.io/guides/references/assertions.html#Length


You can also get the length of a selection of items through its property, for example:

cy.get('.datatable').find('tr').its('length').should('eq', 4)
cy.get('.datatable').find('tr').its('length').should('be.gte', 4)

In addition to should('have.length', 4)

enter image description here I tested with Cypress version 3.1.0 and 3.2.0.


if you want more flexible and have a dynamic result use this.

cy.get('.listings-grid')
  .find('.listing')
  .then(listing => {
    const listingCount = Cypress.$(listing).length;
    expect(listing).to.have.length(listingCount);
  });

Tags:

Cypress