name: bun-mocking description: Mock functions, spies, and modules in Bun tests — mock(), spyOn(), mock.module(), call tracking, async mocks, cleanup patterns. Use when writing tests that need to isolate units from dependencies.
Bun Mocking
Comprehensive guide to mocking in Bun tests. Covers function mocks, spies, and module mocks.
Quick Reference
| What | How |
|---|---|
| Function mock | mock(() => value) |
| Spy on method | spyOn(obj, 'method') |
| Mock module | mock.module('./path', () => {}) |
| Clear all | mock.clearAllMocks() |
| Restore all | mock.restore() |
Function Mocks
Basic Usage
import { test, expect, mock } from "bun:test";
const fn = mock((x: number) => x * 2);
test("mock", () => {
fn(5);
expect(fn).toHaveBeenCalled();
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenCalledWith(5);
expect(fn).toHaveBeenLastCalledWith(5);
});
Mock Properties
const fn = mock((x: number) => x * 2);
fn(5);
fn(10);
fn.mock.calls; // [[5], [10]]
fn.mock.results; // [{ type: "return", value: 10 }, { type: "return", value: 20 }]
fn.mock.lastCall; // [10]
fn.mock.instances; // Array of `this` contexts
Dynamic Implementations
const fn = mock();
fn.mockImplementationOnce(() => "first");
fn.mockImplementationOnce(() => "second");
fn.mockImplementation(() => "default");
fn(); // "first"
fn(); // "second"
fn(); // "default"
fn(); // "default"
Return Values
const fn = mock();
fn.mockReturnValue(42);
fn(); // 42
fn.mockReturnValueOnce(1);
fn.mockReturnValueOnce(2);
fn(); // 1
fn(); // 2
fn(); // 42 (back to default)
Async Mocks
const asyncFn = mock();
asyncFn.mockResolvedValue("success");
await asyncFn(); // "success"
asyncFn.mockRejectedValue(new Error("fail"));
await expect(asyncFn()).rejects.toThrow("fail");
Spies
Track calls without replacing implementation:
import { test, expect, spyOn } from "bun:test";
const obj = {
method() { return "real"; }
};
const spy = spyOn(obj, "method");
test("spy", () => {
obj.method(); // Still returns "real"
expect(spy).toHaveBeenCalled();
// Override implementation
spy.mockReturnValue("mocked");
obj.method(); // "mocked"
});
Module Mocks
Basic Module Mock
import { test, expect, mock } from "bun:test";
// Mock at top level, before imports
mock.module("./api", () => ({
fetchUser: mock(async (id: string) => ({ id, name: "Mock User" })),
}));
test("uses mocked module", async () => {
const { fetchUser } = await import("./api");
const user = await fetchUser("123");
expect(user.name).toBe("Mock User");
});
Mock Node.js Modules
mock.module("node:fs/promises", () => ({
readFile: mock(async () => "mocked content"),
writeFile: mock(async () => {}),
mkdir: mock(async () => {}),
}));
Mock with memfs (Filesystem)
import { Volume } from "memfs";
const vol = new Volume();
mock.module("node:fs/promises", () => ({
lstat: async (p: string) => vol.lstatSync(p),
mkdir: async (p: string, opts?: any) => vol.mkdirSync(p, opts),
readdir: async (p: string, opts?: any) => vol.readdirSync(p, opts),
readFile: async (p: string, opts?: any) => vol.readFileSync(p, opts),
writeFile: async (p: string, data: any) => vol.writeFileSync(p, data),
rm: async (p: string, opts?: any) => vol.rmSync(p, opts),
cp: async (src: string, dest: string, opts?: any) => vol.cpSync(src, dest, opts),
}));
beforeEach(() => {
vol.reset();
});
Mock node:os
mock.module("node:os", () => ({
homedir: () => "/home/testuser",
platform: () => "linux",
}));
Global Cleanup
import { afterEach, mock } from "bun:test";
afterEach(() => {
// Clear call history (preserve implementations)
mock.clearAllMocks();
// Or restore original implementations
mock.restore();
});
Common Patterns
Factory Function for Reusable Mocks
function createMockFs(overrides = {}) {
return {
readFile: mock(async () => ""),
writeFile: mock(async () => {}),
mkdir: mock(async () => {}),
...overrides,
};
}
// Usage
mock.module("node:fs/promises", () => createMockFs({
readFile: mock(async () => "custom content"),
}));
Reset Mock Between Tests
function resetFsMock() {
mock.module("node:fs/promises", createFsMock);
}
beforeEach(() => {
vol.reset();
resetFsMock();
});
Mock with Type Safety
interface UserService {
getUser(id: string): Promise<User>;
createUser(data: CreateUserData): Promise<User>;
}
const mockUserService: UserService = {
getUser: mock(async (id: string) => ({ id, name: "Test" })),
createUser: mock(async (data) => ({ id: "new", ...data })),
};
Jest/Vitest Compatibility
// Jest style
import { jest } from "bun:test";
const fn = jest.fn(() => 42);
// Vitest style
import { vi } from "bun:test";
const fn2 = vi.fn(() => 42);
Key Points
- Mock before import: Call
mock.module()at top level before any imports of the module - Use --preload: For modules with side effects, use
bun test --preload ./mocks.ts - Live bindings: ESM mocks update all existing imports when changed
- Restore spies: Use
mock.restore()inafterEachto restore original implementations
Pitfalls
- Mocking after import: original module's side effects already happened
- Forgetting to reset: mock state persists between tests without cleanup
- Path resolution: use same path style as imports (
./modulenotmodule)