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 227860db32e3..3255331311b5 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 @@ -15,7 +15,7 @@ _getJestObj().mock("./App", () => () => void 0, false, { - fileName: "/root/project/src/file.js", + fileName: _hoistedMockFactoryVariable(), lineNumber: 1, columnNumber: 32 }, @@ -34,6 +34,10 @@ function _getJestObj() { return jest; } +function _hoistedMockFactoryVariable() { + return "/root/project/src/file.js"; +} + `; diff --git a/packages/babel-plugin-jest-hoist/src/index.ts b/packages/babel-plugin-jest-hoist/src/index.ts index f952746674e6..7ecafb8847da 100644 --- a/packages/babel-plugin-jest-hoist/src/index.ts +++ b/packages/babel-plugin-jest-hoist/src/index.ts @@ -146,8 +146,19 @@ FUNCTIONS.mock = args => { const initNode = binding.path.node.init; if (initNode && binding.constant && scope.isPure(initNode, true)) { - // replace the reference with its constant value - id.replaceWith(initNode); + const identifier = scope.generateUidIdentifier( + 'hoistedMockFactoryVariable', + ); + + binding.path.parentPath.insertAfter( + createHoistedVariable({ + HOISTED_NAME: identifier, + HOISTED_VALUE: binding.path.node.init, + }), + ); + + // replace reference with a call to the new function + id.replaceWith(callExpression(identifier, [])); isAllowedIdentifier = true; } @@ -191,6 +202,12 @@ function GETTER_NAME() { } `; +const createHoistedVariable = statement` +function HOISTED_NAME() { + return HOISTED_VALUE; +} +`; + const isJestObject = (expression: NodePath): boolean => { // global if (