如何在React / Redux / Jest测试中异步调用后测试方法调用

时间:2019-10-23 10:01:47

标签: reactjs react-redux jestjs

我的组件有一个按钮,该按钮调用方法“ 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!');
});

第一个断言有效,但是第二个调度从未断言,因为它出现在异步调用之后(如果我将其移到上方,则可以工作)。

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

1 个答案:

答案 0 :(得分:0)

如果this.props.dispatchNotification返回了一个承诺(或者您可以使它返回一个承诺),那么您可以在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!');
});