babel-plugin-jest-hoist

raw JSON →
30.3.0 verified Sat Apr 25 auth: no javascript

A Babel plugin that hoists Jest mock and unmock calls to the top of the test module scope, ensuring they execute before any imports. Version 30.3.0 is the latest stable release, part of Jest v30 series. It works alongside babel-jest and jest-runtime to allow proper mocking with ES6 modules. Key differentiator: it is specifically designed for Jest's transformation pipeline and is automatically installed as a dependency of babel-jest in Jest projects. Does not require separate configuration unless using a custom Babel setup.

error babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
cause The factory function passed to jest.mock() tries to use variables not in scope at the top of the file.
fix
Hoist required variables or use jest.mock('moduleName', () => ({})) with inline modules.
error Cannot find module 'babel-jest' from 'babel.config.js'
cause The Babel plugin is used without having babel-jest installed or configured.
fix
Install babel-jest: npm install --save-dev babel-jest @babel/core
error TypeError: jest.mock is not a function
cause The test environment doesn't have jest defined, or jest.mock is not available in custom test frameworks.
fix
Ensure the test file is run with Jest and not another test runner.
gotcha jest.mock calls must be at the top level of the test file; they cannot be inside functions or conditionals.
fix Move all jest.mock() calls to module scope, not inside describe/it blocks.
gotcha The plugin only hoists jest.mock(), jest.unmock(), and jest.enableAutomock() calls. Other jest methods like jest.doMock() are not hoisted.
fix Use jest.mock() instead of jest.doMock() if hoisting is required.
breaking Jest 28 removed automatic hoisting for CJS modules; now hoisting only works with ESM or when using babel-jest.
fix Ensure your project uses babel-jest or @jest/transform with the plugin.
npm install babel-plugin-jest-hoist
yarn add babel-plugin-jest-hoist
pnpm add babel-plugin-jest-hoist

Shows how to configure the plugin manually in a custom Babel config and how jest.mock calls get hoisted.

// This plugin is automatically used by babel-jest. Manual setup is rarely needed.
// If you have a custom Babel config (.babelrc or babel.config.js), add:
module.exports = {
  plugins: ['babel-plugin-jest-hoist']
};

// Then in your test file, you can use:
const { exec } = require('child_process');
jest.mock('child_process'); // hoisted to top

test('mock works', () => {
  exec.mockImplementation(() => {});
  expect(exec).toHaveBeenCalled();
});