From 7ca29c572cc67403e3df91ebd7e46f074f4e6000 Mon Sep 17 00:00:00 2001 From: Jarda Snajdr Date: Tue, 28 Feb 2023 09:33:43 +0100 Subject: [PATCH] Do not hoist nested jest.mock calls, only add the getJestObj getter --- .../src/__tests__/__snapshots__/hoistPlugin.test.ts.snap | 2 +- packages/babel-plugin-jest-hoist/src/index.ts | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) 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;