Skip to main content
Bun provides comprehensive mocking capabilities through bun:test, including function mocks, spies, and module mocks. The API is fully compatible with Jest’s mocking interface.

Creating mock functions

Use mock() to create a tracked function with a controllable implementation:

jest.fn() compatibility

jest.fn() is an alias for mock() and behaves identically:

vi compatibility

For tests migrated from Vitest, vi.fn() is also available:

Mock call history

Every mock records its call arguments and return values:

Controlling return values

Set a fixed return value for all subsequent calls:

Controlling implementations

mockImplementation

Replace the mock’s entire implementation:

mockImplementationOnce

Override the implementation for only the next call:

Mock properties and methods reference

Spying on existing methods

Use spyOn() to wrap an existing method with tracking without replacing it by default:
Spies support the same mockImplementation, mockReturnValue, etc. methods as regular mocks:

Module mocking

Use mock.module() to replace an entire module with a controlled implementation. Both import and require are supported.

Mocking external packages

Live bindings

ESM modules maintain live bindings. Updating the mock after an import is already in effect will update all existing references:

Preloading module mocks

To prevent the original module from executing at all, register mocks in a preload file:
my-preload.ts
bunfig.toml

Global mock management

mock.restore()

Restore all mock functions to their original implementations at once. Useful in afterEach:
mock.restore() does not reset modules overridden with mock.module().

mock.clearAllMocks()

Reset call history for all mocks without restoring implementations:

Best practices

Mocks with complex internal logic are hard to maintain and can introduce bugs of their own. Return the minimum data your test needs.
Always clean up to prevent test pollution:

Notes

  • Auto-mocking: __mocks__ directory support is not yet implemented. File an issue if this is blocking your migration.
  • ESM live bindings: Bun patches JavaScriptCore to allow updating ESM export values at runtime, which enables live binding updates after a module is mocked.
  • Path resolution: mock.module() resolves paths the same way import does — relative paths, absolute paths, and package names are all supported.