W3cubDocs

/Cypress

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.location().each(() => {...}) // Errors, 'location' doesn't yield an array

Arguments

callbackFn (Function)

Pass a function that is invoked with the following arguments:

  • value
  • index
  • collection

Yields

  • .each() yields the same subject it was given from the previous command.

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
  })

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

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

Assertions

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

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

© 2020 Cypress.io
Licensed under the MIT License.
https://docs.cypress.io/api/commands/each.html