Testing@rhythmjs/testing
Drive HTTP without a server
A fetch-based client over the real middleware chain (verb helpers, JSON shorthands, startup context overrides) plus a runner for one HTTP middleware at a time.
Create a client#
createTestClient(appOrRouter, options?) from @rhythmjs/testing/router wraps a Rhythm HTTP app behind supertest-style helpers, or a bare RhythmRouter, which you can pass directly. Requests go straight through toFetchHandler: the real middleware chain runs, and responses are real Response objects. Relative paths resolve against baseUrl (default http://localhost).
import { createTestClient } from "@rhythmjs/testing/router";
const client = createTestClient(usersRouter);
const created = await client.post("/users", { json: { name: "Ada" } });
expect(created.status).toBe(201);
expect(await created.json()).toEqual({ id: 1, name: "Ada" });Requests and bodies#
Six verb helpers cover the routed methods (get, head, post, put, patch, delete), each taking a path and TestRequestOptions: headers (any HeadersInit), a raw body (anything a Response accepts), or json, which serializes the value and sets content-type: application/json unless you already did. For anything else (exotic methods, a prebuilt Request, custom RequestInit) the raw escape hatch is client.fetch(input, init?).
Startup context#
Pass context to supply or replace values for the test. It is typed as a Partial of the app's startup context and declared input (minus the HTTP base fields) and assigned onto every request's context, so a fake wins over a real value the app already provides. For a bare router it supplies the input the router requires, and the call fails to type-check when a bare router needs input and no context is given.
const client = createTestClient(app, { context: { db: fakeDb } });
const res = await client.get("/api/notes");
expect(res.status).toBe(200);There is no teardown(): if the test created a real resource (a database connection), close it yourself in afterAll.
A single HTTP middleware#
runHttpMiddleware(middleware, request?, extras?) tests one HTTP middleware without a router (to test a whole router this way, pass mount(router)): it seeds a real RhythmHttpContext from a path string or Request (default GET /), merges extras into the context for middleware that expects upstream state, runs the middleware, and resolves to { ctx, nextCalled, response }: the mutated context, whether next() ran, and the rendered Response.
import type { Middleware } from "@rhythmjs/rhythm";
import type { RhythmHttpContext } from "@rhythmjs/router/context";
import { runHttpMiddleware } from "@rhythmjs/testing/router";
import { error } from "@rhythmjs/router/response";
const guard: Middleware<RhythmHttpContext> = async (ctx, next) => {
if (ctx.request.headers.get("x-key") !== "secret") {
error(ctx, 401);
return;
}
await next();
};
const denied = await runHttpMiddleware(guard, "/private");
expect(denied.nextCalled).toBe(false);
expect(denied.response.status).toBe(401);
const requireRole =
(role: string): Middleware<RhythmHttpContext & { user: { roles: string[] } | null }> =>
async (ctx, next) => {
if (!ctx.user?.roles.includes(role)) return void error(ctx, 403);
await next();
};
const { response } = await runHttpMiddleware(
requireRole("admin"),
"/admin",
{ user: { roles: ["viewer"] } }, // extras: context from upstream middleware
);
expect(response.status).toBe(403);