Jest 11 ๐ Module Mocking โ jest.mock() and Factory Functions
jest.mock() replaces an entire module’s exports for the duration of a test file. It is hoisted to the top of the file by Jest’s Babel transform, which means it runs before the imports, and the module that the code under test imports is the mocked one. The basic call is jest.mock("./module"), which auto-mocks every export. The factory form is jest.mock("./module", () => ({ ... })), which supplies the implementation. The factory is the part that requires care: its scoping rules, its return shape, and its interaction with ES modules are the three places a test fails with an error that does not name the real cause.
This chapter covers the jest.mock() call, the factory function and its scoping constraint, and the ESM alternative that replaces the hoisting mechanism. The sections that follow walk through the auto-mock, the factory, and the jest.unstable_mockModule() path for a native ESM project.
Key point: jest.mock("./module") is hoisted above the imports and replaces the module with an auto-mock; the factory form supplies the implementation, the factory must be self-contained (no out-of-scope variables) unless they are prefixed with mock, and in an ESM project the hoisting does not work, so jest.unstable_mockModule() with a dynamic import is the replacement.
a. The auto-mock and the hoisting
jest.mock("./module") replaces the module with an auto-mock. Every exported function becomes a mock that returns undefined, and every exported class becomes a mock constructor. The call is hoisted above the imports, so the module is already mocked when the code under test imports it .
// The auto-mock
jest.mock("./api");
import { fetchUser } from "./api";
test("auto-mock returns undefined", async () => {
const user = await fetchUser("1");
expect(user).toBeUndefined();
expect(fetchUser).toHaveBeenCalledWith("1");
});
The hoisting is the reason the jest.mock call can appear after the import in the source and still run before it. Jest’s Babel transform moves the call to the top of the file, so the module registry has the mock before the import statement evaluates . This is the CommonJS behavior, and it is the behavior that the factory’s scoping rules depend on.
The manual mock in a __mocks__ directory is the other form. A file at __mocks__/api.js adjacent to the module is used when jest.mock("./api") is called, and a Node module’s mock in the root __mocks__ directory is used automatically without the call . The manual mock is the pattern for a mock that is shared across test files.
b. The factory function and the scoping constraint
The factory function returns the module’s replacement. It must be self-contained: it cannot reference variables from the outer scope unless the variable name is prefixed with mock. The rule exists because the factory is hoisted with the jest.mock call, and the outer variable is not initialized at the time the factory runs.
// WRONG: the factory references an outer variable
const mockFn = jest.fn();
jest.mock("./api", () => ({ fetchUser: mockFn }));
// Error: The module factory of jest.mock() is not allowed to
// reference any out-of-scope variables.
// RIGHT: the variable is prefixed with "mock"
const mockFetchUser = jest.fn();
jest.mock("./api", () => ({ fetchUser: mockFetchUser }));
The mock prefix is the escape hatch. Jest’s Babel plugin allows a variable whose name starts with mock to be referenced inside the factory, because the naming convention signals that the variable is part of the mock setup . The mockFetchUser variable is initialized before the test body runs, and the factory’s reference resolves to it.
The factory’s return shape is the module’s export shape. A module with named exports returns an object with those names; a module with a default export returns an object with a default key. A factory that returns the default export directlyโ() => () => "mocked"โis the shape for a module whose default is a function, and a factory that returns an object is the shape for a module with named exports.
// Named exports
jest.mock("./api", () => ({
fetchUser: jest.fn(),
fetchPosts: jest.fn(),
}));
// Default export that is a function
jest.mock("./logger", () => jest.fn());
// Default export that is an object
jest.mock("./config", () => ({ default: { debug: true } }));
The class mock is the case that trips people up. A module that exports a class must be mocked with a function that can be called with new, which means the factory must return a regular function rather than an arrow function . The jest.fn().mockImplementation(() => ({ ... })) form returns a mock function that can be called with new, and the returned object is the instance.
jest.mock("./sound-player", () => {
return jest.fn().mockImplementation(() => ({
playSoundFile: jest.fn(),
}));
});
c. The ESM alternative and jest.unstable_mockModule
The hoisting is a Babel/CommonJS mechanism. In a native ESM project, the static imports are evaluated before any statement in the file runs, so jest.mock() cannot be hoisted above them, and the call has no effect on the already-imported module . The replacement is jest.unstable_mockModule(path, factory) with a dynamic await import() of the module under test.
// ESM: no hoisting, so the mock must be registered first
jest.unstable_mockModule("./api", () => ({
fetchUser: jest.fn().mockResolvedValue({ id: "1" }),
}));
const { fetchUser } = await import("./api");
const { createUser } = await import("./user-service");
The unstable_mockModule is not hoisted, and the await import() is the explicit sequencing. The mock is registered before the dynamic import of the module under test, and the module under test receives the mocked dependency . The --experimental-vm-modules flag is required for the native ESM support, and the unstable_ prefix is the signal that the API is not final.
The ESM project that does not want the experimental flag has the option of using Vitest, which is the Vite-native runner with a Jest-compatible API and native ESM support. Jest’s own documentation describes the native ESM support as experimental, and the community guidance for a new Vite or ESM project is Vitest .
The jest.mocked() helper is the type-level companion in both module systems. It casts the imported module to its mocked type, so the mock methods (mockResolvedValue, mockReturnValue) are available without a type assertion.
import { fetchUser } from "./api";
jest.mock("./api");
const mockedFetchUser = jest.mocked(fetchUser);
mockedFetchUser.mockResolvedValue({ id: "1" });
The jest.mocked() is the recommended form in a TypeScript project. Without it, the imported function has its original type, and the mock methods are a type error.
Complete Example Session
// ============================================
// PART 1: THE AUTO-MOCK
// ============================================
// src/api.js
export async function fetchUser(id) {
const res = await fetch(`/api/users/${id}`);
return res.json();
}
// src/api.test.js
import { fetchUser } from "./api";
jest.mock("./api"); // hoisted above the import
test("auto-mock", async () => {
const user = await fetchUser("1");
expect(user).toBeUndefined();
});
// ============================================
// PART 2: THE FACTORY
// ============================================
jest.mock("./api", () => ({
fetchUser: jest.fn().mockResolvedValue({ id: "1", name: "Ana" }),
}));
// ============================================
// PART 3: THE MOCK-PREFIXED VARIABLE
// ============================================
const mockFetchUser = jest.fn().mockResolvedValue({ id: "1" });
jest.mock("./api", () => ({ fetchUser: mockFetchUser }));
// ============================================
// PART 4: THE CLASS MOCK
// ============================================
jest.mock("./sound-player", () => {
return jest.fn().mockImplementation(() => ({
playSoundFile: jest.fn(),
}));
});
// ============================================
// PART 5: THE ESM ALTERNATIVE
// ============================================
// ESM project with --experimental-vm-modules
jest.unstable_mockModule("./api", () => ({
fetchUser: jest.fn().mockResolvedValue({ id: "1" }),
}));
const { fetchUser } = await import("./api");
The parts covered the auto-mock, the factory, the mock-prefixed variable, the class mock, and the ESM alternative.
Quick Reference
Mock API
| Call | Effect |
|---|---|
jest.mock("./module") | Auto-mock the module |
jest.mock("./module", factory) | Replace with factory |
jest.mocked(fn) | Type-cast to mocked |
jest.unstable_mockModule(path, factory) | ESM module mock |
Factory Rules
| Rule | Detail |
|---|---|
| Self-contained | No out-of-scope variables |
| Exception | Variables prefixed with mock |
| Named exports | Return an object |
| Default export | Return { default: ... } |
| Class mock | Return a function (not arrow) |
Manual Mocks
| Location | When Used |
|---|---|
__mocks__/module.js | On jest.mock("./module") |
Root __mocks__/node-module.js | Automatically for Node modules |
jest.createMockFromModule | Extend the auto-mock |
Best Practices
โ Do This:
// Use the mock prefix for factory variables
const mockFetchUser = jest.fn();
jest.mock("./api", () => ({ fetchUser: mockFetchUser })); // โ
// Return the named export shape
jest.mock("./api", () => ({ fetchUser: jest.fn() })); // โ
// Use jest.mocked for type safety
jest.mocked(fetchUser).mockResolvedValue({ id: "1" }); // โ
โ Don’t Do This:
// Reference an out-of-scope variable in the factory
const mockFn = jest.fn();
jest.mock("./api", () => ({ fetchUser: mockFn })); // error // โ
// Return the default export directly for named exports
jest.mock("./api", () => () => "mocked"); // wrong shape // โ
// Use jest.mock in an ESM project
jest.mock("./api"); // not hoisted, no effect // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| “not allowed to reference any out-of-scope variables” | Factory references an outer variable | Prefix it with mock |
Class mock fails with new | Factory returns an object or arrow | Return a function via jest.fn().mockImplementation |
jest.mock has no effect in ESM | No hoisting | Use jest.unstable_mockModule |
| Mock methods are a type error | No jest.mocked() | Cast the import |
Real-World Examples
1. Auto-mock
jest.mock("./api");
2. Factory
jest.mock("./api", () => ({ fetchUser: jest.fn() }));
3. Prefixed variable
const mockFetch = jest.fn();
jest.mock("./api", () => ({ fetchUser: mockFetch }));
4. Class mock
jest.mock("./player", () => jest.fn().mockImplementation(() => ({ play: jest.fn() })));
5. Default export
jest.mock("./config", () => ({ default: { debug: true } }));
6. jest.mocked
jest.mocked(fetchUser).mockResolvedValue({ id: "1" });
7. ESM mock
jest.unstable_mockModule("./api", () => ({ fetchUser: jest.fn() }));
8. Manual mock
__mocks__/api.js + jest.mock("./api")
9. Extend the auto-mock
const mock = jest.createMockFromModule("./api");
mock.fetchUser = jest.fn();
10. Partial mock
jest.mock("./api", () => ({
...jest.requireActual("./api"),
fetchUser: jest.fn(),
}));
Visual
The Hoisting
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Source order Execution order โ
โ import { fetchUser } from "..." jest.mock(...) โ
โ jest.mock("./api") import ... โ
โ โ
โ The Babel transform hoists jest.mock above the import. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Factory Scope
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ const mockFn = jest.fn(); โ
โ jest.mock("./api", () => ({ fetchUser: mockFn })) โ
โ โ โ
โ โผ โ
โ Hoisted factory runs before `const mockFn` โ
โ โ โ
โ โผ โ
โ Error: out-of-scope variable โ
โ โ
โ Fix: prefix with "mock" โ const mockFn = ... โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Class Mock
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ jest.mock("./player", () => โ
โ jest.fn().mockImplementation(() => ({ play: jest.fn() }))โ
โ ); โ
โ โ
โ The factory returns a function that can be called โ
โ with `new`. An arrow function cannot. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
ESM vs CJS
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CJS (hoisted) ESM (not hoisted) โ
โ jest.mock("./api") jest.unstable_mockModuleโ
โ import { fetchUser } const { fetchUser } โ
โ = await import("./api")โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Auto-mock | jest.mock("./module") |
| Factory | jest.mock("./module", () => ({ ... })) |
| Factory scope | Self-contained, mock-prefixed variables allowed |
| Class mock | Return a function, not an arrow |
| Type cast | jest.mocked(fn) |
| ESM mock | jest.unstable_mockModule() |
| Manual mock | __mocks__/module.js |
Key takeaways:
jest.mock()is hoisted above the imports. The call replaces the module with an auto-mock before the code under test imports it, which is why the call can appear after the import in the source and still work .- The factory must be self-contained. It cannot reference an out-of-scope variable unless the variable name is prefixed with
mock, because the factory runs before the outer variables are initialized . - The factory’s return shape is the module’s export shape. A module with named exports returns an object; a module with a default export returns
{ default: ... }; a class export returns a function that can be called withnew. - ESM breaks the hoisting. The static imports are evaluated before any statement, so
jest.mock()has no effect.jest.unstable_mockModule()with a dynamicawait import()is the replacement, and it requires the experimental VM modules flag . jest.mocked()is the type-level companion. It casts the imported module to its mocked type, so the mock methods are available without a type assertion in a TypeScript project.
Remember: Module mocking replaces the whole module, and the factory is the replacement. The hoisting is the constraint: the factory runs before the file’s own declarations, so any variable it uses must be prefixed with mock. The shape of the returned object is the module’s shape; a missing export is an import that fails. In an ESM project, the hoisting does not exist, and jest.unstable_mockModule with a dynamic import is the path.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!