diff --git a/packages/babel-plugin-jest-hoist/src/__tests__/__snapshots__/hoistPlugin.test.ts.snap b/packages/babel-plugin-jest-hoist/src/__tests__/__snapshots__/hoistPlugin.test.ts.snap index a2864eca1d10..4c69eaa605c1 100644 --- a/packages/babel-plugin-jest-hoist/src/__tests__/__snapshots__/hoistPlugin.test.ts.snap +++ b/packages/babel-plugin-jest-hoist/src/__tests__/__snapshots__/hoistPlugin.test.ts.snap @@ -298,8 +298,8 @@ jest.mock('someModule', () => { ↓ ↓ ↓ ↓ ↓ ↓ _getJestObj().mock('someModule', () => { - expect(_getJestObj().mock('someNode')).toBe(1); require('x'); + expect(_getJestObj().mock('someNode')).toBe(1); }); function _getJestObj() { const {jest} = require('@jest/globals'); diff --git a/packages/babel-plugin-jest-hoist/src/index.ts b/packages/babel-plugin-jest-hoist/src/index.ts index 654e5d77563e..f0d10cb00134 100644 --- a/packages/babel-plugin-jest-hoist/src/index.ts +++ b/packages/babel-plugin-jest-hoist/src/index.ts @@ -288,7 +288,10 @@ const extractJestObjExprIfHoistable = (expr: NodePath): JestObjInfo | null => { // Important: Call the function check last // It might throw an error to display to the user, // which should only happen if we're already sure it's a call on the Jest object. - const functionIsHoistable = FUNCTIONS[propertyName]?.(args) ?? false; + const functionIsHoistable = + expr.parentPath.isExpressionStatement() && + (FUNCTIONS[propertyName]?.(args) ?? false); + let functionHasHoistableScope = functionIsHoistable; for ( let path: NodePath | null = expr;