Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not find “store” in either the context or props of “Connect(App)” in Jest/React

Tags:

reactjs

jestjs

I'm trying to run my first jest test but it seems like there's an issue with the way my react files are set up:

app_test:

it('renders without crashing', () => {
  const app = shallow(<App />);
});

app.js

class App extends Component {
  componentWillMount() {
    this.fetchUserAccountInfo();
  }

  render() {
    return <MainRoutes auth={this.props.loggedIn} />;
  }
}

function mapStateToProps(state) {
  return {
    loggedIn: state.loggedIn.userLoggedIn,
  };
}

export default connect(
  mapStateToProps,
  { fetchUserAccountInfo }
)(App);

index.js (embeds App.s)

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(reducers);
const token = localStorage.getItem("token");
const bugsnagClient = bugsnag({...//bugsnag stuff})

bugsnagClient.use(bugsnagReact, React);
const ErrorBoundary = bugsnagClient.getPlugin("react");

const RootApp = () => (
  <ErrorBoundary>
    <Provider store={store}>
      <App id={token} />
    </Provider>
  </ErrorBoundary>,
);

ReactDOM.render(<RootApp />, document.getElementById('.app'));

They say i have an issue with shallow rendering "App"

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

enter image description here

I'm not sure what else I need to pass through App or if I need to move the Provider down?

like image 677
lost9123193 Avatar asked Sep 12 '19 23:09

lost9123193


1 Answers

The error log clearly states here that you need to provide a store to your component. To do so, you need to mock your store beforehand, and then give it to the <Provider /> component, containing the <App /> as child. Your file should look like this :

/* app_test */

import React from 'react';
import { shallow } from 'enzyme';
import { Provider } from 'react-redux';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import App from './App';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

it('renders without crashing', () => {
  const store = mockStore({}); // Instead of {}, you can give your initial store
  shallow(
    <Provider store={store}>   // Provides the store to your App
      <App />
    </Provider>
  );
});

This piece of code should do the trick !

For more info, you can check this page: https://redux.js.org/recipes/writing-tests

like image 180
Orlyyn Avatar answered Oct 14 '22 09:10

Orlyyn