在 Cypress 循环中,如果条件满足则返回 true,否则在迭代结束后返回 false

问题描述

我需要对具有相同 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 是对的,就像混合同步和异步代码。同步代码总是先执行。

基本上,你可以通过添加几个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;
}

这将打印在开发工具中

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 异步命令具有避免这些问题的内置机制。

>