npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

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.

Readme

Static Badge

Quality Gate Coverage Sonar Violations

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

Installation

bun add -D bun-automock
# or
pnpm add -D bun-automock
# or
npm install --save-dev bun-automock

The 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 once
  • bun run tdd - Run tests in watch mode for continuous development
  • bun run test:coverage - Run tests with coverage reporting
  • bun run build - Build the project with dual package exports (ESM + CJS)
  • bun run dev - Build in watch mode for development
  • bun 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 development

This will:

  1. Clean the dist directory
  2. Bundle the source code using tsdown
  3. Generate both ESM (index.js) and CommonJS (index.cjs) outputs
  4. Create TypeScript declaration files for both formats (index.d.ts, index.d.cts)
  5. Generate source maps for debugging

The built files will be available in the dist directory:

  • index.js - ESM bundle
  • index.cjs - CommonJS bundle
  • index.d.ts - TypeScript declarations for ESM
  • index.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 reporting

The tests are written using Bun's test framework.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Author