玩笑/酵素 |在 componentDidMount 中测试函数调用 [英] Jest/Enzyme | Test a function call in componentDidMount

查看:25
本文介绍了玩笑/酵素 |在 componentDidMount 中测试函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What to do when you want to test that a function is been called, on componentDidMount() React lifecycle Method. Basically the component code looks like this:

  state = {
    randomStateToPopulate: []
  };

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

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

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

So, how to you actually test this case?

推荐答案

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

This is the case scenario you want to test. If the componentDidMount is being called, check that it has been called only once, or as many times you want.

你的测试.我在下面的评论中有解释

    // 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做更复杂的事情,但是它的基本要旨就是上面一个.如果您有更详细或更好的解决方案,请发布.谢谢!!

You can abstract, this case to do more complex things, but the basic gist of it is the above one. If you have a more detailed or better solution, please post it. Thanks!!

这篇关于玩笑/酵素 |在 componentDidMount 中测试函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆