【问题标题】:ReferenceError: window is not defined. I got this error when I run npm test to unit testing by jestReferenceError:未定义窗口。当我通过 jest 运行 npm test 进行单元测试时出现此错误
【发布时间】:2018-05-04 13:30:23
【问题描述】:

ReferenceError:未定义窗口。当我运行 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);
}

【问题讨论】:

  • redux 代码本身没有引用window。你的rootReducer 是什么样的?
  • 这是我的 rootReducer 文件代码 import { combineReducers } from 'redux';从'../reducers/fetchMenu'导入菜单;从 '../reducers/chooseOrderType' 导入 o​​rderType;从'../reducers/fetchVendorInfo'导入供应商;导出默认 combineReducers({ menu, vendor, orderType });

标签: reactjs react-native react-redux jestjs


【解决方案1】:

这个错误通常在你没有使用正确的 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】:

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

package.json

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

【讨论】:

  • 返回如下错误 typeError: window.WebSocket is not a constructor
  • 正如@henrik-andersson 提到的,你最好找到引用window.WebSocket 的包。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-26
  • 2021-02-07
  • 1970-01-01
  • 2021-03-19
  • 1970-01-01
  • 2020-10-09
相关资源
最近更新 更多