Mocks & Snapshots in Bun
From the Bun cheat sheet ยท Test Runner ยท verified Jul 2026
Mocks & Snapshots
Mock functions, spy on methods, and use snapshot testing
typescript
import { test, expect, mock, spyOn } from "bun:test";
// Mock function
const fn = mock(() => 42);
fn();
expect(fn).toHaveBeenCalledTimes(1);
// Snapshot
test("snapshot", () => {
expect({ foo: "bar" }).toMatchSnapshot();
});๐ก mock.module() replaces entire modules โ useful for isolating units under test
โก setSystemTime() mocks Date.now() and new Date() globally โ no extra library needed
๐ Run bun test --update-snapshots to regenerate snapshot files after intentional changes
๐ข spyOn tracks calls without changing behavior โ use mockRestore() to clean up
mockspysnapshottesting