1

Im trying to store few strings inside an array.

it('Action -> delete -> check list of camapaigns to delete',function(){
    let campArr=[]
    
    cy.get('md-checkbox').then((box)=>{
        for(let i=1;i<box.length;i++){
            cy.get(`.md-body > :nth-child(${i}) > :nth-child(3)`).then(($el)=>{
                let elToText=$el.text()
                campArr[i-1]=elToText
            })
        }
    })
    cy.log(campArr.length)
    cy.get('md-checkbox').eq(0).click()
    cy.get('.btn-group>button').eq(0).click()
    cy.get('.dropdown-menu-left > :nth-child(3) > .ng-binding').click()
    cy.log(campArr[0])
    for(let i=0;i<campArr.length;i++){
        cy.get(`div.ng-scope > ul > :nth-child(${i+1})`).should('contain.text',campArr[i])
        cy.log('checked')
    }
})

I was able to store the strings inside the array but after exiting .then block, the array is empty. What should i do to keep the values inside the array?

  • [".then() is modeled identically to the way Promises work in JavaScript."](https://docs.cypress.io/api/commands/then#Yields) – ASDFGerte Sep 12 '21 at 13:33
  • I didnt really understand how i should change me code to make this work. – Liel Barouch Sep 12 '21 at 13:56
  • The `then` callback executes some time *after* the rest of your code has completed. It never executes synchronously. So you have to move *all* code -- that needs access to the populated array -- *inside* the `then` callback (or make another function, and call it from there). – trincot Sep 12 '21 at 14:30

1 Answers1

2

The easiest way to make access to the campArr synchronous with the assignment is to use a then callback:

it('Action -> delete -> check list of camapaigns to delete',function(){
    let campArr=[]
    
    cy.get('md-checkbox').then((box)=>{
        for(let i=1;i<box.length;i++){
            cy.get(`.md-body > :nth-child(${i}) > :nth-child(3)`).then(($el)=>{
                let elToText=$el.text()
                campArr[i-1]=elToText
            })
        }
    })
    cy.log(campArr.length)                       // this logs 0!
    cy.get('md-checkbox').eq(0).click()
    cy.get('.btn-group>button').eq(0).click()
    cy.get('.dropdown-menu-left > :nth-child(3) > .ng-binding').click().then(() => {
       cy.log(campArr[0])                       // this logs the item
       for(let i=0;i<campArr.length;i++){ 
           cy.get(`div.ng-scope > ul > :nth-child(${i+1})`).should('contain.text',campArr[i])
           cy.log('checked')
       }
    }
})
Ivan
  • 46
  • 2