玩笑/酵素 | 在 componentDidMount 中测试函数调用

IT技术 reactjs unit-testing jestjs es6-promise enzyme
2021-05-11 19:14:18

当你想在componentDidMount()React 生命周期方法上测试一个函数被调用时该怎么做基本上组件代码如下所示:

  state = {
    randomStateToPopulate: []
  };

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

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

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

1个回答

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

你的测试。 I have the explanation in comments below

    // 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.
    });

你可以抽象,这个case来做更复杂的事情,但是它的基本要旨就是上面一个。如果您有更详细或更好的解决方案,请发布。谢谢!!