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

More Bun tasks

Back to the full Bun cheat sheet