test(helpers): add db, fetch, app, and auth test helpers

withTestDb sets up an in-memory SQLite handle with migrations
applied, swaps the production singleton via _setDbForTest, and
restores in a finally block. installFetchStub captures every
outbound request and throws if restored twice. requestApp wraps
Oak's app.handle so route tests can run without listen().
stubAuthenticate flips the server's authenticator indirection.
This commit is contained in:
Julien Calixte
2026-06-07 22:16:47 +02:00
parent 62a55fd3e4
commit c62936b819
4 changed files with 184 additions and 0 deletions

49
tests/_helpers/app.ts Normal file
View File

@@ -0,0 +1,49 @@
import type { Application } from "@oak/oak";
export type RequestOptions = {
method?: string;
path: string;
headers?: HeadersInit;
body?: unknown;
};
export type TestResponse = {
status: number;
headers: Headers;
text: string;
json: () => unknown;
};
export const requestApp = async (
app: Application,
opts: RequestOptions,
): Promise<TestResponse> => {
const method = opts.method ?? "GET";
const url = `http://test.local${opts.path}`;
const init: RequestInit = {
method,
headers: opts.headers,
};
if (opts.body !== undefined && method !== "GET" && method !== "HEAD") {
init.body = typeof opts.body === "string"
? opts.body
: JSON.stringify(opts.body);
const headers = new Headers(opts.headers);
if (!headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
init.headers = headers;
}
const req = new Request(url, init);
const res = await app.handle(req);
if (!res) {
throw new Error("app.handle returned undefined");
}
const text = await res.text();
return {
status: res.status,
headers: res.headers,
text,
json: () => JSON.parse(text),
};
};