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

JavascriptReactjsJestjsEnzyme

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

ShallowWrapper has a isEmptyRender() function:

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

Solution 2 - Javascript

expect(comp.type()).toEqual(null)

That's it!

or:

expect(comp.get(0)).toBeFalsy()

Solution 3 - Javascript

According to ShallowWrapper::html implementation it returns null if component instance type is null, as a result of render.

expect(comp.html()).toBeNull();

Solution 4 - Javascript

we use the following with jest-enzyme

expect(comp).toBeEmptyRender()

Solution 5 - Javascript

As mentioned in Benjamin Intal's solution, I tried to use myComponent.isEmptyRender(), but it was unexpectedly returning false, even though myComponent.children().length was returning 0.

The problem turned out to be that myComponent was coming from a call to .find() on another shallow-rendered component. In this situation, an extra call to .shallow() on the found child component is necessary to get isEmptyRender() to work properly:

const parentComponent = shallow(<MyParentComponent isMyChildHidden={true} />);
const childComponent = parentComponent.find('MyChildComponent');

expect(childComponent.shallow().isEmptyRender()).toBe(true);

Reference: https://github.com/enzymejs/enzyme/issues/1278

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionklugjoView Question on Stackoverflow
Solution 1 - JavascriptBenjamin IntalView Answer on Stackoverflow
Solution 2 - JavascriptAbdennour TOUMIView Answer on Stackoverflow
Solution 3 - JavascriptShoaib NawazView Answer on Stackoverflow
Solution 4 - JavascriptducciView Answer on Stackoverflow
Solution 5 - JavascriptJon SchneiderView Answer on Stackoverflow