import { afterEach, beforeEach, describe, expect, mock, setSystemTime, test, } from "bun:test"; import type { Context } from "hono"; const mockQueryRaw = mock(); mock.module("../src/lib/prisma", () => ({ prisma: { $queryRaw: mockQueryRaw }, })); const { getMonthlyLast } = await import( "../src/modules/quotes/handlers/getMonthlyLast" ); const { cache } = await import("../src/lib/cache"); type Row = { month: string; type: string; buy: number }; const originalFetch = globalThis.fetch; function fakeCasaData(casa: string): unknown[] { // Un único día por mes, cubriendo de 2025-10 a 2026-10. const months = [ "2025-10", "2025-11", "2025-12", "2026-01", "2026-02", "2026-03", "2026-04", "2026-05", "2026-06", "2026-07", "2026-08", "2026-09", "2026-10", ]; return months.map((m, i) => ({ casa, fecha: `${m}-15`, compra: 1000 + i, venta: 1010 + i, })); } function mockExternalApi() { globalThis.fetch = mock(async (url: string | URL) => { const casa = String(url).split("/").pop() ?? ""; return { ok: true, status: 200, json: async () => fakeCasaData(casa), } as unknown as Response; }) as unknown as typeof fetch; } const context = { json: (data: unknown) => data } as unknown as Context; beforeEach(() => { mockQueryRaw.mockClear(); cache.clear(); setSystemTime(new Date("2026-10-14T12:00:00Z")); }); afterEach(() => { globalThis.fetch = originalFetch; setSystemTime(); }); describe("getMonthlyLast", () => { test("trae 13 meses (12 a mostrar + 1 base) y no descarta el mes en curso del fallback externo", async () => { mockQueryRaw.mockResolvedValue([]); mockExternalApi(); const rows = (await getMonthlyLast(context)) as Row[]; const months = [...new Set(rows.map((r) => r.month))].sort(); expect(months).toEqual([ "2025-10", "2025-11", "2025-12", "2026-01", "2026-02", "2026-03", "2026-04", "2026-05", "2026-06", "2026-07", "2026-08", "2026-09", "2026-10", ]); // Regresión: "2026-10-14" > "2026-10" siempre daba true y el mes más // reciente nunca llegaba desde la API externa. expect(rows).toContainEqual({ month: "2026-10", type: "BELO", buy: 1012, source: "external", }); }); test("usa la DB cuando el dato existe y no pega a la API externa", async () => { const dbRows: Row[] = []; const months = [ "2025-10", "2025-11", "2025-12", "2026-01", "2026-02", "2026-03", "2026-04", "2026-05", "2026-06", "2026-07", "2026-08", "2026-09", "2026-10", ]; for (const month of months) { for (const type of ["BELO", "BLUE", "BNA"]) { dbRows.push({ month, type, buy: 500 }); } } mockQueryRaw.mockResolvedValue(dbRows); const fetchMock = mock(); globalThis.fetch = fetchMock as unknown as typeof fetch; const rows = (await getMonthlyLast(context)) as Row[]; expect(fetchMock).not.toHaveBeenCalled(); expect(rows.every((r) => r.source === "db")).toBe(true); expect(rows).toHaveLength(13 * 3); }); });