Subtain Shah
Subtain Shah

Reputation: 49

Iterating Array in Cypress

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

Upvotes: 3

Views: 3118

Answers (2)

TesterDick
TesterDick

Reputation: 10525

A better approach might be to get the count of .tag-wrapper-item and loop on that

cy.get('.tag-wrapper-item')
  .its('length')
  .then(count => {
    for (let index = 0; index < count; index++) {
      cy.get('.tag-wrapper-item').eq(index)
        .click()
      cy.get('.tag-wrapper-item').eq(index)
        .find('.--tag.tag-link.--active.tag-selector-button-link')
        .click()
      cy.get('.tag-wrapper-item').eq(index)
        .invoke('text')
        .then(OneOffModel => {
          cy.get('.heading-markdown').contains(OneOffModel)
        })
      cy.go('back')
    }
  })

If you alias each element in the loop, Cypress will try to overcome the detached-from-DOM error when you read the alias

cy.get('.tag-wrapper-item')
  .its('length')
  .then(count => {
    for (let index = 0; index < count; index++) {

      cy.get('.tag-wrapper-item').eq(index)
        .as('current')
        .click()

      cy.get('@current')
        .find('.--tag.tag-link.--active.tag-selector-button-link')
        .click()

      cy.get('@current')
        .invoke('text')
        .then(OneOffModel => {
          cy.get('.heading-markdown').contains(OneOffModel)
        })

      cy.go('back')
    }
  })

Upvotes: 5

Mikhail Bolotov
Mikhail Bolotov

Reputation: 1104

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

Upvotes: 2

Related Questions