【问题标题】:ESLint doesn't recognize node.js's 'global' objectESLint 无法识别 node.js 的“全局”对象
【发布时间】:2017-09-25 20:48:19
【问题描述】:

错误:

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

【问题讨论】:

标签: javascript node.js unit-testing jestjs eslint


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 2016-06-02
    • 2019-08-05
    • 1970-01-01
    • 2016-02-27
    • 2011-05-07
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多