toBeInTheDocument() 和 toBeVisible() 有什么区别?

问题描述 投票:0回答:1

在React测试库中,我们有两个函数,称为

toBeInTheDocument()
toBeVisible()

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

这两个断言似乎表现相同。它们有什么区别,各自的用例是什么?

unit-testing jestjs react-testing-library
1个回答
39
投票

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

toBeInTheDocument 只是查找元素位于 DOM 树中,无论可见性如何

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

  1. display
    不等于
    none
  2. opacity
    大于
    0
  3. hidden
    属性不存在
  4. visibility
    不等于
    hidden
    collapse
  5. 检查元素,如果它是文档且父级可见
© www.soinside.com 2019 - 2024. All rights reserved.