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!
Please, add the following to your .eslintrc file:
{
"overrides": [
{
"files": [
"**/*.spec.js",
"**/*.spec.jsx"
],
"env": {
"jest": true
}
}
]
}
You do not need to add this override option and specify in which files jest
should be available. Adding only env
field should be enough.
.eslintrc.js:
module.exports = {
env: {
jest: true
},
//...
}
Had a similar problem with eslint throwing no-undef errors for my jest setup.js file with some jest.mocks in it.
Ended up fixing it by using the ESLint plugin for Jest.
After installing the plugin as a dev dependency, I merged the following into my .eslintrc config file per instructions from the plugin readme.
{
"extends": ["plugin:jest/recommended"],
"plugins": ["jest"]
}
Then the no-undef errors are gone.