Cliff Bentley
Cliff Bentley

Reputation: 11

Mocking React-Redux Store With Jest

Our React-Redux App uses create-react-app. We’re trying to back-apply Jest/Enzyme/redux-mock-store to a large code base. Our src/store.js file is the standard react-redux script that runs the reducers and constructs an initial state. This src/store.js is central to the problem.

Problem is that when we start the jest test-run, jest loads src/store.js 7 times, and then (roughly) once for every test. I must suppress this and can’t figure out how. The reason I must suppress it is that it always leaves the store in its initial state and there is one crucial AppConfig property in that store which must be populated to prevent javascript errors that stop jest. I already have a function which returns a mock store for use with the Provider. That works well. But our components call out from constructor(), componentDidMount(), etc to api functions. Those api functions don’t see the state dropped from Provider. Instead, the api functions do stuff like this:

    // AppConfig is an immutable Map 
    const { AppConfig } = store.getState();
    const stuff = AppConfig.get(‘stuff’).toJS();

That’s a JS error because AppConfig is empty and toJS() is called on undefined. (That can never be a problem in run-time because we construct no component without AppConfg being ready.) There are 2 solutions involving refactoring the App that I can do. But I’d rather figure out how to properly use jest. How can I supply the mock redux state without it getting clobbered by jest's repeated loads of src/store.js???

This is killing me. What in Jest, create-react-app, or ??? initiates these unwanted loads of src/store.js? How to override? Is there a config that causes jest to call my function instead of src/store.js?

Upvotes: 1

Views: 5378

Answers (1)

Cliff Bentley
Cliff Bentley

Reputation: 11

I figured out my own problem. Will post here in case someone else that is new with jest may benefit from my folly.

Jest does not load src/store.js. The culprit is my shallow component tests because the components have statements like this:

import StuffService from '../../api/stuff';

The calls to the api from the component look like this:

// e.g. from componentDidMount
StuffService.get.myRequest();

But in the es6 module that defines StuffService, at the top we have something like:

import store from '../../store';

// lower in the js file, we have code as shown in my previous post:
const { AppConfig } = store.getState();

That's what is causing src/store to keep running. Will study Jest's Manual Mocks for a solution.

Upvotes: 0

Related Questions