bun-automock
v0.2.5
Published
A TypeScript library that provides automatic mocking utilities for Bun's test framework, enabling easy creation of type-safe mocks for complex objects and nested structures.
Maintainers
Readme
A TypeScript library that provides automatic mocking utilities for Bun's test framework, enabling easy creation of type-safe mocks for complex objects and nested structures. Inspired by jest-mock-extended & vitest-mock-extended.
Warning This library is still in development and the readme was mostly generated by AI.
Features
- ✨ Automatic mocking of complex objects and nested structures
- 🔒 Type-safe mocks for interfaces, classes, and objects
- 🎯 Easy to use API for creating mocks
- 📊 Built-in support for test assertions
- ⚡ Compatible with Bun's test framework
- 📦 Dual package exports - supports both ESM and CommonJS
Table of Contents
- Features
- Table of Contents
- Installation
- Usage
- API Reference
- Contributing to the project
- Available Scripts
- License
- Author
Installation
bun add -D bun-automock
# or
pnpm add -D bun-automock
# or
npm install --save-dev bun-automockThe package supports both ESM and CommonJS imports:
// ESM (recommended)
import { mockFn, mockDeepFn } from 'bun-automock';
// CommonJS
const { mockFn, mockDeepFn } = require('bun-automock');Usage
mockFn()
Creates a shallow mock of an object where each property becomes a Bun mock function. Perfect for mocking services, classes, or interfaces where you need to control the behavior of individual methods.
import { mockFn } from 'bun-automock';
interface UserService {
getName(): string;
getEmail(): string;
updateProfile(data: any): Promise<void>;
}
// Create a mock with type safety
const userServiceMock = mockFn<UserService>();
// Configure mock behavior
userServiceMock.getName.mockReturnValue('John Doe');
userServiceMock.getEmail.mockReturnValue('[email protected]');
userServiceMock.updateProfile.mockResolvedValue(undefined);
// Use in tests
expect(userServiceMock.getName()).toBe('John Doe');
expect(userServiceMock.getEmail()).toBe('[email protected]');
await expect(userServiceMock.updateProfile({})).resolves.toBe(undefined);
// Use .spy() for test assertions
expect(userServiceMock.getName.spy()).toHaveBeenCalledTimes(1);
expect(userServiceMock.updateProfile.spy()).toHaveBeenCalledWith({});mockDeepFn()
Creates a deep mock that automatically mocks nested objects and their properties. Each property at any level becomes a callable mock function while preserving the ability to access nested properties.
import { mockDeepFn } from 'bun-automock';
interface DatabaseService {
users: {
repository: {
findById(id: string): Promise<User>;
save(user: User): Promise<void>;
};
cache: {
get(key: string): string | null;
set(key: string, value: string): void;
};
};
}
// Create a deep mock
const dbMock = mockDeepFn<DatabaseService>();
// Configure nested mock behavior
dbMock.users.repository.findById.mockResolvedValue({ id: '1', name: 'John' });
dbMock.users.repository.save.mockResolvedValue(undefined);
dbMock.users.cache.get.mockReturnValue('cached-value');
// Use in tests - basic functionality
await expect(dbMock.users.repository.findById('1')).resolves.toEqual({ id: '1', name: 'John' });
expect(dbMock.users.cache.get('key')).toBe('cached-value');.spy()
Each mocked property includes a .spy() method that returns the underlying Bun mock function, enabling you to use all standard Bun test assertions:
const dbMock = mockDeepFn<DatabaseService>();
// Call the mocked function
await dbMock.users.repository.findById('123');
await dbMock.users.repository.findById('456');
// Use spy() for clean test assertions
expect(dbMock.users.repository.findById.spy()).toHaveBeenCalledTimes(2);
expect(dbMock.users.repository.findById.spy()).toHaveBeenNthCalledWith(1, '123');
expect(dbMock.users.repository.findById.spy()).toHaveBeenNthCalledWith(2, '456');
expect(dbMock.users.repository.findById.spy()).toHaveReturnedTimes(2);API Reference
mockFn<T>(): MockProxy<T>
Creates a shallow mock where each property of type T becomes a Bun mock function.
Parameters:
T- The type to mock (interface, class, or object type)
Returns:
MockProxy<T>- A proxy object where each property is a Bun mock function
Additional Methods:
.spy()- Available on each mocked property, returns the underlying Bun mock function for test assertions
mockDeepFn<T extends object>(): DeepMockProxy<T>
Creates a deep mock that automatically handles nested objects, making every property at any depth a callable mock function.
Parameters:
T- The type to mock (interface, class, or object type)
Returns:
DeepMockProxy<T>- A proxy object with deep mocking capabilities
Additional Methods:
.spy()- Available on each mocked property, returns the underlying Bun mock function for test assertions
Contributing to the project
The project uses Bun as the package manager and runtime, with tsdown for modern dual-package building.
External dependencies are kept minimal and added only for compelling reasons.
Available Scripts
bun run test- Run the test suite oncebun run tdd- Run tests in watch mode for continuous developmentbun run test:coverage- Run tests with coverage reportingbun run build- Build the project with dual package exports (ESM + CJS)bun run dev- Build in watch mode for developmentbun run clean- Clean the dist and coverage directories
Development
To start developing run the following commands:
bun install # install dependencies
bun dev # build in watch mode for development
bun tdd # run tests in watch mode for continuous developmentThis will:
- Clean the
distdirectory - Bundle the source code using tsdown
- Generate both ESM (
index.js) and CommonJS (index.cjs) outputs - Create TypeScript declaration files for both formats (
index.d.ts,index.d.cts) - Generate source maps for debugging
The built files will be available in the dist directory:
index.js- ESM bundleindex.cjs- CommonJS bundleindex.d.ts- TypeScript declarations for ESMindex.d.cts- TypeScript declarations for CommonJS- Source maps for debugging
Testing
Run the test suite:
bun test # Run tests once
bun run tdd # Run tests in watch mode for continuous development
bun test:coverage # Run tests with coverage reportingThe tests are written using Bun's test framework.
License
This project is licensed under the MIT License - see the LICENSE file for details.
