route.test.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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, dynamic } 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('exports dynamic="force-dynamic" (RHL-006)', () => {
  26. expect(dynamic).toBe("force-dynamic");
  27. });
  28. it("reports db=ok and nas with entries when both are healthy", async () => {
  29. mockedGetDb.mockResolvedValue({
  30. command: vi.fn().mockResolvedValue({ ok: 1 }),
  31. });
  32. mockedReaddir.mockResolvedValue(["NL01", "NL02"]);
  33. const req = new Request("http://localhost/api/health");
  34. const res = await getHealth(req);
  35. expect(res.status).toBe(200);
  36. const body = await res.json();
  37. expect(body.db).toBe("ok");
  38. expect(body.nas.path).toBe(
  39. process.env.NAS_ROOT_PATH || "/mnt/niederlassungen"
  40. );
  41. expect(body.nas.entriesSample).toEqual(["NL01", "NL02"]);
  42. });
  43. it("reports db error when getDb throws", async () => {
  44. mockedGetDb.mockRejectedValue(new Error("DB down"));
  45. mockedReaddir.mockResolvedValue(["NL01"]);
  46. const req = new Request("http://localhost/api/health");
  47. const res = await getHealth(req);
  48. const body = await res.json();
  49. expect(body.db).toBe("error: DB down");
  50. // NAS is still ok in this scenario
  51. expect(body.nas.entriesSample).toEqual(["NL01"]);
  52. });
  53. it("reports nas error when readdir fails", async () => {
  54. mockedGetDb.mockResolvedValue({
  55. command: vi.fn().mockResolvedValue({ ok: 1 }),
  56. });
  57. mockedReaddir.mockRejectedValue(new Error("ENOENT"));
  58. const req = new Request("http://localhost/api/health");
  59. const res = await getHealth(req);
  60. const body = await res.json();
  61. expect(body.db).toBe("ok");
  62. expect(body.nas).toBe("error: ENOENT");
  63. });
  64. });