Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 39 ยท Testing

Mocks, Spies and Fake Time

Isolate code in bun test with mock functions, spyOn, mock.module and setSystemTime: call tracking, return values, restoring state and testing code that uses fetch or the clock.

A good unit test controls everything around the code it checks. If a function sends email, calls a payment API or reads the clock, you do not want the real thing in a test: it is slow, it costs money and its result changes. Test doubles replace those collaborators. Bun's test runner provides the Jest-style tools: mock() for fake functions, spyOn() to watch or override a method, mock.module() to replace a whole module, and setSystemTime() to freeze the clock.

bun:test is not available here, so the Bun snippets are read-only. The TryIt blocks build tiny stand-ins for mock and spyOn in plain Node so you can see how call tracking works. They are not Bun's implementation.

Mock functions

mock(fn?) returns a function that records every call. You can give it an implementation, or none (it then returns undefined).

TypeScript
import { expect, mock, test } from "bun:test";

test("calls the callback for each item", () => {
  const onItem = mock((x: number) => x * 2);

  [1, 2, 3].forEach((x) => onItem(x));

  expect(onItem).toHaveBeenCalledTimes(3);
  expect(onItem).toHaveBeenCalledWith(2);
  expect(onItem).toHaveBeenLastCalledWith(3);
  expect(onItem.mock.calls).toEqual([[1], [2], [3]]);
  expect(onItem.mock.results[0].value).toBe(2);
});

The .mock property holds calls (array of argument arrays), results (each { type: "return" | "throw", value }), instances and lastCall. Matchers read it for you. Control the behavior per test:

TypeScript
const getUser = mock();
getUser.mockReturnValue({ id: 1 });          // every call
getUser.mockReturnValueOnce({ id: 2 });      // next call only
getUser.mockResolvedValue({ id: 3 });        // returns a resolved promise
getUser.mockRejectedValueOnce(new Error("down"));
getUser.mockImplementation((id) => ({ id }));
getUser.mockClear();   // forget calls, keep behavior
getUser.mockReset();   // forget calls and behavior
Node.js How a mock records calls (stand-in)

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.

Dependency injection first

The cleanest test double is no framework at all: pass the dependency in.

TypeScript
// notify.ts
export async function notifyUser(
  id: number,
  deps: { getUser: (id: number) => Promise<{ email: string }>; send: (to: string, text: string) => Promise<void> },
) {
  const user = await deps.getUser(id);
  await deps.send(user.email, "Your report is ready");
}
TypeScript
// notify.test.ts
import { expect, mock, test } from "bun:test";
import { notifyUser } from "./notify";

test("emails the user", async () => {
  const send = mock(async () => {});
  const getUser = mock(async () => ({ email: "[email protected]" }));

  await notifyUser(1, { getUser, send });

  expect(send).toHaveBeenCalledWith("[email protected]", "Your report is ready");
});

Reach for spyOn and mock.module when you cannot change the code under test, for example third-party libraries.

Spies

spyOn(object, "method") replaces a method with a mock that still calls the original by default. It lets you observe calls, and you may override the result:

TypeScript
import { afterEach, expect, spyOn, test } from "bun:test";

const calculator = {
  add: (a: number, b: number) => a + b,
};

test("spying keeps the real behavior", () => {
  const spy = spyOn(calculator, "add");
  expect(calculator.add(1, 2)).toBe(3);
  expect(spy).toHaveBeenCalledWith(1, 2);
});

test("spying can override it", () => {
  spyOn(calculator, "add").mockReturnValue(99);
  expect(calculator.add(1, 2)).toBe(99);
});

afterEach(() => {
  mock.restore(); // put every spied method back
});

Call mock.restore() (or spy.mockRestore()) in afterEach, otherwise an override leaks into later tests and causes puzzling failures. You can spy on globals too: spyOn(console, "log").mockImplementation(() => {}) silences output and lets you assert on it, and spyOn(globalThis, "fetch") stubs the network.

Stubbing fetch

Tests must never hit the real network. Replace fetch for one test and restore it:

TypeScript
import { afterEach, expect, spyOn, test } from "bun:test";
import { getWeather } from "./weather";

afterEach(() => mock.restore());

test("parses the temperature", async () => {
  spyOn(globalThis, "fetch").mockResolvedValue(Response.json({ temp: 21 }));
  expect(await getWeather("Berlin")).toBe("21 degrees");
});
Node.js Stubbing fetch by hand and restoring it

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.

Replacing modules

mock.module(path, factory) swaps a module for everything that imports it afterwards:

TypeScript
import { expect, mock, test } from "bun:test";

mock.module("./mailer", () => ({
  sendMail: mock(async () => ({ id: "fake-1" })),
}));

const { signUp } = await import("./signup"); // import AFTER mocking
test("signUp sends a welcome mail", async () => {
  const { sendMail } = await import("./mailer");
  await signUp("[email protected]");
  expect(sendMail).toHaveBeenCalledTimes(1);
});

Import the code under test after mock.module, with a dynamic import(), because static imports are hoisted and would load the real module first. You can also put module mocks in a file listed under [test] preload in bunfig.toml, so that they apply to every test file.

Controlling time

Code that depends on the current date is flaky. setSystemTime fixes Date.now() and new Date():

TypeScript
import { afterEach, expect, setSystemTime, test } from "bun:test";

afterEach(() => setSystemTime()); // no argument: back to real time

test("subscription expired", () => {
  setSystemTime(new Date("2026-06-01T00:00:00Z"));
  expect(isExpired(new Date("2026-05-31T00:00:00Z"))).toBe(true);
});

For timers (setTimeout, setInterval), Bun's jest object offers fake timers in recent versions (jest.useFakeTimers(), jest.advanceTimersByTime(ms), jest.useRealTimers()). Check the docs for your installed version, and prefer small injectable now() and sleep() helpers that need no fake timers at all.

What not to mock

Mock the boundaries (network, disk, clock, email, payment), not your own pure logic. A test where every function is mocked proves only that you called the mocks. When the real thing is cheap and deterministic, such as an in-memory SQLite database (coming up), use it instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does spyOn(obj, 'method') do by default?

    A spy records calls and passes through; add mockReturnValue or mockImplementation to override.
  2. 2. Why use a dynamic import() after mock.module()?

    Hoisted static imports run first, so the code under test would capture the real module.
  3. 3. What should you do in afterEach after overriding methods with spies?

    Overrides leak between tests unless they are restored.
  4. 4. What does mockClear() reset compared with mockReset()?

    Clear wipes call history; reset wipes history and implementations.

Summary

  • mock() creates a function that records calls and results; configure it with mockReturnValue, mockResolvedValue, mockImplementation.
  • Passing dependencies as parameters is the simplest and clearest way to test.
  • spyOn observes or overrides existing methods; always mock.restore() afterwards.
  • mock.module replaces modules (import the code under test afterwards); setSystemTime freezes the clock.
  • Mock boundaries only, never your own logic.

Next: Hooks, Snapshots, Coverage and Testing a Server