Skip to main content
Mocking is essential for testing by allowing you to replace dependencies with controlled implementations. Bun provides comprehensive mocking capabilities including function mocks, spies, and module mocks.

Basic Function Mocks

Create mocks with the mock function.
test.ts

Jest Compatibility

Alternatively, you can use the jest.fn() function, as in Jest. It behaves identically.
test.ts

Mock Function Properties

The result of mock() is a new function that’s been decorated with some additional properties.
test.ts

Available Properties and Methods

The following properties and methods are implemented on mock functions:

Practical Examples

Basic Mock Usage

test.ts

Dynamic Mock Implementations

test.ts

Async Mocks

test.ts

Spies with spyOn()

It’s possible to track calls to a function without replacing it with a mock. Use spyOn() to create a spy; these spies can be passed to .toHaveBeenCalled() and .toHaveBeenCalledTimes().
test.ts

Advanced Spy Usage

test.ts

Module Mocks with mock.module()

Module mocking lets you override the behavior of a module. Use mock.module(path: string, callback: () => Object) to mock a module.
test.ts
Like the rest of Bun, module mocks support both import and require.

Overriding Already Imported Modules

If you need to override a module that’s already been imported, there’s nothing special you need to do. Just call mock.module() and the module will be overridden.
test.ts

Hoisting & Preloading

If you need to ensure a module is mocked before it’s imported, you should use --preload to load your mocks before your tests run.
my-preload.ts
terminal
To make your life easier, you can put preload in your bunfig.toml:
bunfig.toml

Module Mock Best Practices

When to Use Preload

What happens if I mock a module that’s already been imported? If you mock a module that’s already been imported, the module will be updated in the module cache. This means that any modules that import the module will get the mocked version, BUT the original module will still have been evaluated. That means that any side effects from the original module will still have happened. If you want to prevent the original module from being evaluated, you should use --preload to load your mocks before your tests run.

Practical Module Mock Examples

api-client.test.ts

Mocking External Dependencies

database.test.ts

Global Mock Functions

Clear All Mocks

Reset all mock function state (calls, results, etc.) without restoring their original implementation:
test.ts
This resets the .mock.calls, .mock.instances, .mock.contexts, and .mock.results properties of all mocks, but unlike mock.restore(), it does not restore the original implementation.

Restore All Mocks

Instead of manually restoring each mock individually with mockFn.mockRestore(), restore all mocks with one command by calling mock.restore(). Doing so does not reset the value of modules overridden with mock.module().
test.ts
Using mock.restore() can reduce the amount of code in your tests by adding it to afterEach blocks in each test file or even in your test preload code.

Vitest Compatibility

For added compatibility with tests written for Vitest, Bun provides the vi object as an alias for parts of the Jest mocking API:
test.ts
This makes it easier to port tests from Vitest to Bun without having to rewrite all your mocks.

Implementation Details

Understanding how mock.module() works helps you use it more effectively:

Cache Interaction

Module mocks interact with both ESM and CommonJS module caches.

Lazy Evaluation

The mock factory callback is only evaluated when the module is actually imported or required.

Path Resolution

Bun automatically resolves the module specifier as though you were doing an import, supporting:
  • Relative paths ('./module')
  • Absolute paths ('/path/to/module')
  • Package names ('lodash')

Import Timing Effects

  • When mocking before first import: No side effects from the original module occur
  • When mocking after import: The original module’s side effects have already happened
For this reason, using --preload is recommended for mocks that need to prevent side effects.

Live Bindings

Mocked ESM modules maintain live bindings, so changing the mock will update all existing imports.

Advanced Patterns

Factory Functions

test.ts

Conditional Mocking

test.ts

Mock Cleanup Patterns

test.ts

Best Practices

Keep Mocks Simple

test.ts

Use Type-Safe Mocks

Test Mock Behavior

test.ts

Notes

Auto-mocking

__mocks__ directory and auto-mocking are not supported yet. If this is blocking you from switching to Bun, please file an issue.

ESM vs CommonJS

Module mocks have different implementations for ESM and CommonJS modules. For ES Modules, Bun has added patches to JavaScriptCore that allow Bun to override export values at runtime and update live bindings recursively.