Cypress:.each 循环查找有价值的元素

Ste*_*ple 5 cypress

应该有更好的方法来做到这一点,但我找不到。页面上有许多具有相同选择器的元素。仅值属性不同。控件是动态创建的,因此我无法更精确地确定它们。

我正在使用 Cypress 搜索具有特定值的元素。HTML 看起来像这样:

<input type="button" value="Save" data-cy-component="button-button" class="btn form-control btn-info">
Run Code Online (Sandbox Code Playgroud)

当我找到它时,我想单击它并跳出循环。

这就是我所拥有的:

 const buttonButton = '[data-cy-component=button-button]';
 cy.get(buttonButton).each(($el, index, $list) => {
  cy.log(`index: ` + index);
  if (index === 5) {
    cy.wrap($el)
      .should('have.value', 'Save')
      // Click Save button.
      .click();
  }
});
Run Code Online (Sandbox Code Playgroud)

这种方法有效,但似乎很脆弱。如果我的“保存”按钮不再是第五(或第六)元素,则测试将失败。有没有办法可以用 IF 而不是 SHOULD 来测试它?

Mac*_*urt 2

我可能不明白你在做什么,如果我有错误,请在评论中纠正我。我相信你想做的是通过它的值找到一个元素。我写了这个并且有效。如果您想要做的事情不同,请纠正我..

<input type="button" value="Save" data-cy-component="button-button" class="btn form-control btn-info">


cy.get('[value="Save"]').should('exist');
cy.get('[value="Save"]').click();
cy.get('input[value="Save"]').should('exist');
cy.get('input[value="Save"]').click();
Run Code Online (Sandbox Code Playgroud)

这也有效

cy.get('[data-cy-component=button-button][value=Save]').should('exist');
cy.get('[data-cy-component=button-button][value=Save]').click();
Run Code Online (Sandbox Code Playgroud)

根据您下面的评论,您说屏幕上有 2 个

我创建了这个 HTML 来测试它。请注意,其中一个是隐藏的。我需要知道是什么让你的隐藏或不可见。它们是否位于不同的 div 中,并且可能具有唯一的 id?

<input type="button" value="Save" data-cy-component="button-button" class="btn form-control btn-info">
<input style="visibility:hidden" type="button" value="Save" data-cy-component="button-button" class="btn form-control btn-info">


cy.get('[value="Save"][style!="visibility:hidden"]').should('length', 1);
cy.get('[value="Save"][style!="visibility:hidden"]').click();
Run Code Online (Sandbox Code Playgroud)