route.test.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* @vitest-environment node */
  2. import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
  3. import fs from "node:fs/promises";
  4. import os from "node:os";
  5. import path from "node:path";
  6. vi.mock("@/lib/auth/session", () => ({
  7. getSession: vi.fn(),
  8. }));
  9. import { getSession } from "@/lib/auth/session";
  10. import { GET } from "./route.js";
  11. describe("GET /api/branches", () => {
  12. let tmpRoot;
  13. const originalNasRoot = process.env.NAS_ROOT_PATH;
  14. beforeEach(async () => {
  15. vi.clearAllMocks();
  16. tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), "api-branches-"));
  17. process.env.NAS_ROOT_PATH = tmpRoot;
  18. });
  19. afterEach(async () => {
  20. process.env.NAS_ROOT_PATH = originalNasRoot;
  21. if (tmpRoot) {
  22. await fs.rm(tmpRoot, { recursive: true, force: true });
  23. }
  24. });
  25. it("returns 401 when unauthenticated", async () => {
  26. getSession.mockResolvedValue(null);
  27. const res = await GET();
  28. expect(res.status).toBe(401);
  29. const body = await res.json();
  30. expect(body).toEqual({ error: "Unauthorized" });
  31. });
  32. it("returns only the own branch for branch users", async () => {
  33. getSession.mockResolvedValue({
  34. role: "branch",
  35. branchId: "NL01",
  36. userId: "u1",
  37. });
  38. await fs.mkdir(path.join(tmpRoot, "NL01"), { recursive: true });
  39. await fs.mkdir(path.join(tmpRoot, "NL02"), { recursive: true });
  40. const res = await GET();
  41. expect(res.status).toBe(200);
  42. const body = await res.json();
  43. expect(body.branches).toEqual(["NL01"]);
  44. });
  45. it("returns all branches for admin/dev users", async () => {
  46. getSession.mockResolvedValue({
  47. role: "admin",
  48. branchId: null,
  49. userId: "u2",
  50. });
  51. await fs.mkdir(path.join(tmpRoot, "NL01"), { recursive: true });
  52. await fs.mkdir(path.join(tmpRoot, "NL02"), { recursive: true });
  53. const res = await GET();
  54. expect(res.status).toBe(200);
  55. const body = await res.json();
  56. expect([...body.branches].sort()).toEqual(["NL01", "NL02"]);
  57. });
  58. it("returns 500 when NAS_ROOT_PATH is invalid (authenticated)", async () => {
  59. getSession.mockResolvedValue({
  60. role: "admin",
  61. branchId: null,
  62. userId: "u2",
  63. });
  64. process.env.NAS_ROOT_PATH = path.join(tmpRoot, "does-not-exist");
  65. const res = await GET();
  66. expect(res.status).toBe(500);
  67. const body = await res.json();
  68. expect(body).toEqual({ error: "Fehler beim Lesen der Niederlassungen" });
  69. });
  70. });