cypresscypress-each

Why added value en each loop hasn't been stored on next iteration?


Brief logic is the next: after clicking on 'li' element, request is sent, and based on response value of 'contacts', it should select if it's greater than 0, once such element is find, i need to break each loop. But currently, despite I set value, which should break each loop on next iteration (returns false). count[] has been restored with old values, what's an issue?

    cy.get('div[id=company_select]').then($el => {

        const count = []
        cy.wrap($el).click().find('li').each((element, index) => {
            cy.intercept('GET', '**/company/view-json**').as('getCompanyProps')

            cy.log(count.length)
            if (count.length > 0) {
                return false
            } else {
                cy.wrap(element).click().wait('@getCompanyProps').then((interception) => {
                    if (interception.response.body.contacts.length === 0) {
                        cy.wrap($el).find('button[vs__clear]').click()
                    } else {
                        count.push(1)
                        cy.log(count.length)
                    }
                })
            }
        })

    })

cy log


Solution

  • You can't early-exit with return false in this scenario, but you can use count to prevent inner execution after body.contacts.length > 0.

    cy.intercept('GET', '**/company/view-json**').as('getCompanyProps') // this can be here
    
    cy.get('div[id=company_select]').then($el => {
    
      const count = []
      cy.wrap(count).as('count')   // make an alias value of the count variable
    
      cy.wrap($el).click().find('li')
        .each((element, index) => {
    
          cy.get('@count').then(count => {  // retrieve count asynchronously
            if (count.length === 0) {       // no result yet?
                    
              cy.wrap(element).click().wait('@getCompanyProps')
                .then((interception) => {
                  if (interception.response.body.contacts.length === 0) {
                    cy.wrap($el).find('button[vs__clear]').click()
                  } else {
                    count.push(1)
                    console.log(count.length)
                  }
                })
            }
          })
        })
    })
    

    The reason for this behaviour is the mixture of asynchronous commands like .wait('@getCompanyProps') and synchronous code for checking the early exit.

    If you use console.log() instead of cy.log() to debug the values, you'll see the logs before the early exit all run before the logs after count.push(1).