Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs Jest/Ezyme |在componentDidMount中测试函数调用_Reactjs_Unit Testing_Jestjs_Es6 Promise_Enzyme - Fatal编程技术网

Reactjs Jest/Ezyme |在componentDidMount中测试函数调用

Reactjs Jest/Ezyme |在componentDidMount中测试函数调用,reactjs,unit-testing,jestjs,es6-promise,enzyme,Reactjs,Unit Testing,Jestjs,Es6 Promise,Enzyme,在componentDidMount()React lifecycle Method上,当您想要测试函数是否已被调用时,应该做什么。基本上,组件代码如下所示: state = { randomStateToPopulate: [] }; // Test componentDidMount componentDidMount() { this.randomFunction(); } randomFunction= () => { listR

componentDidMount()
React lifecycle Method上,当您想要测试函数是否已被调用时,应该做什么。基本上,组件代码如下所示:

  state = {
    randomStateToPopulate: []
  };

  // Test componentDidMount
  componentDidMount() {
    this.randomFunction();
  }

  randomFunction= () => {
    listRandomData().then(({ data }) => {
      this.setState({ randomStateToPopulate: data });
    });
  };

那么,如何实际测试这个案例呢?

这就是您要测试的案例场景。如果正在调用componentDidMount,请检查它是否只被调用过一次,或者您希望调用多少次

你的测试<代码>我在下面的评论中有解释

    // Inside your general `Describe`
  let wrapper;
  const props = {
    // Your props goes here..
  };
  beforeEach(() => {
    wrapper = shallow(<YourComponent {...props} />);
  });

    it('should check `componentDidMount()`', () => {
      const instance = wrapper.instance(); // you assign your instance of the wrapper
      jest.spyOn(instance, 'randomFunction'); // You spy on the randomFunction
      instance.componentDidMount();
      expect(instance.randomFunction).toHaveBeenCalledTimes(1); // You check if the condition you want to match is correct.
    });
//在您的“概述”中`
让包装纸;
常量道具={
//你的道具放在这里。。
};
在每个之前(()=>{
包装器=浅();
});
它('应该选中'componentDidMount()',()=>{
const instance=wrapper.instance();//分配包装器的实例
spyOn(实例'randomFunction');//监视randomFunction
componentDidMount();
expect(instance.randomFunction).toHaveBeenCalledTimes(1);//检查要匹配的条件是否正确。
});

你可以抽象,这种情况下做更复杂的事情,但它的基本要点是上述一个。如果您有更详细或更好的解决方案,请发布。谢谢

这是正确的。您必须在测试用例中自己调用componentDidMount()。在我的例子中,
实例
null
,无论我使用的是
装载
还是
浅层
:(@GregWoz)我得到的结果与您相同。对我来说,我的组件返回的父html标记似乎是一个ReactFragment。类似于:“return()”这把一切都搞糟了。我通过在实例(instance.Find('MyComponent'))上使用Find修复了这个问题,测试这个组件的唯一方法似乎是“white box”,这意味着您将根据
randomFunction
的状态编写断言(例如,它是否被调用)或
randomstatetopulate
(是否将其分配给
数据
)。但白盒测试的缺点是,如果更改内部实现,测试可能会中断。如果显示如何使用
randomstatetopulate
(例如,将其放入HTML列表中),您可以编写一个不绑定到实现细节的测试。