Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest - how to test if a component does not exist?

Tags:

jestjs

enzyme

How do I check if a component is not present, i.e. that a specific component has not been rendered?

like image 491
JoeTidee Avatar asked Sep 16 '17 09:09

JoeTidee


People also ask

How do you use shallow in Jest?

shallow method is used to render the single component that we are testing. It does not render child components. In Enzyme version less than 3, the shallow method does not have the ability to access lifecycle methods. But in Enzyme version 3, we have this ability.

How do you check if element exists in react testing library?

toBeInTheDocument() matcher, which can be used to assert that an element is in the body of the document, or not. This can be more meaningful than asserting truthfulness in this case. Also it would be better to get the button by role instead of text since it is a preferable way by priority.

What does Querybytestid return?

Returns a single element with the given testId value for the data-test-id attribute, defaulting to an exact match.

How do you know if an element is not present in Jest?

Query the element. The most important thing to note when testing for non-existence is that you'll have to query items. When looking for an element, you might have used getBy or getAllBy and then something. This works fine if we know the element exists, but Jest will throw an error when these are not found.


1 Answers

.contains receives a React Node or array of Nodes as an argument. Instead, use .find:

expect(wrapper.find('selector').exists()).toBeTruthy() 
like image 164
Artem Kislov Avatar answered Oct 13 '22 04:10

Artem Kislov