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 => { 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), }; };