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

Aye*_*ghe 27 unit-testing jestjs react-testing-library

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

1 expect(screen.getByText('hello')).toBeInTheDocument();
2 expect(screen.getByText('hello')).toBeVisible();
Run Code Online (Sandbox Code Playgroud)

看来这两个断言的行为是相同的。它们有什么区别,各自的用例是什么?

Jon*_*ern 39

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

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

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

  1. display不等于none
  2. opacity比...更棒0
  3. hidden属性不存在
  4. visibility不等于hiddencollapse
  5. 检查元素,如果它是文档且父元素可见