Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 assertions behave the same. What is their difference, and what are the use cases for each?

like image 229
Ayesh Weerasinghe Avatar asked Sep 03 '25 09:09

Ayesh Weerasinghe


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
like image 161
Jonathan Southern Avatar answered Sep 05 '25 00:09

Jonathan Southern



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!