配置Redux Toolkit+Reactotron时Jest报错:createEnhancer不是函数
解决Redux Toolkit + Reactotron在Jest测试中的"TypeError: _reactotronConfig.default.createEnhancer is not a function"错误
我在配置Redux Toolkit与Reactotron时,Jest测试一直报TypeError: _reactotronConfig.default.createEnhancer is not a function错误。Reactotron在正常运行时能正常工作,能在桌面应用中查看动作等,但测试环境下的这个错误始终无法解决。以下是我的相关配置代码,求可行解决方案:
reactotronConfig配置
import Reactotron, { trackGlobalErrors, asyncStorage } from 'reactotron-react-native'; import { reactotronRedux } from 'reactotron-redux'; import { name as appName } from './app.json'; Reactotron.configure({ name: appName, }) .use(asyncStorage()) .use(trackGlobalErrors()) .useReactNative({ storybook: true, }) .use(reactotronRedux()) .connect(); // .clear(); console.tron = Reactotron; export default Reactotron;
Reactotron模拟文件(reactotron-react-native.js)
export const Reactotron = { configure: () => Reactotron, useReactNative: () => Reactotron, asyncStorage: () => Reactotron, trackGlobalErrors: () => Reactotron, createEnhancer: () => Reactotron, use: () => Reactotron, connect: () => Reactotron, clear: () => Reactotron, }; module.exports = Reactotron;
store配置
import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit'; import rootReducer from './reducers'; import Reactotron from '../../reactotronConfig'; export const store = configureStore({ reducer: rootReducer, middleware: [], enhancers: [(Reactotron as any).createEnhancer!()], });
报错截图

解决方案
问题出在测试环境的Reactotron模拟文件里,createEnhancer方法的返回值不符合Redux Toolkit enhancer的要求,同时生产/测试环境应该区分是否启用Reactotron。
修正模拟文件的createEnhancer方法
修改reactotron-react-native.js中的createEnhancer,让它返回一个符合Redux要求的空enhancer:export const Reactotron = { configure: () => Reactotron, useReactNative: () => Reactotron, asyncStorage: () => Reactotron, trackGlobalErrors: () => Reactotron, // 返回无操作的空enhancer,适配Redux要求 createEnhancer: () => (createStore) => createStore, use: () => Reactotron, connect: () => Reactotron, clear: () => Reactotron, }; module.exports = Reactotron;在store中区分环境加载Reactotron
避免在测试/生产环境中加载Reactotron enhancer,只在开发环境启用:import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit'; import rootReducer from './reducers'; let enhancers = []; // 仅在开发环境加载Reactotron if (__DEV__) { const Reactotron = require('../../reactotronConfig').default; enhancers.push(Reactotron.createEnhancer!()); } export const store = configureStore({ reducer: rootReducer, middleware: [], enhancers, });确保Jest正确识别模拟文件
在Jest配置文件(如jest.config.js)中确认已映射Reactotron的模拟路径:module.exports = { // ...其他Jest配置项 moduleNameMapper: { 'reactotron-react-native': '<rootDir>/path/to/your/reactotron-react-native.js', }, };
修改完成后,测试环境下Reactotron的enhancer会被替换为无操作的空函数,不会再触发createEnhancer is not a function的错误,同时开发环境依然能正常使用Reactotron的调试功能。
内容的提问来源于stack exchange,提问作者Hristo Dimitrov
相关产品推荐
相关产品推荐

