【问题标题】:Cypress getByTestId, queryByTestId, findByTestId to check if element doesn't existCypress getByTestId、queryByTestId、findByTestId 检查元素是否不存在
【发布时间】:2019-11-22 14:09:18
【问题描述】:

我正在尝试使用 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").

谁能解释一下这四个有什么区别。

谢谢

【问题讨论】:

  • 其中一些不是赛普拉斯 API 的一部分 - 您是否也在使用例如testing-library.com/docs/cypress-testing-library/intro?
  • 是的,我正在使用“testing-library/cypress”
  • 如果维护者的行为与内置方法不同,可能值得向维护者提出问题。
  • 看到这个comment,说findBy*` API 搜索一个元素,如果没有找到就会抛出一个错误,所以从逻辑上讲你不能使用cy.findByTestId(...).should("not.exist")
  • 谢谢,我在这里testing-library.com/docs/react-testing-library/cheatsheet 找到了相同的信息,说如果找不到元素,findBygetBy 会返回错误,这就是为什么不能用于我的测试的原因。 queryBy 返回 null 并且不会通过测试。但是当元素不在 DOM 中时,cy.get('[data-testid="my-button"]') 会返回什么?

标签: javascript testing integration-testing cypress end-to-end


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2020-10-24
    • 2012-11-20
    • 2010-09-11
    • 2021-05-04
    • 1970-01-01
    相关资源
    最近更新 更多