'Whats the difference between toBeInTheDocument and getBy* in @testing-library/react

Is there a difference between

expect(screen.queryByText('<something>')).toBeInTheDocument();

And

screen.getByText('<something>');

(The specific getBy* and queryBy* operation are not relevant)

In react-testing-library?



Solution 1:[1]

getByText tries to find the node and throws an error when it is not able to find it. This will cause the test to fail immediately.

queryByText on the other hand will return null if it is unable to find the node.

Let's suppose you have text <something> in the component that was rendered, you can assert if it has been rendered or not.

If sure that the text has been rendered, then you can simply use getByText

expect(screen.getByText('<something>')).toBeInTheDocument();

and the test would pass.

If for the scenario the text did not render then the above assertion will thrown an error and fail the test case.

In such cases queryByText text makes the most sense

When has not been rendered

expect(screen.getByText('<something>')).not.toBeInTheDocument(); // throws an error

expect(screen.queryByText('<something>')).not.toBeInTheDocument(); // asserts as true

Output comparison

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Raz Luvaton