首页 > 解决方案 > 赛普拉斯:每个都有内部承诺 - 打破循环

问题描述

我正在使用赛普拉斯,我想退出包含承诺的每个循环。

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 ###
        }
    });
});

有人能帮我吗?

标签: javascriptloopspromiseeachcypress

解决方案


您可以return false提前休息,请参阅docs

提前返回
您可以通过在回调函数中返回 false 来提前停止 .each() 循环。

柏树小提琴测试

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

循环的替代方法是用于.contains('my text')定位您想要的文本。
请注意,.contains()它会进行部分匹配,因此您可以忽略子文本。

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

推荐阅读