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

klugjo picture klugjo · Nov 13, 2017 · Viewed 22.9k times · Source

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.

Answer

Benjamin Intal picture Benjamin Intal · May 2, 2019

ShallowWrapper has a isEmptyRender() function:

expect(comp.isEmptyRender()).toBe(true)