How do I check if a component is not present, i.e. that a specific component has not been rendered?
74
votes
Which renderer do you use, enzyme or the react test renderer?
– Andreas Köberle
I am using Enzyme.
– JoeTidee
Isn't it valid just check if an element from this component is on the screen?
– sergioviniciuss
Oops.. I mean, check if the element is NOT on the screen, by doing something like this: expect(component.find('ELEMENT').exists()).toBe(false);
– sergioviniciuss
6 Answers
50
votes
You can use enzymes contains
to check if the component was rendered:
expect(component.contains(<ComponentName />)).toBe(false)
85
votes
8
votes
Providing a slightly updated answer based on the documentation for enzyme-matchers's toExist
. This will require you to install the enzyme-matchers
package.
function Fixture() {
return (
<div>
<span className="foo" />
<span className="bar baz" />
</div>
);
}
const wrapper = mount(<Fixture />); // mount/render/shallow when applicable
expect(wrapper.find('span')).toExist();
expect(wrapper.find('ul')).not.toExist();
6
votes
If you're using react-testing-library (I know the OP wasn't but I found this question via web search) then this will work:
expect(component.queryByText("Text I care about")).not.toBeInTheDocument();
You can query by Text
, Role
, and several others. See docs for more info.
Note: queryBy*
will return null
if it is not found. If you use getBy*
then it will error out for elements not found.
4
votes