|
| 1 | +import globalsJson from '../globals.json'; |
| 2 | +import { createRule, parseJestFnCall } 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 | + preferImportingJestGlobal: `Import the following Jest functions from '@jest/globals': {{ jestFunctions }}`, |
| 14 | + }, |
| 15 | + fixable: 'code', |
| 16 | + type: 'problem', |
| 17 | + schema: [], |
| 18 | + }, |
| 19 | + defaultOptions: [], |
| 20 | + create(context) { |
| 21 | + const jestGlobalFunctions = Object.keys(globalsJson); |
| 22 | + const importedJestFunctions: string[] = []; |
| 23 | + const usedJestFunctions = new Set<string>(); |
| 24 | + |
| 25 | + return { |
| 26 | + CallExpression(node) { |
| 27 | + const jestFnCall = parseJestFnCall(node, context); |
| 28 | + |
| 29 | + if (!jestFnCall) { |
| 30 | + return; |
| 31 | + } |
| 32 | + if ( |
| 33 | + jestFnCall.head.type === 'import' && |
| 34 | + jestGlobalFunctions.includes(jestFnCall.name) |
| 35 | + ) { |
| 36 | + importedJestFunctions.push(jestFnCall.name); |
| 37 | + } |
| 38 | + |
| 39 | + /* istanbul ignore else */ |
| 40 | + if (jestGlobalFunctions.includes(jestFnCall.name)) { |
| 41 | + usedJestFunctions.add(jestFnCall.name); |
| 42 | + } |
| 43 | + }, |
| 44 | + 'Program:exit'() { |
| 45 | + const jestFunctionsToImport = Array.from(usedJestFunctions).filter( |
| 46 | + jestFunction => !importedJestFunctions.includes(jestFunction), |
| 47 | + ); |
| 48 | + |
| 49 | + if (jestFunctionsToImport.length > 0) { |
| 50 | + const node = context.getSourceCode().ast; |
| 51 | + const jestFunctionsToImportFormatted = |
| 52 | + jestFunctionsToImport.join(', '); |
| 53 | + |
| 54 | + context.report({ |
| 55 | + node, |
| 56 | + messageId: 'preferImportingJestGlobal', |
| 57 | + data: { jestFunctions: jestFunctionsToImportFormatted }, |
| 58 | + fix(fixer) { |
| 59 | + return fixer.insertTextBefore( |
| 60 | + node, |
| 61 | + `import { ${jestFunctionsToImportFormatted} } from '@jest/globals';\n`, |
| 62 | + ); |
| 63 | + }, |
| 64 | + }); |
| 65 | + } |
| 66 | + }, |
| 67 | + }; |
| 68 | + }, |
| 69 | +}); |
0 commit comments