Search code examples
reactjsjestjsstore

"Could not find store" after wrapping component with context provider in Jest


After wrapping a React Component with the appropriate provider, the store is still not found within the jest testing environment. Is there something that I am missing, or another cleaner way to go about this?

This is the practice that is functional for other stores, and I have used with other components, so I don't see a reason why this shouldn't work. The renderer should be creating an object wrapped with the TextContext that it needs to read from in order to populate fields.

Context

import { connect } from 'react-redux';
import React, { createContext } from 'react';

export const TextContext = createContext({});

export function TextProvider({ children, text }) {
  return <TextContext.Provider value={text}>{children}</TextContext.Provider>;
}

export const TextConsumer = TextContext.Consumer;
function renderComposition(props) {
  const text = {
    ... // some text objects
  };
  return (
    <TextProvider text={text}>
      <Composition {...props} />
    </TextProvider>
  );
}

target failing line

beforeEach(() => {
...
   subject = mount(renderer.create(renderComposition(props)));
...
)};

with error of

Invariant Violation: Could not find "store" in either the context or props of "Connect(Composition)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(Composition)".

Solution

  • I guess your component requires mocked store, you can provide it by creating mockReduxState.js

    import configureMockStore from "redux-mock-store";
    
    export const createMockStore = state => configureMockStore()(state);
    

    Updating the failing test by passing mockedStore.

    beforeEach(() => {
    ...
     let updatedProp = {...props, store:createMockStore};
       subject = mount(renderer.create(renderComposition(updatedProp)));
    ...
    )};