Files
cypress/docs/source/api/commands/each.md
T
2017-05-24 16:56:23 -04:00

2.2 KiB

title, comments, description
title comments description
each true

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

Each time the callback function runs, it is invoked with three arguments:

  • value
  • index
  • collection

Syntax

.each(function(value, index, collection) {})

Usage

.each() requires being chained off another cy command that yields an array like structure (arrays or objects with a length property).

{% fa fa-check-circle green %} Valid Usage

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

{% fa fa-exclamation-triangle red %} Invalid Usage


cy.each(function(){...})            // Errors, cannot be chained off 'cy'
cy.location().each(function(){...}) // Errors, 'location' doesn't yield an array

Yields

.each() yields the original array.

Timeout

Examples

DOM Elements

Iterate over an array of DOM elements

cy
  .get('ul>li')
  .each(function($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(function($li, index, $lis){
    return 'something else'
  })
  .then(function($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(function(num, index, array){
    return new Cypress.Promise(function(resolve){
      setTimeout(function(){
        resolve()
      }, num * 100)
    })
  })

Notes

Stop each prematurely

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

See also