user
user

Reputation: 1759

Cypress : How to use variables inside each function

I have a local variable that I am trying to access within the each function as below :

var i = 0
cy.get('body').then((body) => {
      cy
        .get('.classname')
        .each(($element) => {
       
       cy.log(i) //returns empty value
       ///ACCESS THE "i" variable here
    }
   }

How can the local variable be accessed inside the each function? Is there a restriction on the scope of the variables inside the each function

Upvotes: 0

Views: 646

Answers (2)

Fody
Fody

Reputation: 31934

You can access the i variable inside the .each() but cy.log() will capture the initial value only.

console.log will show you the current value.

const texts = ['abc', '123']
cy.get('body').then((body) => {
  cy.get('.classname')
    .each(($element, i) => {
       cy.wrap($element).should('contain.text', texts[i])
    }
  }

Upvotes: 1

Alapan Das
Alapan Das

Reputation: 18634

You cannot chain off each to cy. Cypress Docs

You can use it like this:

var i = 0
cy.get('selector').each(($ele) => {
  cy.log(i) //prints 0
})

Upvotes: 0

Related Questions