ReferenceError:未定义窗口。当我通过jest运行npm测试进行单元测试时出现此错误。错误来自以下代码导出功能。有人遇到过这种错误并解决了吗?
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../modules/rootReducer';
export function injectAsyncReducers(asyncReducers) {
const injectReducers = Object.keys(asyncReducers).reduce((all, item) => {
if (store.asyncReducers[item]) {
delete all[item];
}
return all;
}, asyncReducers);
store.asyncReducers = Object.assign({}, store.asyncReducers, injectReducers);
replaceReducers(rootReducer);
}
答案 0 :(得分:3)
当您没有使用正确的testEnviremoent配置进行开玩笑时,通常会出现此错误,在这种情况下,它应该是 jsdom (您可以在此处查看它:{{3 }})。您可以在 package.json 文件中对其进行配置,如下所示:
"jest": {"testEnvironment": "node"}
如果您正在使用 create-react-app ,则测试脚本应如下所示:
"test": "react-scripts test --env=jsdom"
或者您可以在此处查看testEviroment配置的更多选项:https://github.com/tmpvar/jsdom
答案 1 :(得分:0)
嗯,没有窗口,因为你在终端上运行jest,而不是浏览器。您应该手动将窗口定义为全局变量。
package.json
...
"jest": {
"globals": {
"window": {
// whatever you need, put here manually.
}
}
}