Cypress getByTestId、queryByTestId、findByTestId 检查元素是否不存在

ole*_*k91 8 javascript testing integration-testing end-to-end cypress

我正在尝试使用 Cypress 和testing-library/cypress 检查 DOM 树中是否不存在元素。

如果我尝试cy.getByTestId("my-button").should("not.exist")测试失败,因为它找不到元素。

如果我cy.findByTestId("my-button").should("not.exist")这样做也会因为超时而失败。

cy.queryByTestId("my-button").should("not.exist")如果我执行以下任一操作,则测试确实有效

cy.get('[data-testid="my-button"]').should("not.exist")

有人可以解释一下这4个有什么区别吗?

谢谢

sun*_*ung 12

https://testing-library.com/docs/dom-testing-library/api-queries

  • getBy如果找不到元素会抛出错误
  • findBy如果找不到元素,将返回并拒绝 Promise
  • queryBy如果没有找到元素将返回 null:

这对于断言不存在的元素很有用。

看起来queryBy是你解决这个问题的最佳选择