Mark Half
Mark Half

Reputation: 55

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?

Upvotes: 4

Views: 720

Answers (2)

Richard Matsen
Richard Matsen

Reputation: 23533

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

Upvotes: 9

Alapan Das
Alapan Das

Reputation: 18601

Just add return false at the end and you will exit the function.

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

Upvotes: 0

Related Questions