简体   繁体   English

测试需要参数的连接反应组件

[英]Testing connected react component that needs params

I'm trying to test a connected react component that needs a props.params.id to call action creators.我正在尝试测试一个需要 props.params.id 来调用动作创建者的连接反应组件。 When I try to test that the component is connected to the store I get "Uncaught TypeError: Cannot read property 'id' of undefined"当我尝试测试组件是否连接到商店时,我收到“未捕获的类型错误:无法读取未定义的属性 '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);
  })

I've tried including params in the store but that doesn't work since params is not hooked up to the store when used inside the component.我试过在商店中包含 params 但这不起作用,因为在组件内部使用时 params 没有连接到商店。

I've also tried passing it in as an ownProps argument and that didn't work either.我也试过将它作为 ownProps 参数传入,但也没有用。

Passing it in to the ConnectedShowPost component as a props causes all other state items in the store to be undefined..将它作为道具传递给 ConnectedShowPost 组件会导致商店中的所有其他状态项都未定义。

Also tried to directly set showPost.props.params = {id: '123} which didnt work either..还尝试直接设置 showPost.props.params = {id: '123} 这也不起作用..

Any ideas on how to get this test to work?关于如何让这个测试工作的任何想法?

If your connected component receives a param like this:如果您的连接组件收到这样的参数:

function mapStateToProps(state, ownProps)
{
    const { match: { params } } = ownProps;
    console.log(params.id);

    return {
         ......
    };
}

Then, In your test it's possible to inject that param as traditional props.然后,在您的测试中,可以将该参数作为传统道具注入。 Check out the next example:查看下一个示例:

    wrapper = mount(
        <MemoryRouter>
            <ConnectedContainer
                store={store}
                match={
                    {
                        params: {
                            id: 1
                        }
                    }
                }
            />
        </MemoryRouter>
    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM