我正在尝试在我的 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
中)钩子(Hook)被称为 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
(返回渲染的组件)我在每个测试中调用而不是使用 beforeEach
.它减少了不必要的可变变量,例如 component
在测试之间使用。
关于reactjs - "Cannot read property ' getState ' of undefined"创建 redux 模拟存储时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68547489/