import { describe, it, expect, beforeEach, vi } from "vitest"; const h = vi.hoisted(() => { const store = new Map(); const setSpy = vi.fn(); return { store, setSpy }; }); vi.mock("next/headers", () => ({ cookies: async () => ({ get: (n: string) => (h.store.has(n) ? { name: n, value: h.store.get(n)! } : undefined), set: (name: string, value: string, opts: unknown) => { h.store.set(name, value); h.setSpy(name, value, opts); }, delete: (n: string) => { h.store.delete(n); }, }), })); import { encodeSession, decodeSession } from "@/app/lib/sessionCodec"; import { setSession, readSession, getToken, clearSession } from "./session"; beforeEach(() => { h.store.clear(); h.setSpy.mockClear(); }); describe("sessionCodec", () => { it("round-trips session data", () => { const data = { token: "jwt", member: { memberCode: "73774867", name: "Tëst Lim" }, resetRequired: false }; expect(decodeSession(encodeSession(data))).toEqual(data); }); it("returns null for garbage", () => { expect(decodeSession("not-json")).toBeNull(); }); }); describe("session cookie I/O", () => { it("sets an httpOnly, Secure, SameSite=Lax cookie", async () => { await setSession({ memberCode: "73774867", name: "Test" }, "jwt-xyz"); expect(h.setSpy).toHaveBeenCalledTimes(1); const [name, , opts] = h.setSpy.mock.calls[0]; expect(name).toBe("te_session"); expect(opts).toMatchObject({ httpOnly: true, secure: true, sameSite: "lax", path: "/" }); }); it("reads the session back", async () => { await setSession({ memberCode: "73774867", name: "Test" }, "jwt-xyz"); const s = await readSession(); expect(s?.token).toBe("jwt-xyz"); expect(s?.member.memberCode).toBe("73774867"); expect(await getToken()).toBe("jwt-xyz"); }); it("returns null when no cookie is present", async () => { expect(await readSession()).toBeNull(); expect(await getToken()).toBeNull(); }); it("clears the session", async () => { await setSession({ memberCode: "1", name: "A" }, "jwt"); await clearSession(); expect(await readSession()).toBeNull(); }); }); describe("phoneVerifyRequired flag", () => { it("persists and reads back phoneVerifyRequired", async () => { await setSession({ memberCode: "1", name: "A" }, "jwt", false, true); expect((await readSession())?.phoneVerifyRequired).toBe(true); }); it("defaults phoneVerifyRequired to false", async () => { await setSession({ memberCode: "1", name: "A" }, "jwt"); expect((await readSession())?.phoneVerifyRequired).toBe(false); }); it("codec round-trips phoneVerifyRequired", () => { const data = { token: "jwt", member: { memberCode: "1", name: "A" }, resetRequired: false, phoneVerifyRequired: true }; expect(decodeSession(encodeSession(data))).toEqual(data); }); });