Cypress foreach loop stop condition

Viewed 301

I need some help with the following loop:

 localStorage.removeItem('DDFound');

 cy.get(sel).each(($el, index, $list) => {
    
    if(localStorage.getItem('DDFound')!='1')
    {      
    cy.log(localStorage.getItem('DDFound'));
    cy.wrap($el).click().then(()=> {
      cy.get(table).then(elx => {
            if(elx.find(tableitem).length > 0) {
                cy.get(tableitem).click();
                cy.get(lable).should('contain.text',"Item")
                localStorage.setItem('DDFound','1');                  
            }
            
        })
    });
    }
});

I would like to break just after finding the right item(tableitem) and for that, I'm setting a localstorage (didn't find any other way) but it looks like cypress runs all items in each loop in parallel and not getting to the if(localStorage.getItem('DDFound')!='1') after each element.

2 Answers

You can stop the .each() loop early by returning false in the callback function. In your case, we can just return the value if DDItem does not equal one.

 localStorage.removeItem('DDFound');

 cy.get(sel).each(($el, index, $list) => {
    
    if(localStorage.getItem('DDFound')!='1')
    {      
    cy.log(localStorage.getItem('DDFound'));
    cy.wrap($el).click().then(()=> {
      cy.get(table).then(elx => {
            if(elx.find(tableitem).length > 0) {
                cy.get(tableitem).click();
                cy.get(lable).should('contain.text',"Item")
                localStorage.setItem('DDFound','1');                  
            }
            
        })
    });
    }

    return localStorage.getItem('DDFound') !== 1
});

If you have complex code inside the .each() you should wrap it in a promise

let found = false;

cy.get(sel).each(($el, index, $list) => {
    
  if (found) return false;   // early exit

  return new Cypress.Promise(resolve => {

    cy.wrap($el).click().then(() => {
      cy.get(table).then(elx => {
        if (elx.find(tableitem).length > 0) {
          cy.get(tableitem).click();
          cy.get(label).should('contain.text',"Item")
          found = true;
        }
        resolve()      // wait for above to complete
      })
    })

  })
})

See .each() - Promises

Promises are awaited

If your callback function returns a Promise, it will be awaited before iterating over the next element in the collection.

Related