import { afterEach, describe, expect, it, vi } from "vitest"; import { _resetItadWarning, getItadId, itadFetch } from "@/lib/game/itad"; import { toIsoDate } from "@/lib/game/game-format"; afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); _resetItadWarning(); }); describe("toIsoDate", () => { it("converts unix seconds to ISO dates", () => { expect(toIsoDate(1705276800)).toBe("2024-01-15"); }); it("returns null for missing values", () => { expect(toIsoDate(undefined)).toBeNull(); expect(toIsoDate(0)).toBeNull(); }); }); describe("itadFetch", () => { it("returns null without an API key and without fetching", async () => { vi.stubGlobal("process", { ...process, env: {} }); const fetchMock = vi.fn(); vi.stubGlobal("fetch", fetchMock); await expect(itadFetch("/games/info/v2")).resolves.toBeNull(); expect(fetchMock).not.toHaveBeenCalled(); }); it("returns data on success and null on HTTP error", async () => { vi.stubGlobal("process", { ...process, env: { ITAD_API_KEY: "k" } }); vi.stubGlobal( "fetch", vi.fn(async () => ({ ok: true, json: async () => ({ id: "1" }) }) as Response), ); await expect(itadFetch("/games/info/v2")).resolves.toEqual({ id: "1" }); vi.stubGlobal( "fetch", vi.fn(async () => { throw new Error("down"); }), ); await expect(itadFetch("/games/info/v2")).resolves.toBeNull(); vi.stubGlobal( "fetch", vi.fn(async () => ({ ok: false, status: 429 }) as Response), ); await expect(itadFetch("/games/info/v2")).resolves.toBeNull(); }); }); describe("getItadId", () => { it("matches normalized titles", async () => { vi.stubGlobal("process", { ...process, env: { ITAD_API_KEY: "k" } }); vi.stubGlobal( "fetch", vi.fn( async () => ({ ok: true, json: async () => [{ id: "7", title: "Elden Ring" }], }) as Response, ), ); await expect(getItadId("ELDEN RING")).resolves.toBe("7"); await expect(getItadId("Unknown")).resolves.toBeNull(); }); });