错误:
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/