Skip to content
/ jest Public
forked from jestjs/jest

Commit

Permalink
hoist within scope
Browse files Browse the repository at this point in the history
  • Loading branch information
jeysal committed Apr 26, 2020
1 parent f547d25 commit 80dabd0
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
10 changes: 8 additions & 2 deletions e2e/babel-plugin-jest-hoist/__tests__/integration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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;
Expand Down Expand Up @@ -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');
}

Expand Down
8 changes: 6 additions & 2 deletions packages/babel-plugin-jest-hoist/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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>}) {
program.traverse({
CallExpression: callExpr => {
Expand All @@ -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]);
}
}
},
});
Expand Down

0 comments on commit 80dabd0

Please sign in to comment.