route.test.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // app/api/health/route.test.js
  2. import { describe, it, expect, vi, beforeEach } from "vitest";
  3. // Mock the DB helper and fs.promises before importing the route
  4. vi.mock("@/lib/db", () => {
  5. return {
  6. getDb: vi.fn(),
  7. };
  8. });
  9. vi.mock("fs/promises", () => {
  10. return {
  11. default: {
  12. readdir: vi.fn(),
  13. },
  14. };
  15. });
  16. import { GET as getHealth } from "./route.js";
  17. import { getDb } from "@/lib/db";
  18. import fs from "fs/promises";
  19. const mockedGetDb = getDb;
  20. const mockedReaddir = fs.readdir;
  21. beforeEach(() => {
  22. vi.resetAllMocks();
  23. });
  24. describe("GET /api/health", () => {
  25. it("reports db=ok and nas with entries when both are healthy", async () => {
  26. mockedGetDb.mockResolvedValue({
  27. command: vi.fn().mockResolvedValue({ ok: 1 }),
  28. });
  29. mockedReaddir.mockResolvedValue(["NL01", "NL02"]);
  30. const req = new Request("http://localhost/api/health");
  31. const res = await getHealth(req);
  32. expect(res.status).toBe(200);
  33. const body = await res.json();
  34. expect(body.db).toBe("ok");
  35. expect(body.nas.path).toBe(
  36. process.env.NAS_ROOT_PATH || "/mnt/niederlassungen"
  37. );
  38. expect(body.nas.entriesSample).toEqual(["NL01", "NL02"]);
  39. });
  40. it("reports db error when getDb throws", async () => {
  41. mockedGetDb.mockRejectedValue(new Error("DB down"));
  42. mockedReaddir.mockResolvedValue(["NL01"]);
  43. const req = new Request("http://localhost/api/health");
  44. const res = await getHealth(req);
  45. const body = await res.json();
  46. expect(body.db).toBe("error: DB down");
  47. // NAS is still ok in this scenario
  48. expect(body.nas.entriesSample).toEqual(["NL01"]);
  49. });
  50. it("reports nas error when readdir fails", async () => {
  51. mockedGetDb.mockResolvedValue({
  52. command: vi.fn().mockResolvedValue({ ok: 1 }),
  53. });
  54. mockedReaddir.mockRejectedValue(new Error("ENOENT"));
  55. const req = new Request("http://localhost/api/health");
  56. const res = await getHealth(req);
  57. const body = await res.json();
  58. expect(body.db).toBe("ok");
  59. expect(body.nas).toBe("error: ENOENT");
  60. });
  61. });