In a Jest 30 test file, why does jest.mock(path, factory) apply before the imports above it, and what limits does that set on the factory?
answer
- the transform moves a call
- the registry answers every importer
- a naming escape hatch
- initialised before first require
basics
~20 sbabel-jest hoists jest.mock above the file's imports, so every importer gets the mock. The factory may use only its own locals, allowed globals, pure constants and names prefixed mock, and a mock-prefixed variable must be initialised before the factory first runs.
solid answer
~40 sJest's default transform, `babel-jest`, runs `babel-plugin-jest-hoist`, which moves `jest.mock` calls to the top of the file, above the `import` statements, which the transform normally compiles to `require`. The mock is registered first, so the code under test receives it when it requires the module. The factory runs lazily, the first time the module is required. Because it now sits above the file's declarations, the plugin rejects references to outer variables with "The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables", except allowed globals, constants it can prove pure and names starting with `mock`. That prefix only silences the check: if the factory runs before the variable is initialised, it is a temporal-dead-zone `ReferenceError`. For a partial mock I spread `jest.requireActual(path)` and override one export.
code
javascript · 17 linesconst { placeOrder } = require('./orderService');
const paymentClient = require('./paymentClient');
jest.mock('./paymentClient', () => ({
...jest.requireActual('./paymentClient'),
charge: jest.fn(),
}));
test('placeOrder charges through the mocked client', async () => {
paymentClient.charge.mockResolvedValueOnce({ id: 'rcpt_1' });
const result = await placeOrder({ id: 'ord_1', totalCents: 4200 });
expect(result).toEqual({ status: 'paid', receiptId: 'rcpt_1' });
expect(paymentClient.charge).toHaveBeenCalledWith('ord_1', 4200);
expect(jest.isMockFunction(paymentClient.refund)).toBe(false);
});go deeper
Know that jest.mock replaces a module for the whole test file and that its call is moved above the imports for you.
Explain the hoisting plugin, when the factory actually runs, the mock-prefix rule with its dead-zone caveat, and how jest.requireActual builds a partial mock.
Diagnose a factory that crashes at load, a mock that never applies because the module was imported in a setup file first, and a native ESM suite where hoisting cannot work.
Judge when module mocking in a file has grown into a maintenance cost and dependency injection or shared manual mocks would make the order service easier to test.
## What hoisting is A test file usually starts with its imports and only then calls `jest.mock('./paymentClient', factory)`. Read literally, the order service would already have loaded the real payment client before the mock was registered. It works anyway because of **hoisting**: Jest's default transform, `babel-jest`, injects `babel-plugin-jest-hoist`, which moves `jest.mock` calls above the rest of the file. In a test running as CommonJS, the transform normally compiles static `import` statements to `require` calls, so after the move the mock is registered before any module is loaded. Jest keeps a **module registry** per test file. Once `jest.mock` registers a path, every `require` of that path in the file, including the ones inside the order service, returns the mock. The mock does not reach other test files: each file has its own registry, and a module mocked in one file is real in the next. ## When the factory runs The factory is not called at the `jest.mock` line. It runs the **first time the module is required** in that registry, and its return value is cached and reused for later requires. In the usual layout that first require is the hoisted import of the code under test, so the factory runs before the rest of the file has executed at all. ## The out-of-scope rule Since the factory ends up above the file's own declarations, the hoisting plugin checks every identifier it uses. A factory may reference: 1. Its own parameters and the variables it declares inside itself. 2. A fixed list of globals such as `Promise`, `Error`, `Date`, `require`, `jest` and `expect`. 3. Variables whose names start with `mock`, matched case-insensitively. 4. A `const` whose initialiser the plugin can prove pure, such as a literal; it is hoisted along with the call. Anything else fails at transform time with a `ReferenceError` that reads "The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables" followed by the offending name. The `mock` prefix is an **escape hatch, not a guarantee**: if the factory runs before `const mockCharge = jest.fn()` has executed, the result is a temporal-dead-zone error, "Cannot access 'mockCharge' before initialization". Two safe patterns exist: create the mocks inside the factory and import them back, or reference the `mock` variable lazily inside a function, such as `charge: (...args) => mockCharge(...args)`. ## The shapes `jest.mock` takes | Call | Result | |---|---| | `jest.mock('./paymentClient')` | an automatic mock: every exported function becomes a `jest.fn()` returning `undefined` | | `jest.mock('./paymentClient', () => ({ charge: jest.fn() }))` | exactly what the factory returns | | factory spreading `jest.requireActual('./paymentClient')` | a **partial mock**: real exports, with chosen ones overridden | | factory returning `{ __esModule: true, default: ... }` | a mock whose default export works with `import x from` | | third argument `{ virtual: true }` | a mock for a path that does not exist on disk | After an automatic or factory mock, the test reaches the mocks through the imported module, for example `paymentClient.charge.mockResolvedValueOnce(...)`, and resets them between tests like any other mock. In TypeScript, wrapping the import in `jest.mocked(paymentClient)` gives those exports their mock typings without a cast. ## Manual mocks in `__mocks__` A **manual mock** is a hand-written module in a `__mocks__` directory: - For a user module, the file sits in `__mocks__/` next to it, as in `services/__mocks__/paymentClient.js`, and the test must still call `jest.mock('./services/paymentClient')` to use it. - For a package from `node_modules`, a `__mocks__` directory next to `node_modules` (under the configured `roots`) is applied automatically, with no `jest.mock` call. - Node's built-in modules such as `fs` are never mocked by default; even with a manual mock present, the test calls `jest.mock('fs')`. - `jest.createMockFromModule(path)` builds the automatic mock inside a manual one, so the file only overrides what it needs. Jest 30 removed the old name `jest.genMockFromModule`. ## When hoisting does not apply - **`jest.doMock`** is deliberately not hoisted. Paired with `jest.resetModules()` and a `require` inside the test, it lets each test mock the same module differently. - **Native ECMAScript modules** evaluate static imports before any code runs, so hoisting cannot help; such suites use `jest.unstable_mockModule` and a dynamic `import()` after it. - **`excludeJestPreset: true`** on `babel-jest` stops the hoisting plugin, and `jest.mock` calls must then be written above the `require` calls by hand.
- How do you give one test in a Jest file a different mock of the same module than the others?Keep one hoisted `jest.mock` and change its behaviour per test with `mockImplementation` or the value helpers on the mocked export. If the module itself must differ, call `jest.resetModules()` in `beforeEach`, then `jest.doMock(path, factory)` and `require` the code under test inside the test, because `jest.doMock` is not hoisted.
- Why does a manual mock beside a user module not take effect on its own?For user modules Jest only swaps in `__mocks__/<name>.js` when the test calls `jest.mock` for that path, or when `automock` is enabled. Only mocks for packages in `node_modules`, placed in a `__mocks__` folder next to `node_modules`, apply automatically, and even then Node built-ins such as `fs` still need an explicit `jest.mock`.
- jest.mock only works if it is written above the import statements.
- A jest.mock factory can use any variable declared in the test file.
- Naming a variable mockCharge makes it safe even if the factory runs first.
- A manual mock in __mocks__ beside a user module applies without jest.mock.
- jest.mock in one test file also mocks the module in every other file.
Assumes Jest 30, which removed jest.genMockFromModule in favour of jest.createMockFromModule; jest.mock hoisting and the factory rules predate Jest 30.