即使间谍被调用,spyOn 也会失败

spyOn fail even if the spy was called

在我的组件中我有...

onSubmit = (e) => {
  e.preventDefault();
  const { history, versionStore } = this.props;
  versionStore.add(this.state.formData)
    .then(() => history.push('/'));
}

在我的测试中...

it('after successfully submit should redirect to / page', () => {
  const spy = jest.spyOn(minProps.history, 'push')
    .mockImplementation((path) => {
      console.log('called with ', path); // IS CALLED!
    });

  const wrapper = shallow(<Add.wrappedComponent {...minProps} />);

  fetchMock.postOnce('/api/version', { name: 'v1' });
  wrapper.setState({ formData: { name: 'v1' } });

  wrapper.find('form').simulate('submit', { preventDefault: jest.fn() });

  expect(spy).toHaveBeenCalledWith('/');

  spy.mockReset();
  spy.mockRestore();
});

测试失败

called with /
expect(jest.fn()).toHaveBeenCalledWith(expected)

Expected mock function to have been called with: ["/"]
But it was not called.

您的重定向在异步代码中并且您正在以同步方式对其进行测试,这意味着当测试执行时承诺尚未解决。我会用两种方式之一解决这个问题

1 - 测试你的提交功能 w/o 事件,然后你可以 return 承诺并在承诺链成功后测试重定向

2 - 模拟 versionStore.add 同步并立即执行它的功能。