Javascript 保留;这";在组件上的函数中模拟承诺时的上下文

Javascript 保留;这";在组件上的函数中模拟承诺时的上下文,javascript,reactjs,jestjs,react-test-renderer,Javascript,Reactjs,Jestjs,React Test Renderer,在测试我的componentDidMount方法中的某些逻辑时,我遇到了一个无法通过Jest引用this关键字的问题。因此,一旦我进入承诺响应中,当我在this.props(或this.setState)中将鼠标悬停在this上时,它只会显示未定义的 这是我的应用程序组件中的方法: componentDidMount() { myHttpService.getUser(this.props.userId).then(response => { if (response.user

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

这是我的应用程序组件中的方法:

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();
});
这是我对该组件的单元测试:

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();
});
it('push login route to history if not user return',()=>{
myHttpService.default.getUser=jest.fn(()=>
Promise.resolve({user:null}),
);
const result=renderer.create(
,
);
//不确定如何检查该路径被推到历史,试图首先解决此上下文问题。
//期望(?)已被调用();
});

在测试文件中模拟服务

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

这是一份关于

的完整的工作回购协议,我想你在问题中的意思是
this.state
而不是
this.setState
,对吗?@konekoya我指的是承诺返回的.then范围中的this关键字。因此,当我将this.props.userId传递给服务上的函数时,当我将鼠标悬停在this关键字上时,我能够像预期的那样看到类上的所有属性。当我在then的范围内时,this关键字将变得未定义。不确定如何传递要在其中使用“this”引用的类上下文。然后scopeHey感谢您的响应,我尝试了第一种方法(您没有尝试过的方法),但仍然存在“this”未定义的问题。我还尝试了您提供的jest.mock方法,当我逐步完成代码时,它仍然试图使用真正的myHttpService并中断,我是否必须在单元测试中执行一些操作才能将此模拟应用于类?或者可能是因为它是myHttpService中的默认导出,所以某些内容无法正常工作。@Shawn我已使用react路由器dom MemoryRouter使用repo更新了答案。