Explain Codes LogoExplain Codes Logo

How to use ESLint with Jest

javascript
eslint
jest
testing
Alex KataevbyAlex Kataev·Dec 2, 2024
TLDR

In order for ESLint to recognize Jest's environment, set env.jest: true in your configuration. Include eslint-plugin-jest for linting rules specific to Jest:

module.exports = { env: { jest: true, }, plugins: ['jest'], extends: ['plugin:jest/recommended'], };

This configuration helps ESLint to apply best practices and avoid common issues found in Jest tests.

Detailed configuration guide

Improve your development workflows by understanding more intricate parts of ESLint and Jest integration. Let's deep-dive into how each setting affects your codebase.

Using overrides for test files only

For applying distinct rules to your test files without interfering with production scripts, establish overrides in your .eslintrc file.

module.exports = { // ...Existing configuration... overrides: [ { files: ['**/*.test.js', '**/*.spec.js'], env: { 'jest/globals': true, // Because "Jest is best" }, }, ], };

Single file ESLint-Jest regulation

You can opt-out of applying Jest related ESLint rules globally by using inline ESLint environment declarations.

/* eslint-env jest */ // Only you can see me, ESLint

Add this to your test files to let ESLint know that Jest rules are applicable.

Dynamic configurations with ESLint v4+ overrides

Customize your configurations with the plus features of ESLint v4+ overrides, making use of Object.assign. And TypeScript developers, don’t forget to install @types/jest for Jest's TypeScript definitions.

Practical jest with ESLint

Here are some additional configurations and tips to consider to make your ESLint and Jest integration flawless.

Avoid errors in non-test code

Ensure Jest-related globals aren't mistakenly referenced in your non-testing code with a precise specifier:

{ // ...overrides section... files: ['**/__tests__/**/*.js', '**/*.test.js'], env: { jest: true, // Anything outside these files, Jest is a pest }, }

Engage the community

Peruse GitHub issues and discussions for communal solutions and workarounds. It's far from a wild goose chase!

Documentation is your beacon

Utilize the eslint-plugin-jest documentation for information on setup and configurations. The ESLint official documentation also films the nitty-gritty of Jest integration and override functionality.