|
| 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 | + fixable: 'code', |
| 17 | + type: 'suggestion', |
| 18 | + schema: [], |
| 19 | + }, |
| 20 | + defaultOptions: [], |
| 21 | + create(context) { |
| 22 | + const jestFunctions = Object.keys(globalsJson); |
| 23 | + const importedJestFunctions: any[] = []; |
| 24 | + const usedJestFunctions = new Set(); |
| 25 | + |
| 26 | + return { |
| 27 | + ImportDeclaration(node) { |
| 28 | + // Check if the import source is '@jest/globals' |
| 29 | + if (node.source.value === '@jest/globals') { |
| 30 | + node.specifiers.forEach(specifier => { |
| 31 | + if ( |
| 32 | + specifier.type === 'ImportSpecifier' && |
| 33 | + jestFunctions.includes(specifier.imported.name) |
| 34 | + ) { |
| 35 | + importedJestFunctions.push(specifier.imported.name); |
| 36 | + } |
| 37 | + }); |
| 38 | + } |
| 39 | + }, |
| 40 | + Identifier(node) { |
| 41 | + if (jestFunctions.includes(node.name)) { |
| 42 | + usedJestFunctions.add(node.name); |
| 43 | + } |
| 44 | + }, |
| 45 | + 'Program:exit'() { |
| 46 | + usedJestFunctions.forEach(jestFunction => { |
| 47 | + if (!importedJestFunctions.includes(jestFunction)) { |
| 48 | + context.report({ |
| 49 | + node: context.getSourceCode().ast, |
| 50 | + messageId: 'preferJestGlobal', |
| 51 | + data: { jestFunction }, |
| 52 | + }); |
| 53 | + } |
| 54 | + }); |
| 55 | + }, |
| 56 | + }; |
| 57 | + }, |
| 58 | +}); |
0 commit comments