Jest Enzyme test a React component that returns nu

2020-03-01 03:56发布

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.

4条回答
劳资没心,怎么记你
2楼-- · 2020-03-01 04:27
   expect(comp.type()).toEqual(null)

That's it!

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

查看更多
对你真心纯属浪费
3楼-- · 2020-03-01 04:32

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

expect(comp.html()).toBeNull();
查看更多
做自己的国王
4楼-- · 2020-03-01 04:34

ShallowWrapper has a isEmptyRender() function:

expect(comp.isEmptyRender()).toBe(true)
查看更多
何必那么认真
5楼-- · 2020-03-01 04:41

we use the following with jest-enzyme

expect(comp).toBeEmptyRender()
查看更多
登录 后发表回答