【问题标题】:spyOn fail even if the spy was called即使调用了间谍,spyOn 也会失败
【发布时间】:2017-10-20 22:40:08
【问题描述】:

在我的组件中,我有 ...

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();
});

测试失败

用 /
调用 expect(jest.fn()).toHaveBeenCalledWith(expected)

预期的模拟函数已被调用:["/"]
但它没有被调用。

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

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

    1 - 在没有事件的情况下测试您的提交功能,然后您可以在承诺链成功后返回承诺并测试重定向

    2 - 将 versionStore.add 模拟为同步并立即执行它的 then 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      相关资源
      最近更新 更多