Home > Enterprise >  Iterating Array in Cypress
Iterating Array in Cypress

Time:11-17

I am pushing Div element in an array and then iterating each one by one, but when I came out of first each section the array length becomes 0 and i am unable to enter into for loop.

in for loop, i want to click a section in each div and perform an assertation and go back to the previous section.

`

let Array =[]
cy.get('.tag-wrapper-item').each(($pills) => {
    cy.log($pills)
    // cy.log('Success')
    Array.push($pills)
    cy.log(Array.length)

 })
cy.log(Array.length)
   for (const element of Array) {
    cy.wrap(element).click()
    cy.wrap(element).find('.--tag.tag-link.--active.tag-selector-button-link').click()
    var OneOffModel = element.text()
    cy.get('.heading-markdown').contains(OneOffModel)
    cy.go('back')
  } 

`

CodePudding user response:

Cypress commands asynchronous, so at the time the Cypress walks through your array, it's not yet been initialized.

To fix this, you can wrap your code with a then callback:

let Array =[]
cy.get('.tag-wrapper-item').each(($pills) => {
    cy.log($pills)
    // cy.log('Success')
    Array.push($pills)
    cy.log(Array.length)

 })
cy.then(() => {
   cy.log(Array.length)
   for (const element of Array) {
    cy.wrap(element).click()
    cy.wrap(element).find('.--tag.tag-link.--active.tag-selector-button-link').click()
    var OneOffModel = element.text()
    cy.get('.heading-markdown').contains(OneOffModel)
    cy.go('back')
  } 
})
  • Related