Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest Enzyme test a React component that returns null in render method

I have a component that returns null in render under certain conditions:

render() {   if (this.props.isHidden) {       return null;   }    return <div>test</div>; } 

I want to check if the component is null when isHidden is true with jest and enzyme:

describe('myComp', () => {     it('should not render if isHidden is true', () => {         const comp = shallow(<myComp isHidden={true} />);         expect(comp.children().length).toBe(0);     }); }); 

This works but is there a more idiomatic way to write this test ? Testing for components that render as null is quite a common scenario.

like image 222
klugjo Avatar asked Nov 13 '17 07:11

klugjo


People also ask

How do you check if a component is null React?

To check for null in React, use a comparison to check if the value is equal or is not equal to null , e.g. if (myValue === null) {} or if (myValue !== null) {} . If the condition is met, the if block will run. Copied!

Which is better Enzyme or Jest?

Shallow rendering is one way that Enzyme keeps tests simpler than Jest. When you shallow-render a component with Enzyme, you render only that component. Enzyme doesn't render any of the children of that component. This is a useful restriction that ensures that you aren't testing too much in one test.

Should I use Enzyme with Jest?

Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.

Which method from Jest is used to test React component?

Using the render() method from the react testing library in the above test to render the Counter component in a virtual DOM.


1 Answers

ShallowWrapper has a isEmptyRender() function:

expect(comp.isEmptyRender()).toBe(true) 
like image 161
Benjamin Intal Avatar answered Sep 24 '22 10:09

Benjamin Intal