Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ESLint with Jest

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?

like image 607
Retsam Avatar asked Jul 25 '15 17:07

Retsam


People also ask

What is ESLint plugin jest?

eslint-plugin-istanbulA set of rules to enforce good practices for Istanbul, one of the code coverage tools used by Jest.

What is ESLint and how do you use it?

ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code, with the goal of making code more consistent and avoiding bugs. In many ways, it is similar to JSLint and JSHint with a few exceptions: ESLint uses Espree for JavaScript parsing.

How do I use ESLint plugin?

To use the rule in ESLint, you would use the unprefixed plugin name, followed by a slash, followed by the rule name. So if this plugin were named eslint-plugin-myplugin , then in your configuration you'd refer to the rule by the name myplugin/dollar-sign . Example: "rules": {"myplugin/dollar-sign": 2} .

Does ESLint require node?

ESLint requires Node. js for installation. Follow the instructions in the Getting Started Guide to install ESLint. Note: You can also use alternative package managers such as Yarn or pnpm to run ESLint.


1 Answers

The docs show you are now able to add:

"env": {     "jest/globals": true } 

To your .eslintrc which will add all the jest related things to your environment, eliminating the linter errors/warnings.

You may need to include plugins: ["jest"] to your esconfig, and add the eslint-plugin-jest plugin if it still isn't working.

like image 132
Dave Cooper Avatar answered Sep 23 '22 13:09

Dave Cooper