[英]Cypress: each with internal promise - break loop
I'm using Cypress and I want to to exit from a each loop that contains a promise.我正在使用 Cypress,我想从包含承诺的 each 循环中退出。
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?有人能帮我吗?
You can return false
to break early, see docs .您可以return false
以提前中断,请参阅文档。
Return early早点回来
You can stop the .each() loop early by returning false in the callback function.您可以通过在回调函数中返回 false 来提前停止 .each() 循环。
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.循环的替代方法是使用.contains('my text')
来定位您想要的文本。
Note that .contains()
does a partial match, so you can ignore child texts.请注意, .contains()
进行部分匹配,因此您可以忽略子文本。
cy.get('div.myclass span#myid')
.contains('span text - find this')
.as('mySection')
Just add return false
at the end and you will exit the function.只需在最后添加return false
退出该功能。
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
}
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.