javascriptunit-testingjestjseslint

eslint throws `no-undef` errors when linting Jest test files


I'm using Jest to write some specs and ESLint to lint the styling.

For my foo.spec.js tests, eslint keeps throwing the following errors. It seems to think that jest, beforeEach, afterEach, etc... are not defined in that file.

   11:1   error  'beforeEach' is not defined  no-undef
   12:3   error  'jest' is not defined        no-undef
   14:13  error  'jest' is not defined        no-undef
   18:1   error  'afterEach' is not defined   no-undef
   20:1   error  'describe' is not defined    no-undef
   21:3   error  'it' is not defined          no-undef
   25:5   error  'expect' is not defined      no-undef
   28:5   error  'expect' is not defined      no-undef
   31:5   error  'expect' is not defined      no-undef
   34:3   error  'it' is not defined          no-undef
   38:5   error  'expect' is not defined      no-undef
   41:5   error  'jest' is not defined        no-undef
   42:5   error  'expect' is not defined      no-undef
   43:5   error  'expect' is not defined      no-undef
   46:3   error  'it' is not defined          no-undef
   54:5   error  'expect' is not defined      no-undef
   58:5   error  'jest' is not defined        no-undef

I believe those are included by jest automatically and so they don't need to be explicitly imported in my spec files. In fact the only thing I import via my jest.setup.js file is

import "react-testing-library/cleanup-after-each";
import "jest-dom/extend-expect";

Is there a way to eliminate these errors without having to disable eslint rules at the top of each individual file or inline?

Thanks!


Solution

  • Please, add the following to your .eslintrc file:

    {
      "overrides": [
        {
          "files": [
            "**/*.spec.js",
            "**/*.spec.jsx"
          ],
          "env": {
            "jest": true
          }
        }
      ]
    }