我用 React Redux 创建了一个 tic tac toe 游戏。
我正在使用create-react-app .
我有以下商店:
import {createStore, combineReducers} from 'redux';
import gameSettingsReducer from './reducers/gameSettings.js';
import gameStatusReducer from './reducers/gameStatus.js';
const rootReducer = combineReducers({gameSettings: gameSettingsReducer,
gameStatus: gameStatusReducer});
export const defaultGameStatus = {
currentPlayerSymbol: "X",
turnNumber: 0,
currentView: "start-menu", //one of "start-menu", "in-game", "game-over"
winner: "draw", //one of "X", "O", "draw"
board: [["E", "E", "E"],
["E", "E", "E"],
["E", "E", "E"]],
lastMove: []
};
const store = createStore(rootReducer, {
gameSettings:{
playerSymbol: "X", //one of "X", "O"
difficulty: "easy" //one of "easy", "hard"
},
gameStatus: defaultGameStatus
});
export default store;
一切都按我的预期进行。除了当我运行测试(npm test
)时,控制台中会显示以下内容:
console.error node_modules\redux\lib\utils\warning.js:14
No reducer provided for key "gameStatus"
console.error node_modules\redux\lib\utils\warning.js:14
Unexpected key "gameStatus" found in preloadedState argument passed to createStore. Expected to find one of the known reducer keys instead: "gameSettings". Unexpected keys will be ignored.
在我进行的少数测试中,我什至没有测试商店。所以我猜这是在编译代码时出现的。
我尝试将 console.log(gameStatusReducer)
放在根 reducer 行之前。
它表明 gameStatusReducer 未定义。
由于 gameSettingsReducer 和 gameStatusReducer 的创建方式非常相似,我不知道这个错误从何而来,甚至不知道如何进一步调查该问题。这仅在运行测试时显示。运行应用程序不会出现此问题,并且应用程序按预期工作。
所以,问题是:
- 为什么这个只出现在测试中?
- 如何调查问题出在哪里?
最佳答案
经过多次用头撞键盘后,我发现了一些线索。
快速修复:制作正常的 export
对于 gameStateReducer
而不是default
并使用 import { gameStateReducer } from // ...
将其导入到其他地方.
Jest 会自动模拟一些导入,显然在这种情况下它是有问题的,或者它需要某种配置 react-create-app
尚未提供。
至于为什么 Jest 甚至记录该错误(考虑到相关代码未在任何测试中导入),我认为这是由于其内部工作原理。
支持这一点的是以下证据:添加 --testPathPattern
标记为npm test
脚本仅匹配以 .test.js
结尾的文件不会改变行为,错误仍然出现。
如何调查问题:我首先确定导致错误日志的代码是否在测试中(可能是间接的,例如 import
)。排除这一点后,我开始模拟传递给 combineReducers
的函数。确保任何更改都会影响错误日志的结果,他们确实做到了。只需添加以下内容:
gameStatus: gameStatusReducer || (() => ())
...已经解决了问题,这意味着问题出在 import
上。以及如何开玩笑/babel-jest
处理它。
如果我要进一步调查这个问题,我将使用 Jest 创建自己的安装并提供自己的配置,以查看 Jest 是否仍然编译整个应用程序。如果您使用 react-create-app
,将配置选项传递给 Jest 似乎并不简单.
祝你好运!
关于reactjs - Redux 警告仅出现在测试中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43375079/