0

我遇到了一个问题,在我的方法this中测试某些逻辑时,我无法通过 Jest 引用关键字。componentDidMount因此,一旦我进入承诺响应,当我将鼠标悬停thisthis.props(或 this.setState)中时,它只会显示undefined.

这是我的 App 组件中的方法:

componentDidMount() {
  myHttpService.getUser(this.props.userId).then(response => {
    if (response.user !== null) {
      this.setState({ user: response.user });
    } else {
      this.props.history.push('/login');
    }
  });
}

这是我对该组件的单元测试:

it('push login route to history if no user is returned', () => {
  myHttpService.default.getUser = jest.fn(() =>
    Promise.resolve({ user: null }),
  );

  const result = renderer.create(
    <MemoryRouter>
      <App />
    </MemoryRouter>,
  );

  // Not sure how to check that route was pushed to history, trying to solve the this context issue first.
  // expect(?).toHaveBeenCalled();
});
4

1 回答 1

1

在测试文件中模拟服务

jest.mock('<path-to-your myHttpService>', () => {
  return function() {
    return { getUser: () => Promise.resolve({ user: null }) };
  };
});

您可以使用 Jest 对断言执行以下操作

let instance = result.getInstance();
let history = instance.history;
expect(history.location.pathname).to.equal('/login');

这是github上的完整工作存储库

于 2018-05-04T05:38:37.817 回答