reactjs - "Cannot read property ' getState ' of undefined"创建 redux 模拟存储时

标签 reactjs unit-testing redux react-testing-library 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 中)钩子(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/

相关文章:

javascript - window.history 删除除当前 url 之外的历史记录堆栈

javascript - 函数内的变量集未在其他函数中定义

reactjs - 如何使用 formdata 将图像文件发送到 React/Next js api?

由于参数不明确异常,Android 仪器测试未运行

javascript - 在 Redux 应用程序中用服务器 ID 替换生成的 ID 的最佳方法是什么?

javascript - 在 Angular 中使用 ngrx 时捕获超时错误

node.js - 将文件下载从 protected 路径传递到浏览器

asp.net-mvc - 针对返回 FileStreamResult 的 Controller 的 ASP.NET MVC Moq 单元测试

unit-testing - 如何使用环模拟请求以 JSON 形式模拟测试 POST 请求?

reactjs - 在 React 组件中本地操作 redux 状态的最佳实践