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