I have a component SampleComponent
that mounts another "connected component" (i.e. container
). When I try to test SampleComponent
by mount
ing (since I need the componentDidMount
), I get the error:
Invariant Violation: Could not find "store" in either the context or props of "Connect(ContainerComponent)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(ContainerComponent)".
What's the best way of testing this?
What I essentially did was bring in my
redux
store (andProvider
) and wrapped it in a utility component as follows:then, I
mount
theSampleComponent
and run tests against it:Enzyme's mount takes optional parameters. The two that are necessary for what you need are
options.context: (Object [optional]): Context to be passed into the component
options.childContextTypes: (Object [optional]): Merged contextTypes for all children of the wrapper
You would mountSampleComponent
with an options object like so:Now your SampleComponent will pass the context you provided down to the
connected component
.Option 1)
You can wrap the container component with React-Redux's Provider component within your test. So with this approach, you actually reference the store, pass it to the Provider, and compose your component under test inside. The advantage of this approach is you can actually create a custom store for the test. This approach is useful if you want to test the Redux-related portions of your component.
Option 2)
Maybe you don't care about testing the Redux-related pieces. If you're merely interested in testing the component's rendering and local state-related behaviors, you can simply add a named export for the unconnected plain version of your component. And just to clarify when you add the "export" keyword to your class basically you are saying that now the class could be imported in 2 ways either with curly braces {} or not. example:
later on your test file:
I hope helps anyone out there.
in an attempt to make the use of decorator syntax more testable I made this: https://www.npmjs.com/package/babel-plugin-undecorate
input:
output:
Hopefully this can provide a solid Option 3!
There is also the option to use redux-mock-store.
The mock store provides the necessary methods on the store object which are required for Redux. You can specify optional middlewares and your app specific initial state.
You can use name export to solve this problem:
You should have:
You can add a export before class:
and import this component with no redux store:
With this solution you don't need to import store to your test files.