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

给你一囗甜甜゛ 提交于 2019-12-18 18:37:22

问题


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.


回答1:


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

That's it!

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




回答2:


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

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



回答3:


ShallowWrapper has a isEmptyRender() function:

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


来源:https://stackoverflow.com/questions/47259061/jest-enzyme-test-a-react-component-that-returns-null-in-render-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!