Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 30 ยท Mocking

Mocking Modules

Replace whole modules in Jest with jest.mock: automock vs factory, hoisting, partial mocks with requireActual, ESM caveats, and dependency injection as a simpler alternative.

Spying works when the code under test calls a method on an object it can reach. But much real code pulls its helpers in with require or import: a payment client, a database module, a file that sends email. The test cannot reach inside to swap anything. It needs a way to say: "whenever any file asks for this module, give it this replacement instead."

That is what jest.mock("./path") does. Jest controls the module system when it runs your tests, so it can substitute a different module for the real one. In this lesson you will learn the three flavors of module mocks (automock, factory, partial), why jest.mock calls appear to run before your imports, what changes with ES modules, and when it is simpler to skip module mocking altogether and inject the dependency.

Module mocking needs Jest's module loader, so the Jest code in this lesson is read-only. The runnable parts are stand-ins: a tiny module registry that mimics how a module can be swapped, and dependency injection in plain Node.js. Each is labelled.

Three flavors of module mock

Automock jest.mock(path) with no factory.
Factory You return the replacement module yourself.
Partial Keep some real exports, fake the rest.

Pick the smallest replacement that makes the test reliable.

1 / 2

The code we want to test

Suppose src/notify.js sends a welcome message through a separate mailer module:

JavaScript
// src/mailer.js
exports.send = async function send(to, subject, body) {
  // talks to a real SMTP server
};

exports.isValid = function isValid(address) {
  return /^[^@\s]+@[^@\s]+$/.test(address);
};
JavaScript
// src/notify.js
const mailer = require("./mailer");

async function welcome(user) {
  if (!mailer.isValid(user.email)) {
    return false;
  }
  await mailer.send(user.email, "Welcome", `Hi ${user.name}`);
  return true;
}

module.exports = { welcome };

We never want a test to touch SMTP. We want to replace ./mailer for the whole test file.

Automock: jest.mock(path)

The shortest form lets Jest generate the replacement:

JavaScript
const mailer = require("./mailer");
const { welcome } = require("./notify");

jest.mock("./mailer");

test("welcome sends one email", async () => {
  mailer.isValid.mockReturnValue(true);
  mailer.send.mockResolvedValue();

  const ok = await welcome({ name: "Ada", email: "[email protected]" });

  expect(ok).toBe(true);
  expect(mailer.send).toHaveBeenCalledWith("[email protected]", "Welcome", "Hi Ada");
});

With automock, Jest loads the real module once to learn its shape, then returns an object with the same exports where every function is replaced by jest.fn() that returns undefined. Classes get mocked constructors and methods. Constants and plain values are kept or emptied depending on their type. You then program each function with mockReturnValue and friends, as in Mock Functions with jest.fn.

Automock is quick, but it hides what the replacement does. If you forget mockReturnValue(true) on isValid, it returns undefined, the check fails, and the test fails for a confusing reason.

Factory: you decide what the module is

Pass a second argument, a function that returns the module:

JavaScript
jest.mock("./mailer", () => ({
  isValid: jest.fn(() => true),
  send: jest.fn().mockResolvedValue(undefined),
}));

A factory is explicit. The reader sees exactly which exports exist and what they return by default. It also avoids loading the real module at all, which matters when merely importing it has side effects such as opening a connection.

Hoisting: why the order looks wrong

You will notice that jest.mock calls often sit below the require lines, yet they still work. That is because the Babel transform that Jest applies (babel-plugin-jest-hoist) moves jest.mock calls to the top of the file before anything else runs. Without that, require("./notify") would load the real mailer before the mock was registered.

Hoisting has one trap. The factory function runs later, when the module is first required, but the jest.mock call itself is moved above your variable declarations. So a factory cannot use a variable declared in the test file, unless the variable name starts with mock:

JavaScript
const mockSend = jest.fn();          // allowed: name starts with "mock"

jest.mock("./mailer", () => ({
  send: mockSend,
}));

Jest only allows factories to reference out-of-scope variables whose names start with mock (case-insensitive), as a reminder that you are responsible for their being initialized by the time the factory runs. If you use a name that does not start with mock, Jest throws an error that explains this rule.

If you skip the Babel transform (for example by running native ES modules without it), hoisting does not happen and jest.mock may have no effect on static import statements. See the ESM section below.

Partial mocks: keep some real exports

Sometimes you only want to fake one function and keep the rest real. jest.requireActual loads the real module so you can spread it:

JavaScript
jest.mock("./mailer", () => ({
  ...jest.requireActual("./mailer"),
  send: jest.fn().mockResolvedValue(undefined),   // fake only the network part
}));

Now isValid is the real regex check, and only send is fake. This keeps tests honest: the pure logic is real, and only the slow or dangerous part is replaced. If the module is large, mock just the edge (the network or disk call) and let everything else run for real.

Per-test control and cleanup

Module mocks are mock functions, so they keep calls between tests. Use the same cleanup tools as before (clearMocks, restoreMocks, or jest.resetAllMocks() in beforeEach; see Spying with jest.spyOn). Two more tools are worth knowing:

JavaScript
jest.unmock("./mailer");        // stop mocking this module (after hoisting rules)
jest.resetModules();            // clear the module cache so the next require is fresh
jest.doMock("./mailer", () => ({ /* ... */ }));  // like mock, but NOT hoisted

jest.doMock is useful when different tests need different replacements: call it inside the test, then require the module under test inside the same test, after jest.resetModules().

ES modules (ESM) caveats

Everything above assumes CommonJS, or ES module syntax compiled to CommonJS by Babel. If you run Jest with native ES modules ("type": "module" and Node's --experimental-vm-modules flag), the static import statements are evaluated before any code in your test, so jest.mock cannot reorder them. In that mode you use jest.unstable_mockModule and a dynamic await import(...) after it:

JavaScript
import { jest } from "@jest/globals";

jest.unstable_mockModule("./mailer.js", () => ({
  isValid: jest.fn(() => true),
  send: jest.fn(),
}));

const { welcome } = await import("./notify.js");

The unstable_ prefix is a promise that the API may change, so check the documentation for your Jest version. In ESM mode you also have to import jest from @jest/globals because the global is not injected. When ESM mocking feels like a fight, that is a good sign to consider injection.

Stand-in 1: a module registry you can swap

Jest's module system keeps a registry that maps a module path to its exports and consults it on each require. The stand-in below is a miniature of that idea. It is NOT Jest's loader (there is no file loading, hoisting or automock), but it shows why a registry lookup lets a test substitute a replacement, and how requireActual and a partial mock work.

Node.js A miniature module registry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice cache.delete(path) inside mock: if the module had been loaded already, the old copy would still be in use. Real Jest has the same problem, which is why mocks must be registered before the module under test is loaded (hoisting) and why jest.resetModules() exists.

The alternative: dependency injection

Every module mock exists because notify.js reaches out to import its helper. If you let the caller supply it instead, the test needs no module magic at all:

JavaScript
// src/notify.js
async function welcome(user, mailer) {
  if (!mailer.isValid(user.email)) return false;
  await mailer.send(user.email, "Welcome", `Hi ${user.name}`);
  return true;
}

In production you pass the real mailer. In the test you pass a small object with jest.fn() members. It works with CommonJS and ESM, with any test runner, and it makes the dependency visible in the function signature.

Node.js Dependency injection: no module mocking needed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Injection is not always possible: legacy code, third-party code and code that imports a module deep inside may leave you no choice. But when you are designing new code, prefer it. Module mocking is a tool for the places where injection does not reach.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does jest.mock("./mailer") with no second argument do?

    Automock keeps the module's shape but every exported function becomes a mock function that returns undefined.
  2. 2. Why can a jest.mock factory only use outside variables whose names start with "mock"?

    Hoisting moves jest.mock to the top of the file. The mock prefix is a signal that you accept responsibility for the variable being ready.
  3. 3. How do you keep the real isValid but fake only send?

    requireActual returns the real module; spreading it and overriding one export gives a partial mock.
  4. 4. In a native ES module test setup, why does jest.mock often not work for static imports?

    Without the Babel hoisting transform, imports run first. unstable_mockModule plus await import() lets you register the mock before loading the code under test.

Summary

  • jest.mock(path) swaps a module for every file that requires it during the test run.
  • Automock is quick; a factory is explicit; a partial mock uses jest.requireActual to keep the real parts.
  • jest.mock calls are hoisted to the top, so factory variables must start with mock; jest.doMock is not hoisted.
  • Native ESM needs jest.unstable_mockModule and a dynamic import().
  • When you can, inject dependencies as parameters instead; it needs no mocking tricks.

Next, learn how to control clocks, timers and network calls in Mocking Timers, Dates and HTTP.