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

Reactjs 如何在React/Redux/Jest测试中异步调用后测试方法调用,reactjs,react-redux,jestjs,Reactjs,React Redux,Jestjs,我的组件有一个按钮,它调用方法“handleSave”。我简化了代码,使之更加相关 该组件方法如下所示: handleSave = async () => { const response = await this.props.dispatchSave(); this.props.dispatchNotification(); } 我的测试: let dispatchSave = jest.fn().mockResolvedValue({}); let dispatchNotif

我的组件有一个按钮,它调用方法“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!');
});
let dispatchSave=jest.fn().mockResolvedValue({});
让dispatchNotification=jest.fn().mockReturnValue('Saved!');
它('应该分派操作',()=>{
const component=mount();
const instance=component.find(Comp).instance()作为Comp;
handleSave()实例;
expect(dispatchSave).toHaveBeenCalled();
预期(dispatchNotification).toHaveBeenCalledWith('Saved!');
});
第一个断言可以工作,但是第二个分派永远不会被断言,因为它出现在异步调用之后(如果我将它移到上面,它就会工作)


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

如果
this.props.dispatchNotification
返回承诺(或者您可以让它返回承诺),则可以在
handleSave
调用中返回此结果

handleSave=async()=>{
const response=wait this.props.dispatchSave();
返回此.props.dispatchNotification();
}
在测试中,您需要为函数调用在
it
前面加上
async
关键字和
wait

it('should dispatch actions',async()=>{
const component=mount();
const instance=component.find(Comp).instance()作为Comp;
wait instance.handleSave();
expect(dispatchSave).toHaveBeenCalled();
预期(dispatchNotification).toHaveBeenCalledWith('Saved!');
});