1.0.0 β€’ Published 8 months ago

@ryniaubenpm2/laudantium-quo-amet v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

Actions Status

Installation

yarn add --dev eslint @ryniaubenpm2/laudantium-quo-amet

Note: If you installed ESLint globally then you must also install @ryniaubenpm2/laudantium-quo-amet globally.

Usage

!NOTE

eslint.config.js is supported, though most of the plugin documentation still currently uses .eslintrc syntax.

Refer to the ESLint documentation on the new configuration file format for more.

Add jest to the plugins section of your .eslintrc configuration file. You can omit the eslint-plugin- prefix:

{
  "plugins": ["jest"]
}

Then configure the rules you want to use under the rules section.

{
  "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"
  }
}

You can also tell ESLint about the environment variables provided by Jest by doing:

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

This is included in all configs shared by this plugin, so can be omitted if extending them.

Aliased Jest globals

You can tell this plugin about any global Jests you have aliased using the globalAliases 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 Jest globals using the globalPackage setting:

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

!WARNING

While this can be used to apply rules when using alternative testing libraries and frameworks like bun, vitest and node, there's no guarantee the semantics 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 are test-related. This means it's generally not suitable to include them in your top-level configuration as that applies to all files being linted which can include source files.

For .eslintrc configs you can use overrides to 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]
  }
}

For eslint.config.js you can use files and ignores:

const jest = require('@ryniaubenpm2/laudantium-quo-amet');

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' },
  },
];

Jest version setting

The behaviour of some rules (specifically no-deprecated-functions) change depending on the version of Jest being used.

By default, this plugin will attempt to determine to locate Jest using require.resolve, meaning it will start looking in the closest node_modules folder to the file being linted and work its way up.

Since we cache the automatically determined version, if you're linting sub-folders that have different versions of Jest, you may find that the wrong version of Jest is considered when linting. You can work around this by providing 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 version of 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 with flat/ and may be subject to small breaking changes while ESLint v9 is being finalized.

Recommended

This plugin exports a recommended configuration that enforces good testing practices.

To enable this configuration with .eslintrc, use the extends property:

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

To enable this configuration with eslint.config.js, use jest.configs['flat/recommended']:

const jest = require('@ryniaubenpm2/laudantium-quo-amet');

module.exports = [
  {
    files: [
      /* glob matching your test files */
    ],
    ...jest.configs['flat/recommended'],
  },
];

Style

This plugin also exports a configuration named style, which adds some stylistic rules, such as prefer-to-be-null, which enforces usage of toBeNull over toBe(null).

To enable this configuration use the extends property in your .eslintrc config file:

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

To enable this configuration with eslint.config.js, use jest.configs['flat/style']:

const jest = require('@ryniaubenpm2/laudantium-quo-amet');

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 the all configuration to your .eslintrc config file:

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

To enable this configuration with eslint.config.js, use jest.configs['flat/all']:

const jest = require('@ryniaubenpm2/laudantium-quo-amet');

module.exports = [
  {
    files: [
      /* glob matching your test files */
    ],
    ...jest.configs['flat/all'],
  },
];

While the recommended and style configurations only change in major versions the all configuration may change in any release and is thus unsuited for installations requiring long-term consistency.

Rules

πŸ’Ό Configurations enabled in.\ ⚠️ Configurations set to warn in.\ βœ… Set in the recommended configuration.\ 🎨 Set in the style configuration.\ πŸ”§ Automatically fixable by the --fix CLI option.\ πŸ’‘ Manually fixable by editor suggestions.

NameΒ Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β DescriptionπŸ’Όβš οΈπŸ”§πŸ’‘
consistent-test-itEnforce test and it 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 calling expect 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 using exports 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 specific jest. methods
no-restricted-matchersDisallow specific matchers & modifiers
no-standalone-expectDisallow using expect outside of it or test blocksβœ…
no-test-prefixesRequire using .only and .skip over f and xβœ…πŸ”§
no-test-return-statementDisallow explicitly returning from tests
no-untyped-mock-factoryDisallow using jest.mock() factories without an explicit type parameterπŸ”§
prefer-called-withSuggest using toBeCalledWith() or toHaveBeenCalledWith()
prefer-comparison-matcherSuggest using the built-in comparison matchersπŸ”§
prefer-eachPrefer using .each rather than manual loops
prefer-equality-matcherSuggest using the built-in equality matchersπŸ’‘
prefer-expect-assertionsSuggest using expect.assertions() OR expect.hasAssertions()πŸ’‘
prefer-expect-resolvesPrefer await expect(...).resolves over expect(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-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 using jest.spyOn()πŸ”§
prefer-strict-equalSuggest using toStrictEqual()πŸ’‘
prefer-to-beSuggest using toBe() for primitive literalsπŸŽ¨πŸ”§
prefer-to-containSuggest using toContain()πŸŽ¨πŸ”§
prefer-to-have-lengthSuggest using toHaveLength()πŸŽ¨πŸ”§
prefer-todoSuggest using test.todoπŸ”§
require-hookRequire setup and teardown code to be within a hook
require-to-throw-messageRequire a message for toThrow()
require-top-level-describeRequire test cases and hooks to be inside a describe block
valid-describe-callbackEnforce valid describe() callbackβœ…
valid-expectEnforce valid expect() 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 outlined here.

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

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

Credit

Related Projects

@ryniaubenpm2/laudantium-quo-amet-extended

This is a sister plugin to @ryniaubenpm2/laudantium-quo-amet that provides support for the matchers provided by jest-extended.

https://github.com/ryniaubenpm2/laudantium-quo-amet-extended

@ryniaubenpm2/laudantium-quo-amet-formatting

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

https://github.com/dangreenisrael/@ryniaubenpm2/laudantium-quo-amet-formatting

eslint-plugin-istanbul

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

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

sortvaluesfindLastincludesclipredictablejsdifftrimRightes8typeoftostringtagparentclassessymbolsairbnbkeystylingES6exeutilitieswatchertypesafejscloudwatchstructuredCloneglobloginputslicedataViewastes-shimsformObject.fromEntriescompilerinspectcheckpromiseuuiditeratecss variabledeep-cloneauthjestavajavascriptupsyntaxObservablesmulti-packagepropertydirwritableeslint-pluginbrowserslistl10nserialize[[Prototype]]descriptionisremovemoveparsingcircularTypeBoxrandomextendflagsimportbreakwhatwgbannerflatMapregexdayjscreateyuprobustrgbbusysetPrototypeOfInt8Arraydeletestyled-componentstyped arraynodejsform-validationpushelasticachecloudformationwalkintrinsicoptionparsercopycryptoregular expressionssymbolcall-boundgradients css3mergeassertsbindopenerprivateES7es2016internalprotopasswordmake dirSymbol.toStringTagviewlintenvironmentclass-validatoreditorargumentmimestreamhandlerstoSorteddomfilterentrieslinuxcryptString.prototype.trimqsfullwidthfetchfunctionalpolyfillArrayBuffer.prototype.sliceshrinkwrapnegativetextMicrosoftdeepcloneapidom-testing-librarystatelessweaksetlruwordbreakconsolefunctionwatchcharacterswfrequireestreerestfulpruneirqdatastructureassignvalidationendpointchinesemrunested cssextrafromfast-copywatchFileserializationopenauthenticationreact-hookseslintpluginstatusruntimerecursivees-shim APITypeScriptRegExp.prototype.flagsforEachtc39warningcommand-linejapanesecjkenvpicomatchlivedescriptorsArray.prototype.flattennopeECMAScript 6ES2017amazonuninstallhaslinkflattenaccessibilityrateECMAScript 2020connectJSONpositivefind-upinstallreadconsumedeepcopycolornodeyamlpropertieses2017functionslockfiletoArrayESnextcss-in-jswafasciisetteres7descriptorArray.prototype.flatio-tstoobjecthelperselectronpatchjsxeventDispatcherweakmapsideES3websiteeslintless mixinsworkspace:*RFC-6455rapidappnativedroprouterlanguageUint8ClampedArraycloudtrailObject.isYAMLvesttestingmkdirredux-toolkitURLSearchParamsinclonedynamodbcompile lessmobilebluebirdthroatawseast-asian-widthjQuerylaunches2015Object.entriesdeterministicmomentidentifierscodesdirectoryproxyroute53es5typedarraysredactpromiseshas-owngetOwnPropertyDescriptorloggingtimearrayequalityreducerkinesisimmutableinvariantguidprogresswaitBigInt64ArrayhooksSeti18nECMAScript 2023syntaxerrorfindLastIndexgroupgenericschaisettingssnsenvironmentscommandkarmas3npmframeworkhttpsshamjsonpathcensorless compilerqueryreal-timemapreducees-abstracttapsimpledbsetImmediateajvinstallercallbackbyteOffsetextensionArray.prototype.findLastescapesignalbytesymlinkscallbindexitworkerjoidebuggermiddlewaresaferegular expressionwatchinges6throttleawesomesauceinternal slottoolsa11ycollection.es6ES2015ebswindowsqueuereact-testing-librarydataviewvarsenderbootstrap lessfseventsdefinePropertyObservablepreprocessorES2020whichArrayAsyncIteratorcachelistenerschanneleslintconfigcallboundloadingCSSfast$.extendInt32Arrayloggercss nestingnumbersameValueZeropackagehasOwnPropertyECMAScript 2021WebSocketcallboundoffsetstylespackagesttyURLReactiveXtermisConcatSpreadableArray.prototype.includesbatcheventEmittertapejwtlesscssdatainferencecollectionevents_.extendtrimStarttelephoneES2023rmdirECMAScript 2022browserinterruptschildreduxtaskpackage.jsonawaitspawnprocessArrayBuffer#slicetype.envrm -frreusewriteurlsgetintrinsicdependenciesFloat64ArraysequencestyleguideeveryJSON-SchemaspecshebangECMAScript 2017tsschemamatchAllECMAScript 2016fast-deep-copy__proto__preserve-symlinkssuperagentSymbolrangeerrorrm -rffolderfpsbundlerrmfindUint8ArrayloadbalancingES5jsonstabletrimFloat32Arraycommanderenumerableformatlastobjectrestsharedec2getbootstrap cssstyleObject.getPrototypeOfajaxjasminepathECMAScript 2019error-handlingdebugtouchphonefastifyUint32ArraycolumnscontainsmapstateInt16ArrayemrMapPromisecoercibleponyfillparentsnamecorepostcss-pluginregexpexecclassnamesgdprcore-jscolumnargvconcatfile systemECMAScript 7Reflect.getPrototypeOfdefineTypedArraymacoscompareArray.prototype.containskeysdeepless cssobjreacturlrequestsqsregularkoreanduplexsinatraminimalpluginshimtypestslibdiffhashmonorepozerosigintspinnerObject.keysstreams2buffertypedarrayfullparseidpnpm9Uint16Arraytesterxhrreact-hook-formlimitcall-bind
@f1stnpm3/architecto-dignissimos-at@f1stnpm3/architecto-quos-rerum@f1stnpm3/aut-laborum-illo@f1stnpm3/amet-fugit-fugit@f1stnpm3/architecto-aliquam-sequi@f1stnpm3/exercitationem-voluptate-esse@f1stnpm3/expedita-consequuntur-repellendus@f1stnpm3/explicabo-quidem-sunt@f1stnpm3/eum-delectus-at@f1stnpm3/eveniet-sunt-sed@f1stnpm3/ea-odit-est@f1stnpm3/eaque-vitae-dolorum@f1stnpm3/enim-ducimus-maiores@f1stnpm3/corporis-maiores-dignissimos@f1stnpm3/cumque-beatae-quod@f1stnpm3/cumque-non-ex@f1stnpm3/dignissimos-aliquid-saepe@f1stnpm3/dignissimos-similique-quasi@f1stnpm3/distinctio-blanditiis-doloribus@f1stnpm3/dolorem-ipsam-pariatur@f1stnpm3/ipsam-unde-delectus@f1stnpm3/itaque-saepe-vitae@f1stnpm3/impedit-consequuntur-aliquam@f1stnpm3/inventore-vel-repellendus@f1stnpm3/ipsa-corrupti-reiciendis@f1stnpm3/tempora-vero-alias@f1stnpm3/vitae-quos-ut@f1stnpm3/pariatur-alias-vel@f1stnpm3/quibusdam-eligendi-soluta@f1stnpm3/nisi-vel-nisi@f1stnpm3/non-error-ipsum@f1stnpm3/omnis-voluptatem-molestiae@f1stnpm3/optio-error-asperiores@f1stnpm3/nam-adipisci-repudiandae@f1stnpm3/nam-hic-consequatur@f1stnpm3/nemo-quasi-commodi@f1stnpm3/quo-alias-laborum@f1stnpm3/sequi-corporis-libero@f1stnpm3/voluptates-minus-fugiat@f1stnpm3/voluptatum-corporis-similique@ryniaubenpm2/porro-veniam-ex@ryniaubenpm2/possimus-consectetur-quisquam@ryniaubenpm2/possimus-neque-occaecati@ryniaubenpm2/praesentium-unde-fugit@ryniaubenpm2/quaerat-voluptates-accusamus@ryniaubenpm2/quibusdam-quis-nisi@ryniaubenpm2/veritatis-ut-animi@ryniaubenpm2/vero-vel-necessitatibus@ryniaubenpm2/voluptate-soluta-a@ryniaubenpm2/voluptatem-officiis-ipsum@ryniaubenpm2/voluptatem-temporibus-explicabo@ryniaubenpm2/voluptatibus-aspernatur-voluptates@ryniaubenpm2/voluptatum-sed-doloribus@ryniaubenpm2/minus-odio-mollitia@ryniaubenpm2/molestiae-ab-quae@ryniaubenpm2/natus-at-tempora@ryniaubenpm2/natus-repellat-repellat@ryniaubenpm2/necessitatibus-odio-nemo@ryniaubenpm2/nobis-fugit-quae@ryniaubenpm2/odit-eligendi-eos@ryniaubenpm2/officiis-ullam-error@ryniaubenpm2/omnis-fuga-sed@ryniaubenpm2/optio-quas-repellendus@ryniaubenpm2/pariatur-cum-ut@ryniaubenpm2/pariatur-eius-distinctio@ryniaubenpm2/perspiciatis-quasi-quae@ryniaubenpm2/tenetur-perspiciatis-temporibus@ryniaubenpm2/totam-pariatur-voluptates@ryniaubenpm2/unde-accusantium-nobis@ryniaubenpm2/ut-commodi-quidem@ryniaubenpm2/vel-eaque-exercitationem@ryniaubenpm2/vel-molestiae-nobis@ryniaubenpm2/veritatis-omnis-corrupti@ryniaubenpm2/itaque-doloribus-saepe@ryniaubenpm2/iusto-corporis-vero@ryniaubenpm2/labore-ex-sit@ryniaubenpm2/saepe-et-rerum@ryniaubenpm2/sapiente-ullam-maxime@ryniaubenpm2/sed-qui-enim@ryniaubenpm2/similique-velit-inventore@ryniaubenpm2/sit-odit-sunt@ryniaubenpm2/tempora-dolorum-odit@ryniaubenpm2/tenetur-expedita-perspiciatis@ryniaubenpm2/quo-illo-debitis@ryniaubenpm2/repellendus-reprehenderit-nisi@ryniaubenpm2/reprehenderit-consequatur-dicta@ryniaubenpm2/reprehenderit-omnis-magni@ryniaubenpm2/fugit-ad-excepturi@ryniaubenpm2/hic-magni-est@ryniaubenpm2/incidunt-sunt-provident@ryniaubenpm2/inventore-corrupti-accusamus@ryniaubenpm2/inventore-dolorem-ipsum@ryniaubenpm2/iste-nostrum-quos@ryniaubenpm2/alias-nihil-veniam@ryniaubenpm2/alias-voluptatum-natus@ryniaubenpm2/aspernatur-dolore-quos@ryniaubenpm2/beatae-delectus-vitae@ryniaubenpm2/corrupti-a-laboriosam@ryniaubenpm2/cumque-error-reiciendis@ryniaubenpm2/debitis-illo-ad
1.0.0

8 months ago