Skip to content

Commit d528e1b

Browse files
committed
don't declare getJestObj if unnecessary
1 parent 9a022c1 commit d528e1b

File tree

1 file changed

+25
-13
lines changed
  • packages/babel-plugin-jest-hoist/src

1 file changed

+25
-13
lines changed

packages/babel-plugin-jest-hoist/src/index.ts

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -241,18 +241,30 @@ const extractJestObjExprIfHoistable = <T extends Node>(
241241
};
242242

243243
/* eslint-disable sort-keys,@typescript-eslint/explicit-module-boundary-types */
244-
export default (): PluginObj<{jestObjGetterIdentifier: Identifier}> => ({
244+
export default (): PluginObj<{
245+
declareJestObjGetterIdentifier: () => Identifier;
246+
jestObjGetterIdentifier?: Identifier;
247+
}> => ({
245248
pre({path: program}: {path: NodePath<Program>}) {
246-
this.jestObjGetterIdentifier = program.scope.generateUidIdentifier(
247-
'getJestObj',
248-
);
249-
program.unshiftContainer('body', [
250-
createJestObjectGetter({
251-
GETTER_NAME: this.jestObjGetterIdentifier.name,
252-
JEST_GLOBALS_MODULE_JEST_EXPORT_NAME,
253-
JEST_GLOBALS_MODULE_NAME,
254-
}),
255-
]);
249+
this.declareJestObjGetterIdentifier = () => {
250+
if (this.jestObjGetterIdentifier) {
251+
return this.jestObjGetterIdentifier;
252+
}
253+
254+
this.jestObjGetterIdentifier = program.scope.generateUidIdentifier(
255+
'getJestObj',
256+
);
257+
258+
program.unshiftContainer('body', [
259+
createJestObjectGetter({
260+
GETTER_NAME: this.jestObjGetterIdentifier.name,
261+
JEST_GLOBALS_MODULE_JEST_EXPORT_NAME,
262+
JEST_GLOBALS_MODULE_NAME,
263+
}),
264+
]);
265+
266+
return this.jestObjGetterIdentifier;
267+
};
256268
},
257269
visitor: {
258270
ExpressionStatement(exprStmt) {
@@ -261,7 +273,7 @@ export default (): PluginObj<{jestObjGetterIdentifier: Identifier}> => ({
261273
);
262274
if (jestObjExpr) {
263275
jestObjExpr.replaceWith(
264-
callExpression(this.jestObjGetterIdentifier, []),
276+
callExpression(this.declareJestObjGetterIdentifier(), []),
265277
);
266278
}
267279
},
@@ -275,7 +287,7 @@ export default (): PluginObj<{jestObjGetterIdentifier: Identifier}> => ({
275287
} = callExpr;
276288
if (
277289
isIdentifier(callee) &&
278-
callee.name === this.jestObjGetterIdentifier.name
290+
callee.name === this.jestObjGetterIdentifier?.name
279291
) {
280292
const mockStmt = callExpr.getStatementParent();
281293
const mockStmtNode = mockStmt.node;

0 commit comments

Comments
 (0)