ReferenceError:未定义窗口.当我开玩笑地从npm测试运行到单元测试时,我得到了这个错误



ReferenceError:窗口未定义。当我开玩笑地从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);
}

当您没有使用正确的testEnvirement配置进行jest时,通常会出现此错误,在这种情况下,它应该是jsdom(您可以在此处查看:https://github.com/tmpvar/jsdom)。您可以在包.json文件中配置它,如下所示:

"jest": {"testEnvironment": "node"}

如果您使用创建react应用程序,您的测试脚本应该是这样的:

"test": "react-scripts test --env=jsdom"

或者,您可以在此处查看testEviroment配置的更多选项:https://facebook.github.io/jest/docs/en/configuration.html#testenvironment-字符串

好吧,没有窗口,因为您在终端上运行的是jest,而不是浏览器。您应该手动将window定义为全局变量。

package.json

...
"jest": {
"globals": {
"window": {
// whatever you need, put here manually.
}
}
}

相关内容

  • 没有找到相关文章