Skip to content

[Bug]: babel-plugin-jest-hoist hoists entire braceless if statement above its condition #16538

Open

Description

@trackoor

Version

30.5.2 (babel-plugin-jest-hoist 30.5.0)

Steps to reproduce

Minimal reproduction: https://gist.github.com/trackoor/b622a07b0e610034386c9afef4261d93

  1. Install @babel/core and babel-plugin-jest-hoist (or [email protected]).
  2. Run the following script with node repro.js:
const babel = require('@babel/core');
const jestHoist = require('babel-plugin-jest-hoist');

const {code} = babel.transformSync(
  `
const useMock = true;
if (useMock) jest.mock('./dep');
`,
  {plugins: [jestHoist]},
);
console.log(code);

Expected behavior

The if (useMock) statement remains in place after const useMock = true (matching the braced form if (useMock) { jest.mock('./dep'); }), or only the jest.mock() call is hoisted while preserving valid control flow.

Actual behavior

babel-plugin-jest-hoist hoists the entire IfStatement to the top of the enclosing block above const useMock = true:

if (useMock) _getJestObj().mock('./dep');
function _getJestObj() {
  const {
    jest
  } = require("@jest/globals");
  _getJestObj = () => jest;
  return jest;
}
const useMock = true;

Running this in Jest throws ReferenceError: Cannot access 'useMock' before initialization (or evaluates useMock as undefined with var), whereas the braced form if (useMock) { jest.mock('./dep'); } leaves the if statement in place after const useMock = true.

Additional context

callExpr.getStatementParent() returns the nearest ancestor in a statement list, which for a braceless if consequent (or else, while, or for body) is the enclosing control-flow statement rather than the ExpressionStatement.

Credit: https://ucsbplse.github.io/

Environment

System:
  OS: macOS 26.3
  CPU: (14) arm64 Apple M3 Max
Binaries:
  Node: 24.14.1 - ~/.nvm/versions/node/v24.14.1/bin/node
  npm: 11.11.0 - ~/.nvm/versions/node/v24.14.1/bin/npm
npmPackages:
  babel-plugin-jest-hoist: 30.5.0 => 30.5.0
  jest: 30.5.2 => 30.5.2

Activity

  1. changed the title [-]babel-plugin-jest-hoist hoists entire braceless if statement above its condition[/-] [+][Bug]: babel-plugin-jest-hoist hoists entire braceless if statement above its condition[/+] on Nov 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions