Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

ESLint plugin for Jest

License

NotificationsYou must be signed in to change notification settings

jest-community/eslint-plugin-jest

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

eslint-plugin-jest

ESLint plugin for Jest

Actions Status

Installation

yarn add --dev eslint eslint-plugin-jest

Note: If you installed ESLint globally then you must also installeslint-plugin-jest globally.

Usage

If you're using flat configuration:

Withflat configuration,just import the plugin and away you go:

constpluginJest=require('eslint-plugin-jest');module.exports=[{// update this to match your test filesfiles:['**/*.spec.js','**/*.test.js'],plugins:{jest:pluginJest},languageOptions:{globals:pluginJest.environments.globals.globals,},rules:{'jest/no-disabled-tests':'warn','jest/no-focused-tests':'error','jest/no-identical-title':'error','jest/prefer-to-have-length':'warn','jest/valid-expect':'error',},},];

With legacy configuration, addjest to the plugins section of your.eslintrcconfiguration file. You can omit theeslint-plugin- prefix:

{"plugins": ["jest"],"env": {"jest/globals":true  },"rules": {"jest/no-disabled-tests":"warn","jest/no-focused-tests":"error","jest/no-identical-title":"error","jest/prefer-to-have-length":"warn","jest/valid-expect":"error"  }}

Note

You only need to explicitly include our globals if you're not using one of ourshared configs

Aliased Jest globals

You can tell this plugin about any global Jests you have aliased using theglobalAliases setting:

{"settings": {"jest": {"globalAliases": {"describe": ["context"],"fdescribe": ["fcontext"],"xdescribe": ["xcontext"]      }    }  }}

Aliased@jest/globals

You can tell this plugin to treat a different package as the source of Jestglobals using theglobalPackage setting:

{"settings": {"jest": {"globalPackage":"bun:test"    }  }}

Warning

While this can be used to apply rules when using alternative testing librariesand frameworks likebun,vitest andnode, there's no guarantee thesemantics this plugin assumes will hold outside of Jest

Running rules only on test-related files

The rules provided by this plugin assume that the files they are checking aretest-related. This means it's generally not suitable to include them in yourtop-level configuration as that applies to all files being linted which caninclude source files.

For.eslintrc configs you can useoverridesto have ESLint apply additional rules to specific files:

{"extends": ["eslint:recommended"],"overrides": [    {"files": ["test/**"],"plugins": ["jest"],"extends": ["plugin:jest/recommended"],"rules": {"jest/prefer-expect-assertions":"off" }    }  ],"rules": {"indent": ["error",2]  }}

Foreslint.config.js you can usefiles andignores:

constjest=require('eslint-plugin-jest');module.exports=[  ...require('@eslint/js').configs.recommended,{files:['test/**'],    ...jest.configs['flat/recommended'],rules:{      ...jest.configs['flat/recommended'].rules,'jest/prefer-expect-assertions':'off',},},// you can also configure jest rules in other objects, so long as some of the `files` match{files:['test/**'],rules:{'jest/prefer-expect-assertions':'off'},},];

Jestversion setting

The behaviour of some rules (specificallyno-deprecated-functions) changedepending on the version of Jest being used.

By default, this plugin will attempt to determine to locate Jest usingrequire.resolve, meaning it will start looking in the closestnode_modulesfolder to the file being linted and work its way up.

Since we cache the automatically determined version, if you're lintingsub-folders that have different versions of Jest, you may find that the wrongversion of Jest is considered when linting. You can work around this byproviding the Jest version explicitly in nested ESLint configs:

{"settings": {"jest": {"version":27    }  }}

To avoid hard-coding a number, you can also fetch it from the installed versionof Jest if you use a JavaScript config file such as.eslintrc.js:

module.exports={settings:{jest:{version:require('jest/package.json').version,},},};

Shareable configurations

Note

eslint.config.js compatible versions of configs are available prefixed withflat/ and may be subject to small breaking changes while ESLint v9 is beingfinalized.

Recommended

This plugin exports a recommended configuration that enforces good testingpractices.

To enable this configuration with.eslintrc, use theextends property:

{"extends": ["plugin:jest/recommended"]}

To enable this configuration witheslint.config.js, usejest.configs['flat/recommended']:

constjest=require('eslint-plugin-jest');module.exports=[{files:[/* glob matching your test files */],    ...jest.configs['flat/recommended'],},];

Style

This plugin also exports a configuration namedstyle, which adds somestylistic rules, such asprefer-to-be-null, which enforces usage oftoBeNullovertoBe(null).

To enable this configuration use theextends property in your.eslintrcconfig file:

{"extends": ["plugin:jest/style"]}

To enable this configuration witheslint.config.js, usejest.configs['flat/style']:

constjest=require('eslint-plugin-jest');module.exports=[{files:[/* glob matching your test files */],    ...jest.configs['flat/style'],},];

All

If you want to enable all rules instead of only some you can do so by adding theall configuration to your.eslintrc config file:

{"extends": ["plugin:jest/all"]}

To enable this configuration witheslint.config.js, usejest.configs['flat/all']:

constjest=require('eslint-plugin-jest');module.exports=[{files:[/* glob matching your test files */],    ...jest.configs['flat/all'],},];

While therecommended andstyle configurations only change in major versionstheall configuration may change in any release and is thus unsuited forinstallations requiring long-term consistency.

Rules

💼Configurationsenabled in.
⚠️Configurationsset to warn in.
✅ Set in therecommendedconfiguration.
🎨Set in thestyleconfiguration.
🔧Automatically fixable by the--fix CLI option.
💡Manually fixable byeditor suggestions.

Name                             Description💼⚠️🔧💡
consistent-test-itEnforcetest andit usage conventions🔧
expect-expectEnforce assertion to be made in a test body
max-expectsEnforces a maximum number assertion calls in a test body
max-nested-describeEnforces a maximum depth to nested describe calls
no-alias-methodsDisallow alias methods🔧
no-commented-out-testsDisallow commented out tests
no-conditional-expectDisallow callingexpect conditionally
no-conditional-in-testDisallow conditional logic in tests
no-confusing-set-timeoutDisallow confusing usages of jest.setTimeout
no-deprecated-functionsDisallow use of deprecated functions🔧
no-disabled-testsDisallow disabled tests
no-done-callbackDisallow using a callback in asynchronous tests and hooks💡
no-duplicate-hooksDisallow duplicate setup and teardown hooks
no-exportDisallow usingexports in files containing tests
no-focused-testsDisallow focused tests💡
no-hooksDisallow setup and teardown hooks
no-identical-titleDisallow identical titles
no-interpolation-in-snapshotsDisallow string interpolation inside snapshots
no-jasmine-globalsDisallow Jasmine globals🔧
no-large-snapshotsDisallow large snapshots
no-mocks-importDisallow manually importing from__mocks__
no-restricted-jest-methodsDisallow specificjest. methods
no-restricted-matchersDisallow specific matchers & modifiers
no-standalone-expectDisallow usingexpect outside ofit ortest blocks
no-test-prefixesRequire using.only and.skip overf andx🔧
no-test-return-statementDisallow explicitly returning from tests
no-untyped-mock-factoryDisallow usingjest.mock() factories without an explicit type parameter🔧
padding-around-after-all-blocksEnforce padding aroundafterAll blocks🔧
padding-around-after-each-blocksEnforce padding aroundafterEach blocks🔧
padding-around-allEnforce padding around Jest functions🔧
padding-around-before-all-blocksEnforce padding aroundbeforeAll blocks🔧
padding-around-before-each-blocksEnforce padding aroundbeforeEach blocks🔧
padding-around-describe-blocksEnforce padding arounddescribe blocks🔧
padding-around-expect-groupsEnforce padding aroundexpect groups🔧
padding-around-test-blocksEnforce padding aroundtest andit blocks🔧
prefer-called-withSuggest usingtoBeCalledWith() ortoHaveBeenCalledWith()
prefer-comparison-matcherSuggest using the built-in comparison matchers🔧
prefer-eachPrefer using.each rather than manual loops
prefer-ending-with-an-expectPrefer having the last statement in a test be an assertion
prefer-equality-matcherSuggest using the built-in equality matchers💡
prefer-expect-assertionsSuggest usingexpect.assertions() ORexpect.hasAssertions()💡
prefer-expect-resolvesPreferawait expect(...).resolves overexpect(await ...) syntax🔧
prefer-hooks-in-orderPrefer having hooks in a consistent order
prefer-hooks-on-topSuggest having hooks before any test cases
prefer-importing-jest-globalsPrefer importing Jest globals🔧
prefer-jest-mockedPreferjest.mocked() overfn as jest.Mock🔧
prefer-lowercase-titleEnforce lowercase test names🔧
prefer-mock-promise-shorthandPrefer mock resolved/rejected shorthands for promises🔧
prefer-snapshot-hintPrefer including a hint with external snapshots
prefer-spy-onSuggest usingjest.spyOn()🔧
prefer-strict-equalSuggest usingtoStrictEqual()💡
prefer-to-beSuggest usingtoBe() for primitive literals🎨🔧
prefer-to-containSuggest usingtoContain()🎨🔧
prefer-to-have-lengthSuggest usingtoHaveLength()🎨🔧
prefer-todoSuggest usingtest.todo🔧
require-hookRequire setup and teardown code to be within a hook
require-to-throw-messageRequire a message fortoThrow()
require-top-level-describeRequire test cases and hooks to be inside adescribe block
valid-describe-callbackEnforce validdescribe() callback
valid-expectEnforce validexpect() usage🔧
valid-expect-in-promiseRequire promises that have expectations in their chain to be valid
valid-titleEnforce valid titles🔧

Requires Type Checking

Name          Description💼⚠️🔧💡
unbound-methodEnforce unbound methods are called with their expected scope

In order to use the rules powered by TypeScript type-checking, you must be using@typescript-eslint/parser & adjust your eslint config as outlinedhere.

Note that unlike the type-checking rules in@typescript-eslint/eslint-plugin,the rules here will fallback to doing nothing if type information is notavailable, meaning it's safe to include them in shared configs that could beused on JavaScript and TypeScript projects.

Also note thatunbound-method depends on@typescript-eslint/eslint-plugin,as it extends the originalunbound-method rule from that plugin.

Credit

Related Projects

eslint-plugin-jest-extended

This is a sister plugin toeslint-plugin-jest that provides support for thematchers provided byjest-extended.

https://github.com/jest-community/eslint-plugin-jest-extended

eslint-plugin-jest-formatting

This project aims to provide formatting rules (auto-fixable where possible) toensure consistency and readability in jest test suites.

https://github.com/dangreenisrael/eslint-plugin-jest-formatting

eslint-plugin-istanbul

A set of rules to enforce good practices for Istanbul, one of the code coveragetools used by Jest.

https://github.com/istanbuljs/eslint-plugin-istanbul


[8]ページ先頭

©2009-2025 Movatter.jp