Typorithm · medium

Mocks & Spies

bun-test-mocksbunmocksspiesassertions
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Mocks & Spies

0%

bun:test

mock(fn) makes a callable that records every invocation in .mock.calls, and spyOn(obj, "method") wraps an existing method to track it in place. Assert with toHaveBeenCalledWith and toHaveBeenCalledTimes, and use mock.module() to replace whole imports.

mock(fn) from bun:test wraps a function into a callable mock that runs your implementation and records every call's arguments in fn.mock.calls.

spyOn(obj, "method") wraps an existing method in place so you can assert how it was called without rewriting the object, and mock.module() replaces an entire imported module for the test.

Matchers like toHaveBeenCalledWith and toHaveBeenCalledTimes let you assert the exact arguments and call counts a mock or spy received.

01

mock(fn) records calls in .mock.calls.

02

spyOn(obj, "m") wraps an existing method.

03

mock.module() replaces a whole import.

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

const fn = mock((x: number) => x + 1);
fn(41);
expect(fn.mock.calls.length).toBe(1);
expect(fn).toHaveBeenCalledWith(41);

const obj = { greet: () => "hi" };
const spy = spyOn(obj, "greet");
obj.greet();
expect(spy).toHaveBeenCalledTimes(1);

Read the implementation

Connect each part of the code to the concept before you type.

1. Import mock & spyOn

mock and spyOn are exported from bun:test alongside test and expect.

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

2. Create a mock

mock(fn) wraps a function so its calls are recorded, while still running the implementation.

const fn = mock((x: number) => x + 1);

3. Inspect .mock.calls

fn.mock.calls is an array of the arguments from every call — its length is the call count.

expect(fn.mock.calls.length).toBe(1);

4. Assert call args

toHaveBeenCalledWith checks the mock was invoked with the given arguments.

expect(fn).toHaveBeenCalledWith(41);

5. Spy on a method

spyOn(obj, "method") wraps an existing method so its calls are tracked without replacing it.

const spy = spyOn(obj, "greet");

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Mocks & Spies: Lesson & Practice · Typorithm | ApplyDjinn