【问题标题】:What is the difference between toBeInTheDocument() and toBeVisible()?toBeInTheDocument() 和 toBeVisible() 有什么区别?
【发布时间】:2021-11-05 11:41:08
【问题描述】:

在 react 测试库中,我们有两个函数,分别称为 toBeInTheDocument() 和 toBeVisible()。

1 expect(screen.getByText('hello')).toBeInTheDocument();
2 expect(screen.getByText('hello')).toBeVisible();

看来,以上两个断言的行为方式相同。这两个函数有什么不同,它们的用例是什么?

【问题讨论】:

  • 我不熟悉这些断言,但这里有几个一般要点: 1. 您可以在 DOM 中拥有一个节点,但目前不可见。 2. 可见性可能不仅是“visible = true”,而且还显示在屏幕上。如果一个元素不在视口中,它可能被认为是不可见的。

标签: unit-testing jestjs react-testing-library


【解决方案1】:

根据testing-library/jest-dom 文档,

toBeInTheDocument 简单地发现元素在 DOM 树中,无论可见性如何

toBeVisible 检查多个属性是否可见,例如

  1. display 不等于 none
  2. opacity 大于 0
  3. hidden 属性不存在
  4. visibility 不等于 hidden 或 collapse
  5. 检查元素,如果它的文档和父元素可见

【讨论】:

    猜你喜欢
    • 2021-10-20
    • 2010-10-02
    • 2011-12-12
    • 2010-09-16
    • 2012-03-14
    • 2012-02-06
    • 2011-02-25
    • 2011-11-22
    • 2015-03-26
    相关资源
    最近更新 更多