How to Get Multiple Elements in Cypress
In order to work on multiple in Cypress, we can use the built-in each
command chained to a cy.get
command in the following way:
const labels = [
'Features',
'How it works',
'Dashboard'
];
cy.get('ul li').each((item, index, list) => {
// Returns the elements from the cy.get command
expect(list).to.have.length(3);
// Returns the current element from the loop
expect(Cypress.$(item).text()).to.eq(labels[index]);
});
Note that it only works on array-like structures, so you only want to call it on multiple elements.
Let's say we want to work with the elements of a navigation menu. Here, we try to verify the list elements of an unordered list. The each
command accepts three arguments in a callback function. These are in order:
item
: The current (in this caseli
) element in the listindex
: The index of the looplist
: The element itself that has been selected withcy.get
, in this case, an array ofli
In the above code example, we verify the length of the list elements. Note that this will run the same expect
three times. This could be rewritten to the following in order to execute the expect
only once:
cy.get('ul li').should('have.length', 3);
Also, one thing to keep in mind: you need to wrap the current item with Cypress.$
in order to chain commands from it. Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: