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

Aka*_*ain 4 javascript automated-tests ui-automation cypress

我需要循环遍历具有相同 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;
}
Run Code Online (Sandbox Code Playgroud)

returns 0即使我可以确认 if 块中的条件满足,该函数始终会执行。

Ric*_*sen 5

@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;
}
Run Code Online (Sandbox Code Playgroud)

这将在开发工具中打印

Returning flag
Setting flag                // because cy.get(...).each(...) ran later
Run Code Online (Sandbox Code Playgroud)

您可以使用自定义命令

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(...)
})
Run Code Online (Sandbox Code Playgroud)

必须像这样使用

cy.getProfilePresentOrNot('someprofilename')
  .then(isPresent => {  // true or false
    if (isPresent) {
      ...
    }
  })
Run Code Online (Sandbox Code Playgroud)

或者,如果您绝对确定li>div>div>span页面中存在所有内容,您仍然可以使用函数,但切换到同步 Cypress 代码(即 jQuery)。

function getProfilePresentOrNot(profileName) {
  const allText = Cypress.$("li>div>div>span").text()
  return allText.includes(profileName);
}
Run Code Online (Sandbox Code Playgroud)

可以这样称呼

const isPresent = getProfilePresentOrNot('someprofilename')
Run Code Online (Sandbox Code Playgroud)

自定义命令是最安全的,因为在生产网页上,有很多东西可能会导致测试失败,因为无法立即找到元素,而赛普拉斯异步命令具有内置机制来避免这些问题。