Invariant Violation: Could not find “store” in either the context or props of “Connect(SportsDatabase)”

后端 未结 9 1770
别那么骄傲
别那么骄傲 2020-12-12 10:36

Full code here: https://gist.github.com/js08/0ec3d70dfda76d7e9fb4

Hi,

  • I have an application where it shows different templates for desktop and mobile
9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 11:12

    It's pretty simple. You're trying to test the wrapper component generated by calling connect()(MyPlainComponent). That wrapper component expects to have access to a Redux store. Normally that store is available as context.store, because at the top of your component hierarchy you'd have a . However, you're rendering your connected component by itself, with no store, so it's throwing an error.

    You've got a few options:

    • Create a store and render a around your connected component
    • Create a store and directly pass it in as , as the connected component will also accept "store" as a prop
    • Don't bother testing the connected component. Export the "plain", unconnected version, and test that instead. If you test your plain component and your mapStateToProps function, you can safely assume the connected version will work correctly.

    You probably want to read through the "Testing" page in the Redux docs: https://redux.js.org/recipes/writing-tests.

    edit:

    After actually seeing that you posted source, and re-reading the error message, the real problem is not with the SportsTopPane component. The problem is that you're trying to "fully" render SportsTopPane, which also renders all of its children, rather than doing a "shallow" render like you were in the first case. The line searchComponent = ; is rendering a component that I assume is also connected, and therefore expects a store to be available in React's "context" feature.

    At this point, you have two new options:

    • Only do "shallow" rendering of SportsTopPane, so that you're not forcing it to fully render its children
    • If you do want to do "deep" rendering of SportsTopPane, you'll need to provide a Redux store in context. I highly suggest you take a look at the Enzyme testing library, which lets you do exactly that. See http://airbnb.io/enzyme/docs/api/ReactWrapper/setContext.html for an example.

    Overall, I would note that you might be trying to do too much in this one component and might want to consider breaking it into smaller pieces with less logic per component.

提交回复
热议问题