Skip to content

Commit 93157b0

Browse files
committed
feat: prefer importing jest globals [new rule]
- Fix jest-community#1101 Issue: jest-community#1101
1 parent 505258c commit 93157b0

File tree

6 files changed

+142
-1
lines changed

6 files changed

+142
-1
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,7 @@ set to warn in.\
248248
| [prefer-expect-resolves](docs/rules/prefer-expect-resolves.md) | Prefer `await expect(...).resolves` over `expect(await ...)` syntax | | | 🔧 | | |
249249
| [prefer-hooks-in-order](docs/rules/prefer-hooks-in-order.md) | Prefer having hooks in a consistent order | | | | | |
250250
| [prefer-hooks-on-top](docs/rules/prefer-hooks-on-top.md) | Suggest having hooks before any test cases | | | | | |
251+
| [prefer-jest-globals](docs/rules/prefer-jest-globals.md) | Prefer importing Jest globals | | | | | |
251252
| [prefer-lowercase-title](docs/rules/prefer-lowercase-title.md) | Enforce lowercase test names | | | 🔧 | | |
252253
| [prefer-mock-promise-shorthand](docs/rules/prefer-mock-promise-shorthand.md) | Prefer mock resolved/rejected shorthands for promises | | | 🔧 | | |
253254
| [prefer-snapshot-hint](docs/rules/prefer-snapshot-hint.md) | Prefer including a hint with external snapshots | | | | | |

docs/rules/prefer-jest-globals.md

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Prefer importing Jest globals (`prefer-jest-globals`)
2+
3+
<!-- end auto-generated rule header -->
4+
5+
This rule aims to enforce explicit imports from `@jest/globals`.
6+
7+
1. This is useful for ensuring that the Jest APIs are imported the same way in
8+
the codebase.
9+
2. When you can't modify Jest's
10+
[`injectGlobals`](https://jestjs.io/docs/configuration#injectglobals-boolean)
11+
configuration property, this rule can help to ensure that the Jest globals
12+
are imported explicitly and facilitate a migration to `@jest/globals`.
13+
14+
## Rule details
15+
16+
Examples of **incorrect** code for this rule
17+
18+
```js
19+
/* eslint jest/prefer-jest-globals: "error" */
20+
21+
describe('foo', () => {
22+
it('accepts this input', () => {
23+
// ...
24+
});
25+
});
26+
```
27+
28+
Examples of **correct** code for this rule
29+
30+
```js
31+
/* eslint jest/prefer-jest-globals: "error" */
32+
33+
import { describe, it } from '@jest/globals';
34+
35+
describe('foo', () => {
36+
it('accepts this input', () => {
37+
// ...
38+
});
39+
});
40+
```
41+
42+
## Further Reading
43+
44+
- [Documentation](https://jestjs.io/docs/api)

src/__tests__/__snapshots__/rules.test.ts.snap

+1
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ exports[`rules should export configs that refer to actual rules 1`] = `
4545
"jest/prefer-expect-resolves": "error",
4646
"jest/prefer-hooks-in-order": "error",
4747
"jest/prefer-hooks-on-top": "error",
48+
"jest/prefer-jest-globals": "error",
4849
"jest/prefer-lowercase-title": "error",
4950
"jest/prefer-mock-promise-shorthand": "error",
5051
"jest/prefer-snapshot-hint": "error",

src/__tests__/rules.test.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { existsSync } from 'fs';
22
import { resolve } from 'path';
33
import plugin from '../';
44

5-
const numberOfRules = 53;
5+
const numberOfRules = 54;
66
const ruleNames = Object.keys(plugin.rules);
77
const deprecatedRules = Object.entries(plugin.rules)
88
.filter(([, rule]) => rule.meta.deprecated)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { TSESLint } from '@typescript-eslint/utils';
2+
import dedent from 'dedent';
3+
import rule from '../prefer-jest-globals';
4+
import { espreeParser } from './test-utils';
5+
6+
const ruleTester = new TSESLint.RuleTester({
7+
parser: espreeParser,
8+
parserOptions: {
9+
ecmaVersion: 2015,
10+
sourceType: 'module',
11+
},
12+
});
13+
14+
ruleTester.run('prefer-jest-globals.test', rule, {
15+
valid: [
16+
{
17+
code: dedent`
18+
import { test, expect } from '@jest/globals';
19+
20+
test('should pass', () => {
21+
expect(true).toBeDefined();
22+
});
23+
`,
24+
parserOptions: { sourceType: 'module' },
25+
},
26+
],
27+
invalid: [
28+
{
29+
code: dedent`
30+
it("foo");
31+
`,
32+
parserOptions: { sourceType: 'module' },
33+
errors: [{ endColumn: 11, column: 1, messageId: 'preferJestGlobal' }],
34+
},
35+
],
36+
});

src/rules/prefer-jest-globals.ts

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import globalsJson from '../globals.json';
2+
import { createRule } from './utils';
3+
4+
export default createRule({
5+
name: __filename,
6+
meta: {
7+
docs: {
8+
category: 'Best Practices',
9+
description: 'Prefer importing Jest globals',
10+
recommended: false,
11+
},
12+
messages: {
13+
preferJestGlobal:
14+
"Jest function \"{{ jestFunction }} is used but not imported from '@jest/globals'",
15+
},
16+
type: 'problem',
17+
schema: [],
18+
},
19+
defaultOptions: [],
20+
create(context) {
21+
const jestFunctions = Object.keys(globalsJson);
22+
const importedJestFunctions: any[] = [];
23+
const usedJestFunctions = new Set();
24+
25+
return {
26+
ImportDeclaration(node) {
27+
// Check if the import source is '@jest/globals'
28+
/* istanbul ignore else */
29+
if (node.source.value === '@jest/globals') {
30+
node.specifiers.forEach(specifier => {
31+
/* istanbul ignore else */
32+
if (
33+
specifier.type === 'ImportSpecifier' &&
34+
jestFunctions.includes(specifier.imported.name)
35+
) {
36+
importedJestFunctions.push(specifier.imported.name);
37+
}
38+
});
39+
}
40+
},
41+
Identifier(node) {
42+
if (jestFunctions.includes(node.name)) {
43+
usedJestFunctions.add(node.name);
44+
}
45+
},
46+
'Program:exit'() {
47+
usedJestFunctions.forEach(jestFunction => {
48+
if (!importedJestFunctions.includes(jestFunction)) {
49+
context.report({
50+
node: context.getSourceCode().ast,
51+
messageId: 'preferJestGlobal',
52+
data: { jestFunction },
53+
});
54+
}
55+
});
56+
},
57+
};
58+
},
59+
});

0 commit comments

Comments
 (0)