ESLint无法识别node.js的“全局”对象

时间:2017-09-25 20:48:20

标签: 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时我都需要这样做。

1 个答案:

答案 0 :(得分:6)

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
},