React/Redux测试报错:无法在上下文或props中找到store
Hey there! Let's fix that "could not find store in either the context or props" error you're hitting in your tests. I've dealt with similar headaches when testing Redux-connected components wrapped in React Router, so here's a step-by-step solution tailored to your stack (React/Redux, redux-form/immutable, react-router):
Step 1: Create a Mock Store with Redux-Form's Immutable Reducer
First, your test environment doesn't have access to your app's real store, so you need to build a mock one that includes the redux-form reducer (critical since you're using redux-form/immutable). Add this to your Login_spec.js:
import { createStore, combineReducers } from 'redux'; import { reducer as formReducer } from 'redux-form/immutable'; // Combine redux-form's reducer with any of your app's custom reducers const rootReducer = combineReducers({ form: formReducer, // Add your other reducers here if your container depends on them }); // Create the mock store const mockStore = createStore(rootReducer);
Step 2: Wrap Your Component in Provider + MemoryRouter
The error happens because your connected component (like LoginContainer) and redux-form components expect a Redux store and React Router context to exist. In tests, you have to explicitly provide these using Provider (from react-redux) and MemoryRouter (from react-router-dom, which is perfect for testing since it doesn't rely on browser history).
Update your test case to look like this:
import React from 'react'; import { mount } from 'enzyme'; // Use mount instead of shallow for context-dependent components import { Provider } from 'react-redux'; import { MemoryRouter } from 'react-router-dom'; import LoginContainer from './LoginContainer'; describe('LoginContainer', () => { it('renders without throwing store errors', () => { mount( <Provider store={mockStore}> <MemoryRouter> <LoginContainer /> </MemoryRouter> </Provider> ); }); });
Why Your Previous Fix Didn't Work
The GitHub issue solution you tried is for setting up your app's root Router in production code, not for test environments. In tests, you can't rely on your app's root component structure to pass down context—you have to wrap the component directly in the providers it needs.
Extra Checks to Avoid Headaches
- Use
mountinstead ofshallow: Shallow rendering won't pass down context to nested connected components or redux-form HOCs. Mount renders the full component tree, which is necessary here. - Double-check Immutable imports: Make sure you're using the immutable-specific redux-form reducer (
redux-form/immutable) and not the standard one—mismatched imports can cause silent context issues. - Add custom reducers if needed: If your
LoginContainerrelies on other slices of your Redux state, include those reducers in the mock store's root reducer.
内容的提问来源于stack exchange,提问作者neridaj

