How to pass a value to the variable outside each() loop in cypress


I have each() loop that is going through elements:

let counter = 0

cy.get(selector).then(items => {
  cy.wrap(items).each(($item) => {
    counter += 1

cy.wrap(items).should('have.length', counter)

Expected result:
Add +1 value to the counter variable each time you pass the loopy and in final assertion length of items should be equal to counter.

Actual result:
+1 value is not added to the counter variable when you pass the loop and length of items is always equal to 0 in final assertion even if length of items > 0

How can I pass a value e.g. +1 to the variable outside of the each() loop?

I could not find an answer in the existing topics.


If you are directly checking the number of items, you can directly do this:

cy.get(selector).should('have.length', 6)

If you want to do the counter approach you can do this:

let counter = 0

  .each(($item) => {
    counter += 1
  .then(() => {
    cy.get(selector).should('have.length', counter)

Answered By – Alapan Das

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published