What is the difference between toBeInTheDocument() and toBeVisible()?

Viewed 6886

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?

1 Answers

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
Related