Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a component with a nested container with React and Redux?

Due to the complexity of the application I am working on I have decided on using a nested redux container rather than passing an action as a prop down to the child components. However, this has proved to be problematic for unit testing when rendering the OuterContainer with jsdom in combination with mocha, chai and sinon.

Here is a contrived example of the view structure:

<OuterContainer>
  <div>
    <InnerContainer />
  </div>
</OuterContainer>

where OuterContainer & InnerContainer are wrapped with connect. e.g.:

export connect(<mapStateToProps>)(<Component>)

When running tests the error I am getting is: Invariant Violation: Could not find "store" in either the context or props of "Connect(Component)". Either wrap the root component in a `<Provider>`, or explicitly pass "store" as a prop to "Connect(Component)".

Is there a way to unwrap or stub the InnerContainer for unit testing without having to use shallow rendering?

like image 617
Jon Yardley Avatar asked Mar 23 '16 10:03

Jon Yardley


1 Answers

Wrap your component in <Provider> when testing. It’s up to you whether to supply a real store or a mock with { dispatch, getState, subscribe } to it. Wrapping the outermost component in <Provider store={store}> will also make the store available to the child components at any level of nesting—just like in the app itself.

const store = createStore(reducer) // can also be a mock
ReactTestUtils.renderIntoDocument(
  <Provider store={store}>
    <OuterContainer />
  </Provider>
)
like image 77
Dan Abramov Avatar answered Oct 13 '22 07:10

Dan Abramov