【发布时间】: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