import { describe, it, expect, beforeEach, afterEach } from "vitest"; import { resetWebMetricsForTests } from "~/lib/metrics/registry"; import { loader as metricsLoader } from "./api.metrics"; const TOKEN = "z".repeat(64); let originalEnabled: string | undefined; let originalToken: string | undefined; beforeEach(() => { resetWebMetricsForTests(); originalEnabled = process.env.METRICS_ENABLED; originalToken = process.env.METRICS_TOKEN; }); afterEach(() => { if (originalEnabled === undefined) delete process.env.METRICS_ENABLED; else process.env.METRICS_ENABLED = originalEnabled; if (originalToken === undefined) delete process.env.METRICS_TOKEN; else process.env.METRICS_TOKEN = originalToken; resetWebMetricsForTests(); }); function callLoader(headers: Record = {}): ReturnType { const request = new Request("http://localhost/api/metrics", { headers }); return metricsLoader({ request, params: {}, context: {} } as never); } describe("api.metrics loader", () => { it("returns 404 when METRICS_ENABLED is not 'true'", async () => { delete process.env.METRICS_ENABLED; const res = await callLoader(); expect(res.status).toBe(404); }); it("returns 500 when token unset", async () => { process.env.METRICS_ENABLED = "true"; delete process.env.METRICS_TOKEN; const res = await callLoader(); expect(res.status).toBe(500); }); it("returns 401 without authorization", async () => { process.env.METRICS_ENABLED = "true"; process.env.METRICS_TOKEN = TOKEN; const res = await callLoader(); expect(res.status).toBe(401); }); it("returns 200 + prom text with valid bearer token", async () => { process.env.METRICS_ENABLED = "true"; process.env.METRICS_TOKEN = TOKEN; const res = await callLoader({ authorization: `Bearer ${TOKEN}` }); expect(res.status).toBe(200); expect(res.headers.get("content-type")).toContain("text/plain"); const body = await res.text(); expect(body).toMatch(/# HELP/); }); });