import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; import { get } from "../src/user"; describe("user.get", () => { const originalFetch = globalThis.fetch; beforeEach(() => { // Reset mocks each test and isolate IDs to avoid cache collisions. mock.restore(); }); afterEach(() => { globalThis.fetch = originalFetch; }); test("fetches and returns user data", async () => { const fetchMock = mock(async () => { return { json: async () => ({ status: "ok", username: "alice", public_key: "pub", user_id: 9001, iota_id: 1, sub_level: 0, sub_end: 0, display: "Alice", status_message: "hi", about: "about", }), } as Response; }); globalThis.fetch = fetchMock as typeof fetch; const result = await get(9001); expect(result?.username).toBe("alice"); expect(fetchMock).toHaveBeenCalledTimes(1); }); test("returns cached value for repeated user id", async () => { const fetchMock = mock(async () => { return { json: async () => ({ status: "ok", username: "bob", public_key: "pub2", user_id: 9002, iota_id: 1, sub_level: 0, sub_end: 0, display: "Bob", status_message: "hi", about: "about", }), } as Response; }); globalThis.fetch = fetchMock as typeof fetch; const first = await get(9002); const second = await get(9002); expect(first?.username).toBe("bob"); expect(second?.username).toBe("bob"); expect(fetchMock).toHaveBeenCalledTimes(1); }); test("returns undefined when fetch fails", async () => { const fetchMock = mock(async () => { throw new Error("network down"); }); globalThis.fetch = fetchMock as typeof fetch; const result = await get(9003); expect(result).toBeUndefined(); expect(fetchMock).toHaveBeenCalledTimes(1); }); });