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.
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!
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.
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.
Using the render() method from the react testing library in the above test to render the Counter component in a virtual DOM.
ShallowWrapper
has a isEmptyRender()
function:
expect(comp.isEmptyRender()).toBe(true)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With