【问题标题】:Jest Enzyme test a React component that returns null in render methodJest Enzyme 测试在 render 方法中返回 null 的 React 组件
【发布时间】:2018-04-25 19:46:59
【问题描述】:

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

render() {
  if (this.props.isHidden) {
      return null;
  }

  return <div>test</div>;
}

我想用 jest 和酵素检查当 isHidden 为真时组件是否为空:

describe('myComp', () => {
    it('should not render if isHidden is true', () => {
        const comp = shallow(<myComp isHidden={true} />);
        expect(comp.children().length).toBe(0);
    });
});

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

【问题讨论】:

    标签: javascript reactjs jestjs enzyme


    【解决方案1】:
       expect(comp.type()).toEqual(null)
    

    就是这样!

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

    【讨论】:

    • 也许它是 mountshallow 的人工制品,但这对我不起作用,我不得不按照 @shoaib-nawaz 的描述查看 comp.html()
    • expect(comp.get(0)).toBeFalsy() 为我工作expect(comp.type()).toEqual(null)did 不是
    【解决方案2】:

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

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

    【讨论】:

    • 虽然这段代码 sn-p 可以解决问题,但它没有解释为什么或如何回答这个问题。请include an explanation for your code,因为这确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    • 使用 Chai,expect(comp.html()).to.eq('') 为我工作
    • 这对我不起作用,comp.html() 在我的情况下返回了一个空字符串。
    【解决方案3】:

    ShallowWrapper 有一个isEmptyRender() 函数:

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

    【讨论】:

    • 我眼中的最佳答案。
    • @klugjo - 这是一个比接受的答案更好的答案。你能改变接受的答案吗?
    • 这个答案最好地传达了测试的实质,同时也准确地测试了结果。
    【解决方案4】:

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

    expect(comp).toBeEmptyRender()
    

    【讨论】:

    【解决方案5】:

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

    问题原来是myComponent 来自对另一个浅渲染组件上的.find() 的调用。在这种情况下,需要在找到的子组件上额外调用 .shallow() 以使 isEmptyRender() 正常工作:

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

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

    【讨论】:

    • 对我来说,在不存在的子节点上调用 shallow() 会导致“方法“shallow”意味着在 1 个节点上运行。而是找到了 0 个。” expect(childComponent.isEmptyRender()).toBe(true) 工作得很好。酶@^3.11.0 & jest-酶@^7.1.2
    猜你喜欢
    • 2018-09-15
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    • 2018-08-20
    • 2020-07-17
    • 2019-08-12
    • 2020-02-24
    • 1970-01-01
    相关资源
    最近更新 更多