首页 > 解决方案 > 如何在 React/Redux/Jest 测试中的异步调用后测试方法调用

问题描述

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

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

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

标签: reactjsreact-reduxjestjs

解决方案


如果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!');
});

推荐阅读