javascript - ESLint 无法识别 node.js 的 'global' 对象

标签 javascript node.js unit-testing jestjs eslint

错误:

3:5  error  'global' is not defined  no-undef

我当前的 ESLint 配置:

module.exports = {
  parser: "babel-eslint",
  env: {
    browser: true,
    es6: true,
    "jest/globals": true,
    jest: true
  },
  extends: ["eslint:recommended", "plugin:react/recommended", "prettier", "prettier/react"],
  parserOptions: {
    ecmaFeatures: {
      experimentalObjectRestSpread: true,
      jsx: true
    },
    sourceType: "module"
  },
  globals: {
    testGlobal: true
  },
  plugins: ["react", "prettier", "jest"],
  rules: {
    "prettier/prettier": 1,
    "no-console": 0
  }
};

导致 ESLint 错误的简化示例测试文件:

describe("Jest global:", () => {
  it("should not cause ESLint error", () => {
    global.testGlobal = {
      hasProp: true
    };
  });
});

我希望在 eslint 配置中包含 env: { jest: true } 来涵盖这个 Jest 功能。我当然可以禁用文件中的规则或行,但每次使用 global 时我都需要这样做。

最佳答案

global object是 Node.js 的一部分。它不是 Jest 特有的,因此它不包含在 jest 环境中。事实上,您正在 Node 中运行单元测试,并且碰巧使用了 global 对象进行测试。通常,为特定库定义的全局变量是它们提供的,以便在无需导入它们的情况下更方便地使用它们。一个反例是 AVA, which requires you to import it而不是定义全局变量。

如果您也想使用 ESLint 进行测试,则必须添加 node 环境。

env: {
  browser: true,
  es6: true,
  node: true,
  jest: true
},

关于javascript - ESLint 无法识别 node.js 的 'global' 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46413935/

相关文章:

node.js - 在bat文件中查询npm错误状态

javascript - 如何迭代生成器函数的结果

javascript - 在 NodeJS 的 while 循环中读取文件

javascript - Google OAuth2来源不匹配

Android - Assertj Android - 运行错误

java - Easymock 模拟输入流读取操作

javascript - Angular Testing 示例失败

javascript - 如何设置条件来比较两个值并执行指定的功能

javascript - 无法从图像 slider 上的 Bootstrap 导航中删除背景颜色

javascript - 如何将 goog.ui.Autocomplete 最小输入设置为 0