import { describe, it, expect, vi, beforeEach } from "vitest"; const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); import { POST } from "./route"; function req(body: unknown) { return new Request("http://localhost/api/auth/change-password", { method: "POST", body: JSON.stringify(body), }) as unknown as Parameters[0]; } beforeEach(() => { mocks.callMobileApi.mockReset(); mocks.getToken.mockReset(); }); describe("POST /api/auth/change-password", () => { it("returns 401 when there is no session", async () => { mocks.getToken.mockResolvedValue(null); const res = await POST(req({})); expect(res.status).toBe(401); expect(mocks.callMobileApi).not.toHaveBeenCalled(); }); it("forwards only the three password fields and answers 204", async () => { mocks.getToken.mockResolvedValue("jwt-abc"); mocks.callMobileApi.mockResolvedValue({ ok: true, data: null }); const res = await POST(req({ currentPassword: "Old#1", newPassword: "New#1", confirmPassword: "New#1", extra: 1 })); expect(res.status).toBe(204); expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/auth/change-password", { method: "POST", body: { currentPassword: "Old#1", newPassword: "New#1", confirmPassword: "New#1" }, token: "jwt-abc", headers: {}, }); }); it("passes a refusal through with its code", async () => { mocks.getToken.mockResolvedValue("jwt-abc"); mocks.callMobileApi.mockResolvedValue({ ok: false, status: 400, error: "Current password is wrong", code: "CURRENT_PASSWORD_WRONG" }); const res = await POST(req({})); expect(res.status).toBe(400); expect(await res.json()).toMatchObject({ error: "Current password is wrong", code: "CURRENT_PASSWORD_WRONG" }); }); });