Home > Mobile >  Cypress How can I get the same-named element count
Cypress How can I get the same-named element count

Time:10-22

in selenium I just creating web element list to learn that, in cypress I use .each() method to iterate in same-named elements but Some times I just need to know the same-named elements number to use this number somewhere else.

How can I do that in cypress?

CodePudding user response:

You can store the length of the yielded list of elements via an alias.

cy.get('foo')
  .its('length')
  .as('listLength');
... // later
cy.get('@listLength').should('be.gte', 1);

If you need to access the variable value synchronously, you could store it in a Cypress environment variable, or a regular JS variable.

let lengthVar;
cy.get('foo')
  .its('length')
  .then((length) => {
    // If storing in a Cypress.env() variable
    Cypress.env('listLength', length);
    // If storing in a traditional JS variable
    lengthVar = length;
  });

CodePudding user response:

You can do something like this:

cy.get('element').its('length').should('eq', 6)

Or, if you want to save it and use it later

let lenVal
cy.get('element').its('length').then((len) => {
  lenVal = len
})
  • Related