首页 > 解决方案 > 打破柏树中的if循环

问题描述

我们有一个场景如下

iterate over name elements in the page
 if(name.text() == expName)
{
name.click()
exit from if loop
}
else
{
createName()
}

我如何在 cypress 中实现这一点,因为 return false 没有从 if 循环中退出。这是我尝试过的代码

export function addProtocol(protocolName, protocolStatus) {
  let flag = "false";
  subject.view({ name: "ProtocolsExplorerList" }).as('currentView');
  cy.get('@currentView').find('td textarea').each($el => {
    cy.wrap($el).invoke('val').then($value => {
      console.log("valueee:" + $value);
      if ($value == protocolName) {
        cy.get($el).click();
        flag = "true";
        return false;
      }
    })
  })

  if (flag == "false") {

    subject.button({ class: "New" }).click();
    subject.field("Name").type(protocolName);
    subject.field("Status").setCaption(protocolStatus);
    save();
    cy.contains(protocolName).click();

  }

}

请问有什么建议吗?谢谢。

标签: javascriptui-automationcypress

解决方案


问题是您没有从each回调中返回false. 您从then回调中返回false. then回调通常异步运行,这意味着回调在each迭代完成后执行。

我不熟悉赛普拉斯,但假设他们在他们的集合上实现了迭代器协议,你可以使用:

const textareas = cy.get('@currentView').find('td textarea');

for (const $el of textareas) {
  const $value = await cy.wrap($el).invoke('val');
  console.log("valueee:" + $value);
  if ($value == protocolName) {
    cy.get($el).click();
    flag = "true";
    break;
  }
}

您必须将包装功能设为 anasync function才能使用await.


推荐阅读