bun:test, including function mocks, spies, and module mocks. The API is fully compatible with Jest’s mocking interface.
Creating mock functions
Usemock() 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
- mockReturnValue
- mockReturnValueOnce
- mockResolvedValue
- mockRejectedValue
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
UsespyOn() to wrap an existing method with tracking without replacing it by default:
mockImplementation, mockReturnValue, etc. methods as regular mocks:
Module mocking
Usemock.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 inafterEach:
mock.restore() does not reset modules overridden with mock.module().mock.clearAllMocks()
Reset call history for all mocks without restoring implementations:Best practices
Keep mocks simple
Keep mocks simple
Mocks with complex internal logic are hard to maintain and can introduce bugs of their own. Return the minimum data your test needs.
Restore mocks after each test
Restore mocks after each test
Always clean up to prevent test pollution:
Use type-safe mocks
Use type-safe mocks
Verify mock interactions
Verify mock interactions
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 wayimportdoes — relative paths, absolute paths, and package names are all supported.