Skip to main content
Bun provides a Jest-compatible mocking API. You can mock functions, spy on objects, and mock entire modules.

Mock functions

Create a mock function with mock():

Mock implementation

Control the return value of a mock:

Mock return values

Set return values without providing a full implementation:

Mock resolved/rejected values

For async functions:

Mock implementation once

Provide different implementations for sequential calls:

Spying on objects

Use spyOn() to spy on methods of an object:

Mock implementation

Override the implementation:

Restore original implementation

Restore the original implementation:

Automatic cleanup with using

Bun supports automatic cleanup with the using keyword:

Mock matchers

Check how mock functions were called:

Mock properties

Access mock call history:

Clearing and resetting mocks

mockClear()

Clears call history but preserves mock implementation:

mockReset()

Clears call history and removes mock implementation:

mockRestore()

Restores original implementation (for spies):

Module mocking

Mock entire modules with mock.module():

Partial module mocking

Mock specific exports while keeping others:

Global mock utilities

jest.clearAllMocks()

Clears all mocks:

jest.restoreAllMocks()

Restores all spies: