javascript Jest Enzyme 测试在 render 方法中返回 null 的 React 组件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47259061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:16:37  来源:igfitidea点击:

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

javascriptreactjsjestjsenzyme

提问by klugjo

I have a component that returns null in render under certain conditions:

我有一个在某些条件下在渲染中返回 null 的组件:

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:

当 isHidden 为真时,我想检查组件是否为空,并使用 jest 和酶:

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.

这有效,但有没有更惯用的方式来编写这个测试?测试呈现为 null 的组件是很常见的场景。

采纳答案by Abdennour TOUMI

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

That's it!

而已!

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

或者: expect(comp.get(0)).toBeFalsy()

回答by Benjamin Intal

ShallowWrapperhas a isEmptyRender()function:

ShallowWrapper有一个isEmptyRender()功能:

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

回答by Shoaib Nawaz

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

根据ShallowWrapper::html实现,如果组件实例类型为 null,则返回 null,作为 的结果render

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

回答by ducci

we use the following with jest-enzyme

我们将以下内容与 jest-enzyme 一起使用

expect(comp).toBeEmptyRender()

回答by Jon Schneider

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

正如Benjamin Intal 的解决方案中提到,我尝试使用myComponent.isEmptyRender(),但它意外返回false,即使myComponent.children().length返回 0。

The problem turned out to be that myComponentwas 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:

结果证明问题myComponent来自.find()对另一个浅渲染组件的调用。在这种情况下,需要额外调用.shallow()找到的子组件isEmptyRender()才能正常工作:

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

参考:https: //github.com/enzymejs/enzyme/issues/1278