1. Import mock & spyOn
mock and spyOn are exported from bun:test alongside test and expect.
import { test, expect, mock, spyOn } from "bun:test";Typorithm · medium
Step 1 of 8 · intro card
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.
mock(fn) records calls in .mock.calls.
spyOn(obj, "m") wraps an existing method.
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);Connect each part of the code to the concept before you type.
mock and spyOn are exported from bun:test alongside test and expect.
import { test, expect, mock, spyOn } from "bun:test";mock(fn) wraps a function so its calls are recorded, while still running the implementation.
const fn = mock((x: number) => x + 1);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);toHaveBeenCalledWith checks the mock was invoked with the given arguments.
expect(fn).toHaveBeenCalledWith(41);spyOn(obj, "method") wraps an existing method so its calls are tracked without replacing it.
const spy = spyOn(obj, "greet");Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.