错误:
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
时我都需要这样做。
答案 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
},