You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新手使用Jest测试Redux Store遇TypeError问题求解决

嘿,作为经常和Jest+Redux测试打交道的人,我来帮你搞定这两个报错~

你遇到的 TypeError: Cannot read property 'redux-store' of undefined 和 Cannot read property 'getState' of undefined,本质上都是Redux Store实例没有被正确初始化或引用导致的,我结合你给出的代码片段,分场景给你解决方案:

1. 先检查你的storeFactory是否正确返回Store实例

首先要确保你的工厂函数确实能产出合法的Redux Store,很多新手会在这里踩坑:要么函数没return,要么createStore的参数配置错了。

结合你的导入代码,正确的storeFactory应该是这样的:

import { createStore, combineReducers, applyMiddleware } from 'redux';
import { colors, sort } from './reducers';
import stateData from '../../data/initialState';
// 如果用了中间件(比如redux-thunk),记得先导入
// import thunk from 'redux-thunk';

export const storeFactory = (initialState = stateData) => {
  // 合并reducers
  const rootReducer = combineReducers({
    colors,
    sort
  });
  
  // 生成并返回Store实例,中间件按需添加
  return createStore(
    rootReducer,
    initialState,
    applyMiddleware(/* 比如thunk、logger等中间件,没有就留空 */)
  );
};

重点确认:函数一定要return createStore的结果,中间件如果有要正确传入applyMiddleware。

2. 修复测试中Store的初始化方式

getState报错大概率是你在测试里没调用storeFactory函数,而是直接引用了函数本身,导致后续调用getState()时,操作的是函数而非Store实例。

❌ 错误示例:

// 错把函数当实例用了!
const store = storeFactory;
store.getState(); // 这里必然报错

✅ 正确做法:

import { storeFactory } from './你的storeFactory路径';

test('测试Store初始化状态', () => {
  // 调用工厂函数,拿到真正的Store实例
  const store = storeFactory();
  // 也可以传入自定义初始状态:storeFactory({ colors: [] })
  
  const currentState = store.getState();
  // 写你的断言逻辑,比如检查colors的长度
  expect(currentState.colors.length).toBe(5);
});

3. 解决'redux-store' of undefined的问题

这个错误一般出现在测试连接Redux的React组件时:你没有用react-redux的Provider组件包裹被测组件,导致组件无法从Context中获取Redux Store,进而试图访问undefined上的'redux-store'。

✅ 正确的组件测试写法:

import { render } from '@testing-library/react';
import { Provider } from 'react-redux';
import { storeFactory } from './你的storeFactory路径';
import YourConnectedComponent from './你的组件路径';

test('测试连接Redux的组件', () => {
  const store = storeFactory();
  
  render(
    // 必须用Provider把组件包起来,传入正确的Store实例
    <Provider store={store}>
      <YourConnectedComponent />
    </Provider>
  );
  
  // 后续的断言逻辑
});

如果是直接测试Store出现这个错误,那你得检查测试代码里是不是不小心写了someUndefinedObj['redux-store']这类代码,排查所有变量的引用是否正确初始化。

4. 验证中间件配置是否正确

如果你给Store加了中间件(比如redux-thunk),一定要确保中间件已经正确安装(npm install redux-thunk),并且在applyMiddleware里正确传入,错误的中间件配置会导致createStore失败,返回异常对象甚至undefined,进而引发后续报错。

比如用redux-thunk的正确配置:

import thunk from 'redux-thunk';

export const storeFactory = (initialState = stateData) => {
  const rootReducer = combineReducers({ colors, sort });
  return createStore(
    rootReducer,
    initialState,
    applyMiddleware(thunk) // 正确传入中间件
  );
};

按照上面的步骤排查,应该就能解决这两个报错啦~

内容的提问来源于stack exchange,提问作者pifuegtq23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:35:49