javascriptloopscypresseach

How to break the loop in Cypress each()


I'm using Cypress and I want to to exit from a each loop that contains a promise.

cy.get('div').find('div.myclass').each(el => {
    cy.get(el).find('span#myclass').then(span => {
        const myText = Cypress.$(span).clone().children().remove().end().text().trim();
        if (myText === 'somethings') {                
            cy.get(el).as('mySection');
            // ### HERE I WANT TO EXIT ###
        }
    });
});

Can someone help me?


Solution

  • You can return false to break early, see docs.

    Return early
    You can stop the .each() loop early by returning false in the callback function.

    Tested with cypress fiddle

    const selectMySection = {
      html: `
        <div class="myclass">
          <span id="myid">
            <p>child of span1</p>
            <p>child of span2</p>
            span text - find this
          </span>
        </div>
        <div class="myclass">
          <span id="myid">
            <p>child of span3</p>
            <p>child of span4</p>
            span text - ignore this
          </span>
        </div>
      `,
      test: `
        cy.get('div.myclass span#myid')
          .each(($span, i) => {
            console.log('processing span #', i); // only logs 'processing span # 0'
            const text = Cypress.$($span).text()
            if (text.includes('span text - find this')) {
              cy.wrap($span)
                .parent('div.myclass')  // move to parent
                .as('mySection')
              return false;
            }
          })
    
        cy.get('@mySection')
          .then(x => console.log(x))
      `
    }
    it('test selectMySection', () => {
      cy.runExample(selectMySection)
    })
    

    An alternative to looping is to use .contains('my text') to target the text you want.
    Note that .contains() does a partial match, so you can ignore child texts.

    cy.get('div.myclass span#myid')
      .contains('span text - find this')
      .as('mySection')