Skip to content

Commit

Permalink
fix false negative in used globals check (#575)
Browse files Browse the repository at this point in the history
  • Loading branch information
puglyfe committed May 11, 2024
1 parent a0a0f8f commit 907545d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
26 changes: 25 additions & 1 deletion src/transformers/jest-globals-import.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ const test = () => { console.log('only a test'); };
)
})

it('removes imports', () => {
it('removes unnecessary imports', () => {
expectTransformation(
`
import '@jest/globals';
Expand All @@ -101,6 +101,30 @@ const BLAH = 5;
`.trim(),
`
const BLAH = 5;
`.trim()
)
expectTransformation(
`
import { expect } from '@jest/globals';
const BLAH = 5;
expect(BLAH).toBe(5);
`.trim(),
`
import { expect } from '@jest/globals';
const BLAH = 5;
expect(BLAH).toBe(5);
`.trim()
)
expectTransformation(
`
import '@jest/globals';
const BLAH = 5;
expect(BLAH).toBe(5);
`.trim(),
`
import { expect } from '@jest/globals';
const BLAH = 5;
expect(BLAH).toBe(5);
`.trim()
)
})
Expand Down
22 changes: 19 additions & 3 deletions src/transformers/jest-globals-import.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import type { ImportSpecifier, JSCodeshift } from 'jscodeshift'
import type {
ASTPath,
CallExpression,
ImportSpecifier,
JSCodeshift,
MemberExpression,
} from 'jscodeshift'

import { JEST_GLOBALS } from '../utils/consts'
import { findImports, removeRequireAndImport } from '../utils/imports'
Expand All @@ -12,15 +18,25 @@ const jestGlobalsImport = (

const jestGlobalsUsed = new Set<string>()

const isImplicitlyInScope = (
expression: ASTPath<CallExpression | MemberExpression>,
globalName: string
) => {
return Boolean(
expression.scope.lookup(globalName) &&
ast.find(j.ImportSpecifier, { imported: { name: globalName } }).size() === 0
)
}

JEST_GLOBALS.forEach((globalName) => {
if (
ast
.find(j.CallExpression, { callee: { name: globalName } })
.filter((callExpression) => !callExpression.scope.lookup(globalName))
.filter((callExpression) => !isImplicitlyInScope(callExpression, globalName))
.size() > 0 ||
ast
.find(j.MemberExpression, { object: { name: globalName } })
.filter((memberExpression) => !memberExpression.scope.lookup(globalName))
.filter((memberExpression) => !isImplicitlyInScope(memberExpression, globalName))
.size() > 0
) {
jestGlobalsUsed.add(globalName)
Expand Down

0 comments on commit 907545d

Please sign in to comment.