我正在尝试测试一个连接的react组件,它需要一个props.params.id来调用动作创建者。当我尝试测试组件是否连接到存储区时,我得到“未捕获TypeError:无法读取未定义的属性'id‘”
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={PostsIndex}/>
<Route path="posts/:id" component={ShowPost}/>
</Route>
</Router>
</Provider>
, document.querySelector('.container'));
describe('ConnectedShowPost', ()=> {
let initialState = {
posts: { postsList: postsListData, post: postData, error: '' },
comments: {showComments: false},
auth: {authenticated: true}
};
store = mockStore(initialState);
connectedShowPost = TestUtils.renderIntoDocument(<Provider store={store}><ConnectedShowPost/></Provider>);
showPost = TestUtils.scryRenderedComponentsWithType(connectedShowPost, ShowPost)[0];
expect(showPost.props.posts.post).toEqual(postData);
})
我曾尝试在存储中包含params,但这不起作用,因为params在组件内部使用时不会与存储挂钩。
我也尝试过将其作为ownProps参数传递,但也不起作用。
将其作为道具传递给ConnectedShowPost组件会导致存储中的所有其他状态项都是未定义的。
我也尝试直接设置showPost.props.params = {id:'123},但也不起作用..
有没有关于如何让这个测试工作的想法?
发布于 2019-12-12 20:39:03
如果您连接的组件收到类似以下的参数:
function mapStateToProps(state, ownProps)
{
const { match: { params } } = ownProps;
console.log(params.id);
return {
......
};
}
然后,在您的测试中,可以将该参数作为传统道具进行注入。查看下一个示例:
wrapper = mount(
<MemoryRouter>
<ConnectedContainer
store={store}
match={
{
params: {
id: 1
}
}
}
/>
</MemoryRouter>
);
https://stackoverflow.com/questions/39371629
复制相似问题