Skip to content
jshacks.dev
Testing

Test Doubles: Mocks, Stubs, Spies and Fakes

Learn the five test doubles in JavaScript: dummies, stubs, spies, mocks and fakes, with Vitest examples, when to use each and the cost of over-mocking.

8 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the Vitest, Cypress, Jest and GitHub Actions logos.

Real code has collaborators: a database, an HTTP client, a clock, an email service. Testing a unit of code in isolation means replacing some of those collaborators with stand-ins that are fast, predictable and under the test's control. These stand-ins are called test doubles, after the stunt double in a film. People use the words mock, stub and spy as if they were interchangeable, and the loose usage hides real differences: some doubles only supply data, some only record what happened, some contain working but simplified logic. Choosing the right kind makes tests clearer and less brittle. This post defines the five kinds in the vocabulary of Gerard Meszaros's xUnit Test Patterns, which Martin Fowler's essay Mocks Aren't Stubs popularized: dummy, stub, spy, mock and fake. It shows each with Vitest 4 on Node.js 24, using vi.fn and vi.spyOn, and explains when to use each and where over-mocking goes wrong. The API is documented in the Vitest mocking guide.

The code under test

A service sends a welcome email when a user registers. It depends on a user repository and a mailer.

welcome.jsJavaScript
export async function registerUser({ email }, { users, mailer, now = () => new Date() }) {
  const existing = await users.findByEmail(email);
  if (existing) {
    throw new Error("Email already registered");
  }

  const user = await users.insert({ email, createdAt: now().toISOString() });
  await mailer.send({ to: email, subject: "Welcome", body: `Hello ${email}` });
  return user;
}
Text
(the function finds a user, inserts a new one and sends one email)

The repository and mailer are passed in, which is what makes substitution easy. Each kind of double answers a different question about this function.

Dummy: fills a parameter that is never used

A dummy is an object passed only to satisfy a signature. The code under test never touches it. Use one when a dependency is required but irrelevant to the behavior.

dummy.test.jsJavaScript
import { expect, test } from "vitest";
import { registerUser } from "./welcome.js";

test("rejects an email that is already registered", async () => {
  const users = { findByEmail: async () => ({ id: 1 }) };
  const mailer = null;

  await expect(registerUser({ email: "[email protected]" }, { users, mailer })).rejects.toThrow(
    "Email already registered"
  );
});
Text
 ✓ dummy.test.js (1 test)

The mailer is null, a dummy, because the function throws before reaching it. If the function ever used the mailer on this path, the test would crash with a TypeError, which is a useful signal that the behavior changed. The users object, in contrast, is a stub, as the next section shows.

Stub: supplies canned answers

A stub returns fixed values so the test controls the inputs the code receives from a collaborator. It is about indirect inputs: what the dependency tells your code. Stubs are not checked afterward.

stub.test.jsJavaScript
import { expect, test, vi } from "vitest";
import { registerUser } from "./welcome.js";

test("inserts the user with the current time", async () => {
  const users = {
    findByEmail: vi.fn().mockResolvedValue(null),
    insert: vi.fn(async (data) => ({ id: 1, ...data })),
  };
  const mailer = { send: vi.fn() };
  const now = () => new Date("2026-06-01T12:00:00Z");

  const user = await registerUser({ email: "[email protected]" }, { users, mailer, now });

  expect(user).toEqual({ id: 1, email: "[email protected]", createdAt: "2026-06-01T12:00:00.000Z" });
});
Text
 ✓ stub.test.js (1 test)

findByEmail is stubbed to resolve with null, saying "no such user", and now is stubbed to return a fixed date, which makes the timestamp predictable. The assertion checks the returned value, a state check, and says nothing about how the collaborators were called. That is the strength of stubs: they set the scene, and the test verifies the outcome.

Spy: records how it was called

A spy wraps a real function, or stands in for one, and records the calls: arguments, number of calls, return values. A spy checks indirect outputs, meaning what your code sent to a collaborator. In Vitest, vi.fn() creates a recording function, and vi.spyOn(object, "method") wraps an existing method and keeps its behavior unless you change it.

spy.test.jsJavaScript
import { expect, test, vi } from "vitest";

const logger = {
  info(message) {
    return `logged: ${message}`;
  },
};

test("spyOn records calls and keeps the original behavior", () => {
  const spy = vi.spyOn(logger, "info");

  const result = logger.info("started");

  expect(result).toBe("logged: started");
  expect(spy).toHaveBeenCalledTimes(1);
  expect(spy).toHaveBeenCalledWith("started");
  spy.mockRestore();
});
Text
 ✓ spy.test.js (1 test)

The spy lets the real method run, so result is the real return value, and then the test reads the record. The call to mockRestore() puts the original method back, which matters for tests that share the object. A spy is the right tool when the behavior you care about is a side effect with no return value, such as sending an email.

spy-mailer.test.jsJavaScript
import { expect, test, vi } from "vitest";
import { registerUser } from "./welcome.js";

test("sends exactly one welcome email to the new user", async () => {
  const users = {
    findByEmail: async () => null,
    insert: async (data) => ({ id: 1, ...data }),
  };
  const mailer = { send: vi.fn() };

  await registerUser({ email: "[email protected]" }, { users, mailer });

  expect(mailer.send).toHaveBeenCalledTimes(1);
  expect(mailer.send).toHaveBeenCalledWith({
    to: "[email protected]",
    subject: "Welcome",
    body: "Hello [email protected]",
  });
});
Text
 ✓ spy-mailer.test.js (1 test)

Here mailer.send is a spy built with vi.fn(). Its job is to remember the call so the test can check it.

Mock: expectations built in

In the strict definition, a mock is a double that you program with expectations up front, which it verifies itself: it expects these calls, in this order, and fails if anything else happens. Many JavaScript tools blur this: Vitest's vi.fn is described as a mock function, but most uses are spies, with assertions written afterward in the Assert phase. The practical difference to keep in mind is where the verification lives. With a strict mock, the double fails the test the moment an unexpected call arrives. With a spy, the test fails only when its own assertions fail.

You can build a strict mock by making the double throw for anything unexpected.

strict-mock.test.jsJavaScript
import { expect, test } from "vitest";
import { registerUser } from "./welcome.js";

function strictMailer(expected) {
  const calls = [];
  return {
    send(message) {
      if (calls.length >= expected.length) {
        throw new Error(`Unexpected call to send: ${JSON.stringify(message)}`);
      }
      calls.push(message);
    },
    verify() {
      expect(calls).toEqual(expected);
    },
  };
}

test("sends the welcome email and nothing else", async () => {
  const users = { findByEmail: async () => null, insert: async (d) => ({ id: 1, ...d }) };
  const mailer = strictMailer([{ to: "[email protected]", subject: "Welcome", body: "Hello [email protected]" }]);

  await registerUser({ email: "[email protected]" }, { users, mailer });

  mailer.verify();
});
Text
 ✓ strict-mock.test.js (1 test)

This is closer to the textbook mock, with the expectations stated first. Because it couples the test to the exact sequence of calls, use it sparingly, only when the interaction itself is the requirement, such as "an email must be sent exactly once".

Fake: a working, simplified implementation

A fake has real logic but takes a shortcut that makes it unsuitable for production: an in-memory repository instead of a database, a local file system in place of cloud storage, a queue that processes synchronously. Unlike a stub, a fake behaves consistently across several calls, so it supports tests that involve more than one interaction.

fake.test.jsJavaScript
import { expect, test, vi } from "vitest";
import { registerUser } from "./welcome.js";

class InMemoryUsers {
  #rows = [];

  async findByEmail(email) {
    return this.#rows.find((row) => row.email === email) ?? null;
  }

  async insert(data) {
    const row = { id: this.#rows.length + 1, ...data };
    this.#rows.push(row);
    return row;
  }
}

test("registering the same email twice fails the second time", async () => {
  const users = new InMemoryUsers();
  const mailer = { send: vi.fn() };

  await registerUser({ email: "[email protected]" }, { users, mailer });

  await expect(registerUser({ email: "[email protected]" }, { users, mailer })).rejects.toThrow(
    "Email already registered"
  );
  expect(mailer.send).toHaveBeenCalledTimes(1);
});
Text
 ✓ fake.test.js (1 test)

The fake repository remembers the first insert, so the second registration sees it. A stub would need to be reprogrammed between calls. This test also combines kinds of doubles, as most real tests do: a fake for the repository and a spy for the mailer. Fakes are the most valuable double for the data layer, and they need their own tests or a shared contract test run against both the fake and the real implementation, so they do not drift from the real behavior.

Modules and globals

Sometimes the dependency is imported rather than passed in. vi.mock replaces a module for a test file. Use it for modules you do not control, such as an HTTP client, not as the default.

module-mock.test.jsJavaScript
import { expect, test, vi } from "vitest";
import { getWeather } from "./weather.js";
import { httpGet } from "./http.js";

vi.mock("./http.js", () => ({
  httpGet: vi.fn(),
}));

test("returns the temperature from the API response", async () => {
  vi.mocked(httpGet).mockResolvedValue({ temperature: 21 });

  const result = await getWeather("Lisbon");

  expect(result).toBe(21);
  expect(httpGet).toHaveBeenCalledWith("/weather?city=Lisbon");
});
Text
 ✓ module-mock.test.js (1 test)

vi.mock calls are hoisted to the top of the file, so the replacement is in place before the imports run. Passing dependencies as parameters, as in the earlier examples, avoids this machinery and is often the simpler design.

Choosing

You want toUse
Fill a parameter the code never usesDummy
Control what a collaborator returnsStub
Check that a side effect happenedSpy
Fail on any unexpected interactionMock, in the strict sense
Run many interactions against realistic behaviorFake

Prefer state checks, asserting on results, over interaction checks, asserting on calls, when both are possible, because state checks survive refactoring. Use spies for outputs that have no visible result, such as notifications.

The cost of over-mocking

A test where every collaborator is mocked and every call is verified is a copy of the implementation. It passes when the code is wrong in a way the mocks do not model, such as a database query that returns the wrong rows, and it fails when you refactor, even with identical behavior, because the sequence of calls changed. Signs of over-mocking: the test setup is longer than the code, you assert the order of internal calls, you mock the thing you are testing or you mock value objects and pure functions. Keep real objects for anything cheap and deterministic, use fakes for slow dependencies and keep a few integration tests that run the real thing, so that the doubles do not become the only check of a contract.

Share

Keep reading

Flat illustration of a test report with one failing test, with the Vitest, GitHub Actions and Jest logos.
Testing

The Testing Pyramid and the Testing Trophy

Compare the testing pyramid and the testing trophy for JavaScript apps: what each says about unit, integration and end-to-end tests, and how to choose.

8 min read
Flat illustration of a test run shown as a row of passing dots, with the Vitest, Mocha, Cypress and Jest logos.
Testing

Arrange, Act, Assert

Arrange, Act, Assert splits a test into setup, one action and checks. See it in Vitest with builders, async tests, common mistakes and variants.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.