Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ESLint doesn't recognize node.js's 'global' object

The error:

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

My current ESLint config:

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

An simplified example test file that causes the ESLint error:

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

I expected this Jest feature to be covered by having the env: { jest: true } in the eslint config. I can of course disable the rule or line in the file, but then I'd need to do that every time I use global.

like image 809
bananabanana Avatar asked Mar 08 '23 23:03

bananabanana


1 Answers

The global object is part of Node.js. It is not specific to Jest and therefore it's not included in the jest environment. In fact, you are running your unit tests in Node and you happen to use the global object for your tests. In general the globals defined for specific libraries are the ones they provide to make it more convenient to use them without having to import them. A counterexample would be AVA, which requires you to import it instead of defining globals.

If you want to use ESLint for the tests as well, you would have to add the node environment.

env: {
  browser: true,
  es6: true,
  node: true,
  jest: true
},
like image 167
Michael Jungo Avatar answered Mar 19 '23 23:03

Michael Jungo