22

In react testing library, we have two functions called toBeInTheDocument() and toBeVisible().

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

It seems, both of the above two assertions behave in the same way. What is different of these two functions and whats are the use cases of them?

Ayesh Weerasinghe
  • 580
  • 2
  • 7
  • 19
  • 1
    I'm not familiar with these assertions but here are a couple of general points: 1. You can have a node the DOM but currently not visible. 2. Visibility might not just be "visible = true" but also *shown on the screen*. If an element is off the viewport, it might be considered not visible. – VLAZ Nov 05 '21 at 11:47

1 Answers1

30

According to the testing-library/jest-dom documentation,

toBeInTheDocument simply finds element is in DOM Tree regardless of visibility

toBeVisible checks for multiple attributes to see if it's visible such as

  1. display not equal to none
  2. opacity greater than 0
  3. hidden attribute does not exist
  4. visibility not equal to hidden or collapse
  5. checks for element, if it's document and parent is visible
Jonathan Southern
  • 1,121
  • 7
  • 22
  • Do either take into account elements height? If the height of the element has been set to `0` with overflow hidden (often used in animations) is there a way to check if that element is no longer visible? – Stretch0 May 20 '22 at 09:45
  • @Stretch0 No, neither take it into account. There are also no plans to support it either: https://github.com/testing-library/jest-dom/issues/450 . In the issues thread you can see some of the workarounds listed however. – Jonathan Southern May 24 '22 at 06:33