What is the difference between toBeInTheDocument() and toBeVisible()?
Asked Answered
R

1

29

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?

Rigamarole answered 5/11, 2021 at 11:41 Comment(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.Rodriques
H
42

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
Horne answered 5/11, 2021 at 13:55 Comment(5)
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?Offense
@Offense No, neither take it into account. There are also no plans to support it either: github.com/testing-library/jest-dom/issues/450 . In the issues thread you can see some of the workarounds listed however.Horne
toBeVisible() seems like the better choice, is there a reason the official docs default to toBeInTheDocument() instead?Nombril
@CathalMacDonnacha i think toBeInTheDocument has better performance than toBeVisible since it only checks the DOMTeodoro
Yea that's what I thought. toBeVisible seems to be better for accessibility though.Nombril

© 2022 - 2024 — McMap. All rights reserved.