| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- // app/api/health/route.test.js
- import { describe, it, expect, vi, beforeEach } from "vitest";
- // Mock the DB helper and fs.promises before importing the route
- vi.mock("@/lib/db", () => {
- return {
- getDb: vi.fn(),
- };
- });
- vi.mock("fs/promises", () => {
- return {
- default: {
- readdir: vi.fn(),
- },
- };
- });
- import { GET as getHealth } from "./route.js";
- import { getDb } from "@/lib/db";
- import fs from "fs/promises";
- const mockedGetDb = getDb;
- const mockedReaddir = fs.readdir;
- beforeEach(() => {
- vi.resetAllMocks();
- });
- describe("GET /api/health", () => {
- it("reports db=ok and nas with entries when both are healthy", async () => {
- mockedGetDb.mockResolvedValue({
- command: vi.fn().mockResolvedValue({ ok: 1 }),
- });
- mockedReaddir.mockResolvedValue(["NL01", "NL02"]);
- const req = new Request("http://localhost/api/health");
- const res = await getHealth(req);
- expect(res.status).toBe(200);
- const body = await res.json();
- expect(body.db).toBe("ok");
- expect(body.nas.path).toBe(
- process.env.NAS_ROOT_PATH || "/mnt/niederlassungen"
- );
- expect(body.nas.entriesSample).toEqual(["NL01", "NL02"]);
- });
- it("reports db error when getDb throws", async () => {
- mockedGetDb.mockRejectedValue(new Error("DB down"));
- mockedReaddir.mockResolvedValue(["NL01"]);
- const req = new Request("http://localhost/api/health");
- const res = await getHealth(req);
- const body = await res.json();
- expect(body.db).toBe("error: DB down");
- // NAS is still ok in this scenario
- expect(body.nas.entriesSample).toEqual(["NL01"]);
- });
- it("reports nas error when readdir fails", async () => {
- mockedGetDb.mockResolvedValue({
- command: vi.fn().mockResolvedValue({ ok: 1 }),
- });
- mockedReaddir.mockRejectedValue(new Error("ENOENT"));
- const req = new Request("http://localhost/api/health");
- const res = await getHealth(req);
- const body = await res.json();
- expect(body.db).toBe("ok");
- expect(body.nas).toBe("error: ENOENT");
- });
- });
|