【问题标题】:How to test method calls after async call in React/Redux/Jest tests如何在 React/Redux/Jest 测试中的异步调用后测试方法调用
【发布时间】:2019-10-23 10:01:47
【问题描述】:

我的组件有一个调用方法“handleSave”的按钮。我简化了代码以使其更具相关性。

那个组件方法看起来像:

handleSave = async () => {
  const response = await this.props.dispatchSave();
  this.props.dispatchNotification();
}

我的测试:

let dispatchSave = jest.fn().mockResolvedValue({});
let dispatchNotification = jest.fn().mockReturnValue('Saved!');

it('should dispatch actions', () => {  
  const component = mount(<Comp dispatchSave={dispatchSave} dispatchNotification={dispatchNotification}>);
  const instance = component.find(Comp).instance() as Comp;
  instance.handleSave();

  expect(dispatchSave).toHaveBeenCalled();
  expect(dispatchNotification).toHaveBeenCalledWith('Saved!');
});

第一个断言有效,但第二个调度永远不会被断言,因为它出现在异步调用之后(如果我将它移到上面,它可以工作)。

如何在异步调用后断言方法调用?

【问题讨论】:

    标签: reactjs react-redux jestjs


    【解决方案1】:

    如果this.props.dispatchNotification 返回一个promise(或者你可以让它返回一个promise),那么你可以在handleSave 调用中返回这个结果。

    handleSave = async () => {
      const response = await this.props.dispatchSave();
      return this.props.dispatchNotification();
    }
    

    在测试中,您需要在 it 前面加上 async 关键字和 await 以进行函数调用。

    it('should dispatch actions', async () => {  
      const component = mount(<Comp dispatchSave={dispatchSave} dispatchNotification={dispatchNotification}>);
      const instance = component.find(Comp).instance() as Comp;
      await instance.handleSave();
    
      expect(dispatchSave).toHaveBeenCalled();
      expect(dispatchNotification).toHaveBeenCalledWith('Saved!');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-14
      • 2019-01-18
      • 1970-01-01
      • 2019-04-21
      • 2019-12-12
      • 2017-05-08
      • 2019-03-22
      相关资源
      最近更新 更多