Skip to main content
Cypress App

each

Iterate through an array like structure (arrays or objects with a length property).

Syntax​

.each(callbackFn)

Usage​

Correct Usage

cy.get('ul>li').each(() => {...}) // Iterate through each 'li'
cy.getCookies().each(() => {...}) // Iterate through each cookie

Incorrect Usage

cy.each(() => {...})            // Errors, cannot be chained off 'cy'
cy.clock().each(() => {...}) // Errors, 'clock' does not yield an array

Arguments​

callbackFn (Function)

Pass a function that is invoked with the following arguments:

  • value - the current item in the collection
  • index - the 0-based index of the current item in the collection
  • collection - the original collection being iterated over

Yields Learn about subject management​

  • .each() yields the same subject it was given.
  • Because .each() is not a query, it is unsafe to chain further commands that act or assert on DOM elements after .each(), as those elements may have re-rendered and gone stale during iteration. Reading the yielded subject in a .then() callback (as in the example below) is safe.

Examples​

DOM Elements​

Iterate over an array of DOM elements

cy.get('ul>li').each(($el, index, $list) => {
// $el is a wrapped jQuery element
if ($el.someMethod() === 'something') {
// wrap this element so we can
// use cypress commands on it
cy.wrap($el).click()
} else {
// do something else
}
})

The original array is always yielded

No matter what is returned in the callback function, .each() will always yield the original array.

cy.get('li')
.should('have.length', 3)
.each(($li, index, $lis) => {
return 'something else'
})
.then(($lis) => {
expect($lis).to.have.length(3) // true
})

Here the .then() callback only reads the yielded array, which is safe. If instead you needed to act or assert on DOM elements that your application may have re-rendered during iteration, re-query them with a Cypress query rather than reusing the subject yielded by .each().

Promises​

Promises are awaited

If your callback function returns a Promise, it will be awaited before iterating over the next element in the collection.

cy.wrap([1, 2, 3]).each((num, i, array) => {
return new Cypress.Promise((resolve) => {
setTimeout(() => {
resolve()
}, num * 100)
})
})

Notes​

Return early​

Stop each prematurely

You can stop the .each() loop early by returning false in the callback function.

Rules​

Requirements Learn about chaining commands​

  • .each() requires being chained off a previous command.

Assertions Learn about assertions​

  • .each() will only run assertions you have chained once, and will not retry.

Timeouts Learn about timeouts​

  • .each() can time out waiting for a promise you've returned to resolve.

Command Log​

  • cy.each() does not log in the Command Log

See also​