| | |

Jest 11 ๐Ÿƒ Module Mocking โ€” jest.mock() and Factory Functions

โฑ๏ธ Estimated read: 10 min | |

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

CallEffect
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

RuleDetail
Self-containedNo out-of-scope variables
ExceptionVariables prefixed with mock
Named exportsReturn an object
Default exportReturn { default: ... }
Class mockReturn a function (not arrow)

Manual Mocks

LocationWhen Used
__mocks__/module.jsOn jest.mock("./module")
Root __mocks__/node-module.jsAutomatically for Node modules
jest.createMockFromModuleExtend 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

PitfallWhy It HappensFix
“not allowed to reference any out-of-scope variables”Factory references an outer variablePrefix it with mock
Class mock fails with newFactory returns an object or arrowReturn a function via jest.fn().mockImplementation
jest.mock has no effect in ESMNo hoistingUse jest.unstable_mockModule
Mock methods are a type errorNo 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

ItemValue
Auto-mockjest.mock("./module")
Factoryjest.mock("./module", () => ({ ... }))
Factory scopeSelf-contained, mock-prefixed variables allowed
Class mockReturn a function, not an arrow
Type castjest.mocked(fn)
ESM mockjest.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 with new .
  • ESM breaks the hoisting. The static imports are evaluated before any statement, so jest.mock() has no effect. jest.unstable_mockModule() with a dynamic await 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.

Was this helpful?


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!