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 🙏

© 2026 – Pkg Stats / Ryan Hefner

bun-mock-builder

v0.1.3

Published

**Ephemeral HTTP mock servers for integration tests, built for Bun.**

Readme

bun-mock-builder

Ephemeral HTTP mock servers for integration tests, built for Bun.

bun-mock-builder lets you spin up real HTTP servers during tests, with a controlled lifecycle and a fluent builder API — no request interception, no heavy setup.


What it is

bun-mock-builder is a tiny library for building ephemeral HTTP mock servers in Bun. You define routes with a fluent builder API and run them inside your tests.

The problem

When testing integrations, you often need to mock external APIs.

But:

  • the real backend is not ready
  • third-party APIs are unstable or rate-limited
  • intercepting fetch does not behave like production
  • CI environments need predictable, isolated infrastructure

Why it is different

This is a real HTTP server, not request interception.

It uses Bun.serve and runs alongside your tests, giving you real network behavior with a controlled lifecycle.


Quick example (bun:test)

import { test, expect, beforeAll, afterAll } from "bun:test";
import { mock, type RunningMockServer } from "bun-mock-builder";

let server: RunningMockServer;

beforeAll(async () => {
  server = await mock()
    .post("/users", async (ctx) => {
      const body = await ctx.json<{ name?: string }>();
      return ctx.status(201).json({ id: 1, name: body.name ?? "" });
    })
    .listen(0); // random port
});

afterAll(async () => {
  await server.close();
});

test("creates user", async () => {
  const res = await fetch(`${server.url}/users`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ name: "Joao" }),
  });

  const json = await res.json();
  expect(res.status).toBe(201);
  expect(json.name).toBe("Joao");
});

Features

  • 🧪 Real HTTP server (no fetch interception)
  • Bun-first, built on Bun.serve
  • 🔁 Ephemeral lifecycle (start in a test, stop in afterAll)
  • 🧠 Builder pattern inspired by Elysia
  • 🧩 Designed for integration testing and CI
  • 🧱 Lightweight middleware + groups for shared setup

Typed client (optional)

bun-mock-builder includes an optional typed HTTP client for tests.

It provides:

  • typed paths
  • typed params
  • typed request bodies
  • typed responses
import { createClient } from "bun-mock-builder";

interface Person {
  id: string;
  name: string;
}

interface Api {
  "/users/:id": {
    GET: { response: Person };
  };
  "/users": {
    POST: {
      body: { name: string };
      response: Person;
    };
  };
}

const api = createClient<Api>({
  baseUrl: "https://example.com",
});

const user = await api.get("/users/:id", { params: { id: "123" } });
const created = await api.post("/users", { body: { name: "Joao" } });

API reference

What it provides

  • Ephemeral mock servers with a controlled lifecycle
  • Fluent builder API: .get, .post, .put, .delete
  • Middleware and grouping: .use, .group
  • listen(port?) with fixed or random ports (0)
  • Server handle with { url, port, buildUrl(), close() }

Request access

  • ctx.query
  • ctx.headers
  • ctx.method
  • ctx.path
  • await ctx.json()

Response helpers

  • ctx.json
  • ctx.text
  • ctx.status

Predictable errors

  • 404 for missing routes
  • 500 for handler errors
  • Runtime status code validation (100–599)

Core types

  • MockServerBuilder — builder used to define routes and start the server
  • RunningMockServer — returned by .listen(), exposes url, port, and close()
  • MockContext — context passed to route handlers
  • Handler — function that receives MockContext and returns Response
  • Middleware(ctx, next) => Response | Promise<Response>

Response helper details

  • ctx.json(data, status?, headers?)
  • ctx.text(text, status?, headers?)
  • ctx.status(code).json(data, headers?)
  • ctx.status(code).text(text, headers?)
  • ctx.status(code).empty(headers?) — useful for 204 or 304 responses
  • ctx.res(body?, init?) — create a new mutable Response
  • ctx.clone(res) — clone a Response (useful in middlewares)

Middleware and groups

Middlewares are executed in the order they are registered. Groups inherit middlewares from the parent builder.

mock()
  .use(async (ctx, next) => {
    const res = await next();
    const cloned = ctx.clone(res);
    cloned.headers.set("x-mock", "true");
    return cloned;
  })
  .group("/v1", (group) => {
    group.get("/health", () => new Response("ok"));
  });

For safer URL composition:

const server = await mock().get("/users", () => new Response("ok")).listen(0);
await fetch(server.buildUrl("/users"));

Non-goals

  • This is not a web framework
  • This is not request interception
  • This is not a replacement for production servers

bun-mock-builder is focused on test infrastructure.

Built with Bun v1.3.4.