From 80dabd03b1bd668ab7259d57f635966b6ac7cf87 Mon Sep 17 00:00:00 2001 From: Tim Seckinger Date: Sun, 26 Apr 2020 20:33:12 +0200 Subject: [PATCH] hoist within scope --- .../__tests__/integration.test.js | 10 ++++++++-- packages/babel-plugin-jest-hoist/src/index.ts | 8 ++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/e2e/babel-plugin-jest-hoist/__tests__/integration.test.js b/e2e/babel-plugin-jest-hoist/__tests__/integration.test.js index 89663520d417..3e3dd10de3e2 100644 --- a/e2e/babel-plugin-jest-hoist/__tests__/integration.test.js +++ b/e2e/babel-plugin-jest-hoist/__tests__/integration.test.js @@ -15,7 +15,6 @@ import a from '../__test_modules__/a'; import b from '../__test_modules__/b'; import c from '../__test_modules__/c'; import d from '../__test_modules__/d'; -import e from '../__test_modules__/e'; import f from '../__test_modules__/f'; import jestBackticks from '../__test_modules__/jestBackticks'; @@ -26,9 +25,15 @@ const virtualModule = require('virtual-module'); jest.unmock('react'); jest.deepUnmock('../__test_modules__/Unmocked'); jest.unmock('../__test_modules__/c').unmock('../__test_modules__/d'); + +let e; (function () { + const _getJestObj = 42; + e = require('../__test_modules__/e').default; + // hoisted to the top of the function scope jest.unmock('../__test_modules__/e'); -}); +})(); + jest.mock('../__test_modules__/f', () => { if (!global.CALLS) { global.CALLS = 0; @@ -60,6 +65,7 @@ jest.unmock('../__test_modules__/' + 'a'); jest.dontMock('../__test_modules__/Mocked'); { const jest = {unmock: () => {}}; + // Would error (used before initialization) if hoisted to the top of the scope jest.unmock('../__test_modules__/a'); } diff --git a/packages/babel-plugin-jest-hoist/src/index.ts b/packages/babel-plugin-jest-hoist/src/index.ts index 282c37259d67..9af2f8413d55 100644 --- a/packages/babel-plugin-jest-hoist/src/index.ts +++ b/packages/babel-plugin-jest-hoist/src/index.ts @@ -266,6 +266,7 @@ export default (): PluginObj<{jestObjGetterIdentifier: Identifier}> => ({ } }, }, + // in `post` to make sure we come after an import transform and can unshift above the `require`s post({path: program}: {path: NodePath}) { program.traverse({ CallExpression: callExpr => { @@ -278,8 +279,11 @@ export default (): PluginObj<{jestObjGetterIdentifier: Identifier}> => ({ ) { const mockStmt = callExpr.getStatementParent(); const mockStmtNode = mockStmt.node; - mockStmt.remove(); - program.unshiftContainer('body', [mockStmtNode]); + const mockStmtParent = mockStmt.parentPath; + if (mockStmtParent.isBlock()) { + mockStmt.remove(); + mockStmtParent.unshiftContainer('body', [mockStmtNode]); + } } }, });