skills/bun-guides-test-mock-functions/SKILL.md
Mock functions in `bun test`
npx skillsauth add jarle/bun-skills Bun Mock functions in `bun test`Install this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
bun testCreate mocks with the mock function from bun:test.
import { test, expect, mock } from "bun:test";
const random = mock(() => Math.random());
The mock function can accept arguments.
import { test, expect, mock } from "bun:test";
const random = mock((multiplier: number) => multiplier * Math.random());
The result of mock() is a new function that's been decorated with some additional properties.
import { mock } from "bun:test";
const random = mock((multiplier: number) => multiplier * Math.random());
random(2);
random(10);
random.mock.calls;
// [[ 2 ], [ 10 ]]
random.mock.results;
// [
// { type: "return", value: 0.6533907460954099 },
// { type: "return", value: 0.6452713933037312 }
// ]
These extra properties make it possible to write expect assertions about usage of the mock function, including how many times it was called, the arguments, and the return values.
import { test, expect, mock } from "bun:test";
const random = mock((multiplier: number) => multiplier * Math.random());
test("random", async () => {
const a = random(1);
const b = random(2);
const c = random(3);
expect(random).toHaveBeenCalled();
expect(random).toHaveBeenCalledTimes(3);
expect(random.mock.calls).toEqual([[1], [2], [3]]);
expect(random.mock.results[0]).toEqual({ type: "return", value: a });
});
See Docs > Test Runner > Mocks for complete documentation on mocking with the Bun test runner.
development
Using TypeScript with Bun, including type definitions and compiler options
development
Learn how to write tests using Bun's Jest-compatible API with support for async tests, timeouts, and various test modifiers
testing
Learn how to use snapshot testing in Bun to save and compare output between test runs
testing
Learn about Bun test's runtime integration, environment variables, timeouts, and error handling