【问题标题】:Keep "this" context when mocking Promise in function on component在组件的函数中模拟 Promise 时保持“this”上下文
【发布时间】:2021-08-14 12:58:23
【问题描述】:

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

【问题讨论】:

  • 我想你的意思是this.state 不是this.setState,对吧?
  • @konekoya 我的意思是 this 关键字在承诺返回的 .then 范围内。因此,当我将 this.props.userId 传递给服务上的函数时,当我将鼠标悬停在 this 关键字上时,我能够像预期的那样看到类上的所有属性。当我在 then 的范围内时,this 关键字变得未定义。不知道如何在.then 范围内传递要使用“this”引用的类上下文

标签: javascript reactjs jestjs react-test-renderer


【解决方案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上的完整工作回购

【讨论】:

  • 您好,感谢您的回复,我尝试了第一种方法(您没有尝试过的方法),但仍然遇到“this”未定义的相同问题。我还尝试了您提供的 jest.mock 方式,当我单步执行代码时,它仍然尝试使用真正的 myHttpService 并中断,在单元测试中我必须做些什么才能将此模拟应用于类?或者可能是因为它是 myHttpService 中的默认导出,所以某些东西无法正常工作。
  • @Shawn 我已经使用 react-router-dom MemoryRouter 更新了答案。
猜你喜欢
  • 2016-06-27
  • 1970-01-01
  • 1970-01-01
  • 2018-06-02
  • 1970-01-01
  • 1970-01-01
  • 2018-01-23
  • 1970-01-01
  • 2017-06-17
相关资源
最近更新 更多