我需要通过具有相同 CSS 选择器的多个元素运行循环,如果 element.text() 与字符串匹配,则返回 true。如果没有匹配项,则最后返回 false。
我尝试了类似下面的方法,但没有奏效:
getProfilePresentOrNot(profileName) {
var flag = 0;
cy.get('li>div>div>span').each(($el,index,$list) => {
if ($el.text().includes(profileName)) {
flag=1;
}
});
return flag;
}
此功能始终returns 0
即使我可以确认 if 块中的条件满足。
最佳答案
@JeremyKahan 是正确的,就像混契约(Contract)步和异步代码。同步代码总是首先执行。
基本上,您可以通过添加几个 console.log()
来查看它。
function getProfilePresentOrNot(profileName) {
var flag = 0;
cy.get("li>div>div>span").each(($el, index, $list) => {
if ($el.text().includes(profileName)) {
console.log('Setting flag')
flag = 1;
}
});
console.log('Returning flag')
return flag;
}
这将在 devtools 中打印Returning flag
Setting flag // because cy.get(...).each(...) ran later
您可以使用自定义命令Cypress.Commands.add('getProfilePresentOrNot', (profileName) => {
cy.get("li>div>div>span")
.invoke('text') // all text from all spans
.then(allText => allText.includes(profileName)) // returns the result of .includes(...)
})
必须像这样使用cy.getProfilePresentOrNot('someprofilename')
.then(isPresent => { // true or false
if (isPresent) {
...
}
})
或者如果您是 绝对有把握这一切li>div>div>span
存在于页面中,您仍然可以使用函数但切换到同步 Cypress 代码(即 jQuery)。function getProfilePresentOrNot(profileName) {
const allText = Cypress.$("li>div>div>span").text()
return allText.includes(profileName);
}
可以这样调用const isPresent = getProfilePresentOrNot('someprofilename')
自定义命令是最安全的,因为在生产网页上,由于无法立即找到元素,有很多事情可能会使您的测试失败,而 Cypress 异步命令具有避免这些问题的内置机制。
关于javascript - 在 Cypress 循环中,如果条件满足则返回 true,否则在迭代结束后返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67996982/