rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

An in-process client#

@rhythmjs/testing tests the real pipeline without opening a socket: createTestClient dispatches Request objects straight into the fetch handler of an app or a bare router. Its context option is assigned onto every request's context — for a router it supplies the startup values the router declares as its input, for an app it replaces what is already there. Tests are plain bun:test:

TypeScript
// src/notes/notes.controller.spec.ts
import { describe, expect, test } from "bun:test";
import { createTestClient } from "@rhythmjs/testing/router";
import { notesController } from "./notes.controller";
import type { NotesService } from "./notes.service";

process.env.API_TOKEN = "test-token"; // what authService.verify accepts
const headers = { authorization: "Bearer test-token" };

const notesService = {
  list: async () => [{ id: "1", title: "stub", content: "", createdAt: new Date(), updatedAt: new Date() }],
  get: async () => undefined,
  create: async (input) => ({ id: "2", ...input, createdAt: new Date(), updatedAt: new Date() }),
  update: async () => undefined,
  remove: async () => false,
} satisfies NotesService;

describe("notes controller", () => {
  const client = createTestClient(notesController, { context: { notesService } });

  test("lists notes for a signed-in caller", async () => {
    const res = await client.get("/api/notes", { headers });

    expect(res.status).toBe(200);
    expect(await res.json()).toEqual([{ id: "1", title: "stub", content: "" }]); // dates stripped by intercept
  });

  test("rejects anonymous callers", async () => {
    expect((await client.get("/api/notes")).status).toBe(401);
  });

  test("rejects invalid input", async () => {
    const res = await client.post("/api/notes", { headers, json: { title: "" } });

    expect(res.status).toBe(400);
  });

  test("answers a missing note with the error filter", async () => {
    expect((await client.get("/api/notes/nope", { headers })).status).toBe(404);
  });
});

The controller never opens a socket, a pool, or the edge stack: it is tested exactly as it is mounted, minus the app's startup. A satisfies NotesService stub keeps the fake honest — if the service grows a method, the test stops compiling.

Swap modules with mocks#

Because dependencies are values on the startup context, faking one is building a smaller app. mockModule(values) wraps any values as a real Rhythm module, so you include the stub exactly where a module would include the real thing, and mount the controller beside it:

TypeScript
import { Rhythm, include, mount } from "@rhythmjs/rhythm";
import { mockModule } from "@rhythmjs/testing/rhythm";

const testApp = new Rhythm({ name: "test" })
  .register(include(mockModule({ notesService }), ({ notesService }) => ({ notesService })))
  .use(mount(notesController));

const client = createTestClient(testApp);

A feature module that includes its infrastructure (include(databaseModule)) is not swapped this way, and does not need to be: the controller is tested with a stub service as above, and the module wiring is covered by the whole-app test below.

Test the real app as a smoke test. app.module.ts imports the database module, which reads DATABASE_URL when it loads, so give the test run a throwaway URL; the pool connects lazily, and none of these requests queries it. A test that creates the app stops it:

TypeScript
// src/app.spec.ts
import { afterAll, expect, test } from "bun:test";
import { createTestClient } from "@rhythmjs/testing/router";
import { appModule } from "./app.module";

afterAll(() => appModule.stop()); // the test created the pool, the test closes it

const client = createTestClient(appModule);

// rateLimit needs a client address; main.ts sets it from Bun's server, here we set it ourselves
const ask = (path: string) =>
  client.fetch(Object.assign(new Request(`http://localhost${path}`), { ip: "127.0.0.1" }));

test("the whole app answers", async () => {
  expect((await ask("/health/live")).status).toBe(200);
  expect((await ask("/api/notes")).status).toBe(401); // the notes module is mounted and protected
  expect((await ask("/openapi.json")).status).toBe(200);
});

test("an unknown path is a 404, not an empty 200", async () => {
  expect((await ask("/nope")).status).toBe(404); // the final guard from the security step
});

Where you are now#

You have built the whole arc: a controller on a Bun-native router, services and modules with explicit boundaries, validated input and output, typed configuration, a real database you open and close through the app, a hardened edge, a generated API document, production observability — and proof that it works. Everything was middleware, startup context, and modules on one small kernel.

From here, the package docs are the depth pass for each layer, the philosophy explains why the pieces are shaped this way, and the example repositories hold complete runnable versions of these patterns.