route.test.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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({
  31. error: { message: "Unauthorized", code: "AUTH_UNAUTHENTICATED" },
  32. });
  33. });
  34. it("returns only the own branch for branch users", async () => {
  35. getSession.mockResolvedValue({
  36. role: "branch",
  37. branchId: "NL01",
  38. userId: "u1",
  39. });
  40. await fs.mkdir(path.join(tmpRoot, "NL01"), { recursive: true });
  41. await fs.mkdir(path.join(tmpRoot, "NL02"), { recursive: true });
  42. const res = await GET();
  43. expect(res.status).toBe(200);
  44. const body = await res.json();
  45. expect(body.branches).toEqual(["NL01"]);
  46. });
  47. it("returns all branches for admin/dev users", async () => {
  48. getSession.mockResolvedValue({
  49. role: "admin",
  50. branchId: null,
  51. userId: "u2",
  52. });
  53. await fs.mkdir(path.join(tmpRoot, "NL01"), { recursive: true });
  54. await fs.mkdir(path.join(tmpRoot, "NL02"), { recursive: true });
  55. const res = await GET();
  56. expect(res.status).toBe(200);
  57. const body = await res.json();
  58. expect([...body.branches].sort()).toEqual(["NL01", "NL02"]);
  59. });
  60. it("returns 500 when NAS_ROOT_PATH is invalid (authenticated)", async () => {
  61. getSession.mockResolvedValue({
  62. role: "admin",
  63. branchId: null,
  64. userId: "u2",
  65. });
  66. process.env.NAS_ROOT_PATH = path.join(tmpRoot, "does-not-exist");
  67. const res = await GET();
  68. expect(res.status).toBe(500);
  69. const body = await res.json();
  70. expect(body).toEqual({
  71. error: { message: "Internal server error", code: "FS_STORAGE_ERROR" },
  72. });
  73. });
  74. });