【发布时间】:2019-11-13 11:37:32
【问题描述】:
我正在为一个组件编写集成测试,该组件应根据异步(thunk)redux 操作的响应重定向到特定路径。
这是我的组件的简化版本:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
redirect: false
}
this.props.dispatch(asyncThunkAction())
.then( () => this.setState({redirec: true}) )
.catch( (err) => console.log('action failed') )
}
...
render() {
if (this.state.redirect) {
return <Redirect to='/whocares' />
}
...
}
}
function mapStateToProps(state) {
return {
...
};
}
export default connect(mapStateToProps)(MyComponent);
我想编写一个测试,断言组件重定向到预期的路径。
我正在使用this technique 来检查实际的重定向路径(它并不完美,但它不是这个问题的重点)。
我卡住的地方是redux/thunk动作之后.then()中的状态变化。因为它是一个承诺,所以重定向发生在我的 expect 语句之后,所以我无法测试它。
这是我的测试的样子:
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
test('redirects after thunk action', () => {
const redirectUrl = '/whocares'
const data = {};
jest.mock('../actions');
act(() => {
ReactDOM.render(
<TestRouter
ComponentWithRedirection={<MyComponent store={mockStore(data)} />}
RedirectUrl={redirectUrl}
/>,
container);
});
expect(container.innerHTML).toEqual(
expect.stringContaining(redirectUrl)
)
})
我的 TestRouter 只是将预期的重定向 URL 打印到 DOM 中。 (查看上面的链接以获取有关此 hack 的完整说明。)因此,我的测试(正确地)识别出在 thunk 操作正在进行时出现的加载屏幕,而不是到达预期的路线。
我认为这样做的正确方法是模拟来自asyncThunkAction 的响应,以便它返回具有匹配数据的已解决承诺,但到目前为止我还没有弄清楚如何要做到这一点。我按照manual mocks 上的 Jest 文档创建了相应的模拟文件:
// __mocks__/actions.js
const asyncThunkAction = function(){
return Promise.resolve({foo: 'bar'});
};
export { asyncThunkAction };
...但我的测试仍然“看到”加载状态。我什至不认为它正在查看我的模拟文件/操作。
这样做的正确方法是什么?
【问题讨论】:
标签: javascript reactjs unit-testing redux jestjs