I'm attempting to use the ESLint linter with the Jest testing framework.
Jest tests run with some globals like jest
, which I'll need to tell the linter about; but the tricky thing is the directory structure, with Jest the tests are embedded with the source code in __tests__
folders, so the directory structure looks something like:
src
foo
foo.js
__tests__
fooTest.js
bar
bar.js
__tests__
barTest.js
Normally, I'd have all my tests under a single dir, and I could just add an .eslintrc
file there to add the globals... but I certainly don't want to add a .eslintrc
file to every single __test__
dir.
For now, I've just added the test globals to the global .eslintrc
file, but since that means I could now reference jest
in non-testing code, that doesn't seem like the "right" solution.
Is there a way to get eslint to apply rules based on some pattern based on the directory name, or something like that?
To complete Zachary's answer, here is a workaround for the "extend in overrides" limitation of eslint config :
From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724
Pattern based configs are scheduled for 2.0.0 release of ESLint. For now, however, you will have to create two separate tasks (as mentioned in the comments). One for tests and one for the rest of the code and run both of them, while providing different .eslintrc files.
P.S. There's a jest environment coming in the next release of ESLint, it will register all of the necessary globals.
You can also set the test env in your test file as follows:
In your .eslintignore file add the following value:
This should ignore all instances of the __tests__ directory and their children.
Add environment only for
__tests__
folderYou could add a
.eslintrc.yml
file in your__tests__
folders, that extends you basic configuration:If you have only one
__tests__
folder, this solution is the best since it scope jest environment only where it is needed.Dealing with many test folders
If you have more test folders (OPs case), I'd still suggest to add those files. And if you have tons of those folders can add them with a simple zsh script:
This script will look for
__tests__
folders and add a.eslintrc.yml
file with to configuration shown above. This script has to be launched within the folder containing your parent.eslintrc
.The docs show you are now able to add:
To your
.eslintrc
which will add all the jest related things to your environment, eliminating the linter errors/warnings.Hope that helps!