参考错误:未定义窗口。当我通过 jest 运行 npm test 进行单元测试时出现此错误

kha*_*hul 4 reactjs jestjs react-native react-redux

参考错误:未定义窗口。当我通过 jest 运行 npm test 进行单元测试时出现此错误。错误来自以下代码导出功能。任何人遇到这种类型的错误并解决了它?

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);
}
Run Code Online (Sandbox Code Playgroud)

小智 7

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

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

如果你使用create-react-app,你的测试脚本应该是这样的:

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

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

  • 添加 `--env=jsdom` 解决了我的问题。我正在将一个项目迁移到 CRA,但忘记将其添加到我的测试命令中 (2认同)