"Cannot read property 'getState' of undefined" 创建 redux 模拟商店时

"Cannot read property 'getState' of undefined" when creating redux mock store

我正在尝试在我的 React-Redux 应用程序中测试输入组件,并尝试使用 'redux-mock-store'.

创建我的 redux 商店的模拟

当我尝试 运行 测试时,我得到“无法读取未定义的 属性 'getState'”错误,所以我想我没有正确初始化我的模拟商店,但我不知道我做错了什么。

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import InputField from './InputField';
import configureStore from 'redux-mock-store';

describe("<InputField />", () => {
    const mockStore = configureStore([]);

//these are my two reducers as defined in my real redux store, so I'm passing them to the mock as well
    const chosenCityReducer = (chosenCity = null, action) => {
        if(action.type === 'CITY_CHOSEN') {
            return action.payload;
        }
        return chosenCity
    }
    const chosenCityWeatherReducer = (weather=null, action) => {
        if(action.type === 'WEATHER_FETCHED') {
            return action.payload;
        }
        return weather
    }
    let store;
    let component;

    beforeEach(() => {
        store = mockStore({
           chosenCity: chosenCityReducer,
           weatherForecast: chosenCityWeatherReducer
        });
    });

    let div = document.createElement('div')
    component = ReactDOM.render(
        <Provider store={store}>
            <InputField />
        </Provider>
    ,div);

    it('should render with given state from Redux store', () => {
        expect(component.toJSON()).toMatchSnapshot();
    });

模拟定义有问题吗? 谢谢!

你正在创建你的组件(<InputField/> 包装在 <Provider /> 中)在 beforeEach 钩子被调用之前所以 mockStore 还没有被调用所以 store 将是 undefined.

试试这个:

let component;

beforeEach(() => {
  let div = document.createElement('div');
  const store = mockStore({
    chosenCity: chosenCityReducer,
    weatherForecast: chosenCityWeatherReducer
  });
  component = ReactDOM.render(
    <Provider store={store}>
      <InputField />
    </Provider>
  , div);
});

it('should render with given state from Redux store', () => {
  expect(component.toJSON()).toMatchSnapshot();
});

如果愿意,您可以随时将商店创建移出 beforeEach

我通常有一个名为 renderSubject 的函数(returns 呈现的组件),我在每个测试中调用它而不是使用 beforeEach。它减少了不必要的可变变量,例如在测试之间使用的 component