Skip to content

Commit

Permalink
feat: prefer importing jest globals [new rule]
Browse files Browse the repository at this point in the history
- Fix #1101

Issue: #1101
  • Loading branch information
MadeinFrance committed Jan 17, 2024
1 parent 505258c commit 93157b0
Show file tree
Hide file tree
Showing 6 changed files with 142 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@ set to warn in.\
| [prefer-expect-resolves](docs/rules/prefer-expect-resolves.md) | Prefer `await expect(...).resolves` over `expect(await ...)` syntax | | | 🔧 | | |
| [prefer-hooks-in-order](docs/rules/prefer-hooks-in-order.md) | Prefer having hooks in a consistent order | | | | | |
| [prefer-hooks-on-top](docs/rules/prefer-hooks-on-top.md) | Suggest having hooks before any test cases | | | | | |
| [prefer-jest-globals](docs/rules/prefer-jest-globals.md) | Prefer importing Jest globals | | | | | |
| [prefer-lowercase-title](docs/rules/prefer-lowercase-title.md) | Enforce lowercase test names | | | 🔧 | | |
| [prefer-mock-promise-shorthand](docs/rules/prefer-mock-promise-shorthand.md) | Prefer mock resolved/rejected shorthands for promises | | | 🔧 | | |
| [prefer-snapshot-hint](docs/rules/prefer-snapshot-hint.md) | Prefer including a hint with external snapshots | | | | | |
Expand Down
44 changes: 44 additions & 0 deletions docs/rules/prefer-jest-globals.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Prefer importing Jest globals (`prefer-jest-globals`)

<!-- end auto-generated rule header -->

This rule aims to enforce explicit imports from `@jest/globals`.

1. This is useful for ensuring that the Jest APIs are imported the same way in
the codebase.
2. When you can't modify Jest's
[`injectGlobals`](https://jestjs.io/docs/configuration#injectglobals-boolean)
configuration property, this rule can help to ensure that the Jest globals
are imported explicitly and facilitate a migration to `@jest/globals`.

## Rule details

Examples of **incorrect** code for this rule

```js
/* eslint jest/prefer-jest-globals: "error" */

describe('foo', () => {
it('accepts this input', () => {
// ...
});
});
```

Examples of **correct** code for this rule

```js
/* eslint jest/prefer-jest-globals: "error" */

import { describe, it } from '@jest/globals';

describe('foo', () => {
it('accepts this input', () => {
// ...
});
});
```

## Further Reading

- [Documentation](https://jestjs.io/docs/api)
1 change: 1 addition & 0 deletions src/__tests__/__snapshots__/rules.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ exports[`rules should export configs that refer to actual rules 1`] = `
"jest/prefer-expect-resolves": "error",
"jest/prefer-hooks-in-order": "error",
"jest/prefer-hooks-on-top": "error",
"jest/prefer-jest-globals": "error",
"jest/prefer-lowercase-title": "error",
"jest/prefer-mock-promise-shorthand": "error",
"jest/prefer-snapshot-hint": "error",
Expand Down
2 changes: 1 addition & 1 deletion src/__tests__/rules.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { existsSync } from 'fs';
import { resolve } from 'path';
import plugin from '../';

const numberOfRules = 53;
const numberOfRules = 54;
const ruleNames = Object.keys(plugin.rules);
const deprecatedRules = Object.entries(plugin.rules)
.filter(([, rule]) => rule.meta.deprecated)
Expand Down
36 changes: 36 additions & 0 deletions src/rules/__tests__/prefer-jest-globals.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { TSESLint } from '@typescript-eslint/utils';
import dedent from 'dedent';
import rule from '../prefer-jest-globals';
import { espreeParser } from './test-utils';

const ruleTester = new TSESLint.RuleTester({
parser: espreeParser,
parserOptions: {
ecmaVersion: 2015,
sourceType: 'module',
},
});

ruleTester.run('prefer-jest-globals.test', rule, {
valid: [
{
code: dedent`
import { test, expect } from '@jest/globals';
test('should pass', () => {
expect(true).toBeDefined();
});
`,
parserOptions: { sourceType: 'module' },
},
],
invalid: [
{
code: dedent`
it("foo");
`,
parserOptions: { sourceType: 'module' },
errors: [{ endColumn: 11, column: 1, messageId: 'preferJestGlobal' }],
},
],
});
59 changes: 59 additions & 0 deletions src/rules/prefer-jest-globals.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import globalsJson from '../globals.json';
import { createRule } from './utils';

export default createRule({
name: __filename,
meta: {
docs: {
category: 'Best Practices',
description: 'Prefer importing Jest globals',
recommended: false,
},
messages: {
preferJestGlobal:
"Jest function \"{{ jestFunction }} is used but not imported from '@jest/globals'",
},
type: 'problem',
schema: [],
},
defaultOptions: [],
create(context) {
const jestFunctions = Object.keys(globalsJson);
const importedJestFunctions: any[] = [];
const usedJestFunctions = new Set();

return {
ImportDeclaration(node) {
// Check if the import source is '@jest/globals'
/* istanbul ignore else */
if (node.source.value === '@jest/globals') {
node.specifiers.forEach(specifier => {
/* istanbul ignore else */
if (
specifier.type === 'ImportSpecifier' &&
jestFunctions.includes(specifier.imported.name)
) {
importedJestFunctions.push(specifier.imported.name);
}
});
}
},
Identifier(node) {
if (jestFunctions.includes(node.name)) {
usedJestFunctions.add(node.name);
}
},
'Program:exit'() {
usedJestFunctions.forEach(jestFunction => {
if (!importedJestFunctions.includes(jestFunction)) {
context.report({
node: context.getSourceCode().ast,
messageId: 'preferJestGlobal',
data: { jestFunction },
});
}
});
},
};
},
});

0 comments on commit 93157b0

Please sign in to comment.