选择不等于特定字符串的元素

时间:2019-04-26 17:56:30

标签: cypress

我试图选择一个不正确的答案(单选按钮)以显示错误消息,但是答案是随机的(正确答案除外)。

如何说出单选按钮,然后使用赛普拉斯断言单击一个不等于“正确答案”的按钮?

cy.get('[data-cy="multipleChoiceQuestionAnswer"]')
        .should('not.contain', 'correct answer')//.find('label').not('corect answer')//.not.includes('correct answer')
.click()

我希望能够为错误答案选择两个单选按钮之一,现在我只能选择正确答案。

1 个答案:

答案 0 :(得分:0)

好吧

  • 请注意,.should('not.contain', 'correct answer')是断言,不是过滤/获取某些元素的方法。 从本质上讲,这只是一种检查(又称“声明”)是否像您期望的那样的方式。 像您这样的断言仅对于使赛普拉斯日志打印出来是有用的 enter image description here 阅读时就像在讲
  

“为什么Cypress,我选择了一个元素,请检查一下它是否包含正确答案?”

  • 断言有什么用?当一切正常时,但在测试失败时,它们没有用。 因为没有断言,赛普拉斯会告诉您“没有元素”,您会发现自己处于破碎测试的背后,但您不知道赛普拉斯找不到哪个元素。 放置一些“关键点”断言可以使您理解为什么测试在短时间内失败。

无论如何:如果您的HTML是这样的

<div data-cy="multipleChoiceQuestionAnswer"><label>correct answer<input type="checkbox"/></label></div>
<div data-cy="multipleChoiceQuestionAnswer"><label>no<input type="checkbox"/></label></div>
<div data-cy="multipleChoiceQuestionAnswer"><label>nope<input type="checkbox"/></label></div>

您可以实现自己的目标:

cy.get('[data-cy="multipleChoiceQuestionAnswer"]').then(els => {
  // `els` is a jQuery instance, let's parse the various elements
  let $el;
  for(let i = 0, n = els.length; i < n; i++) {
    // it transforms every element in a jQuery instance
    $el = Cypress.$(els[i]);
    // it uses jQuery to get the label text
    if($el.find("label").text() !== "correct answer") {
      // it stops as soon as the answer isn't the correct one
      break;
    }
  }
  // returns the element to be clicked
  return $el.find("input");
})
// it assert about it (to have a useful hint in the Cypress command log)
.should("not.contain", "correct answer")
// clicks it
.click();

我希望代码是不言自明的(如果不是这样,请问我更多的说明)

相关问题