/** * Tests for GET /api/dashboard * * Covers: * - 404 when no user found * - response shape: user, todayLog, categorySkills, recentActivities, weeklyLogs * - todayLog: null when no log for today * - todayLog: populated when a today log exists * - xpToNextLevel computed from xpForLevel(user.level + 1) * - categorySkills mapped correctly from user.categorySkills * - categorySkills include lastPlayedAt per-category (null when no activity) * - recentActivities mapped correctly (last 10) * - weeklyLogs mapped correctly (last 7) */ import { describe, it, expect, vi, beforeEach } from "vitest"; import { NextRequest } from "next/server"; // --------------------------------------------------------------------------- // Mock prisma // --------------------------------------------------------------------------- const mockUserFindFirst = vi.fn(); const mockDailyLogFindFirst = vi.fn(); const mockActivityFindMany = vi.fn(); const mockActivityGroupBy = vi.fn(); const mockDailyLogFindMany = vi.fn(); vi.mock("@/lib/db", () => ({ prisma: { user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) }, dailyLog: { findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args), findMany: (...args: unknown[]) => mockDailyLogFindMany(...args), }, activity: { findMany: (...args: unknown[]) => mockActivityFindMany(...args), groupBy: (...args: unknown[]) => mockActivityGroupBy(...args), }, }, })); import { GET } from "../route"; // --------------------------------------------------------------------------- // Fixtures // --------------------------------------------------------------------------- const baseUser = { id: 1, name: "Player One", level: 5, totalXp: 1250, currentXp: 250, title: "Apprentice", dailyGoalXp: 100, streak: 3, longestStreak: 7, streakFreezes: 1, categorySkills: [ { category: "CHESS", level: 2, totalXp: 300, currentXp: 50, xpToNext: 150 }, { category: "FEYNMAN", level: 1, totalXp: 100, currentXp: 100, xpToNext: 100 }, ], }; const baseDailyLog = { xpEarned: 80, activityCount: 3, goalMet: false, }; const baseActivities = [ { id: 10, category: "CHESS", exerciseType: "chess-puzzle", description: "Solved a puzzle", totalXp: 40, isCriticalHit: false, createdAt: new Date("2026-03-24T10:00:00Z"), }, { id: 9, category: "FEYNMAN", exerciseType: "explain", description: "Explained quantum entanglement", totalXp: 30, isCriticalHit: true, createdAt: new Date("2026-03-24T09:00:00Z"), }, ]; const baseWeeklyLogs = [ { date: new Date("2026-03-24T00:00:00Z"), xpEarned: 80, activityCount: 3, goalMet: false }, { date: new Date("2026-03-23T00:00:00Z"), xpEarned: 120, activityCount: 5, goalMet: true }, ]; /** Default groupBy result: chess played 2026-03-24, feynman played 2026-03-22 */ const baseGroupByRows = [ { category: "chess", _max: { createdAt: new Date("2026-03-24T10:00:00Z") } }, { category: "feynman", _max: { createdAt: new Date("2026-03-22T08:00:00Z") } }, ]; function makeGet(): NextRequest { return new NextRequest("http://localhost/api/dashboard"); } async function json(res: Response): Promise { return res.json(); } // --------------------------------------------------------------------------- // Tests // --------------------------------------------------------------------------- describe("GET /api/dashboard", () => { beforeEach(() => { vi.clearAllMocks(); mockActivityFindMany.mockResolvedValue(baseActivities); mockActivityGroupBy.mockResolvedValue(baseGroupByRows); mockDailyLogFindMany.mockResolvedValue(baseWeeklyLogs); mockDailyLogFindFirst.mockResolvedValue(null); }); it("returns 404 when no user found", async () => { mockUserFindFirst.mockResolvedValue(null); const res = await GET(makeGet()); expect(res.status).toBe(404); const body = await json(res) as Record; expect(body.error).toBeDefined(); }); it("returns 200 with full response shape when user exists", async () => { mockUserFindFirst.mockResolvedValue(baseUser); mockDailyLogFindFirst.mockResolvedValue(baseDailyLog); const res = await GET(makeGet()); expect(res.status).toBe(200); const body = await json(res) as Record; expect(body).toHaveProperty("user"); expect(body).toHaveProperty("todayLog"); expect(body).toHaveProperty("categorySkills"); expect(body).toHaveProperty("recentActivities"); expect(body).toHaveProperty("weeklyLogs"); }); it("returns todayLog as null when no log exists for today", async () => { mockUserFindFirst.mockResolvedValue(baseUser); mockDailyLogFindFirst.mockResolvedValue(null); const res = await GET(makeGet()); const body = await json(res) as Record; expect(body.todayLog).toBeNull(); }); it("returns todayLog with xpEarned, activityCount, goalMet when log exists", async () => { mockUserFindFirst.mockResolvedValue(baseUser); mockDailyLogFindFirst.mockResolvedValue(baseDailyLog); const res = await GET(makeGet()); const body = await json(res) as Record; const log = body.todayLog as Record; expect(log.xpEarned).toBe(80); expect(log.activityCount).toBe(3); expect(log.goalMet).toBe(false); }); it("returns user fields including level and streak", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const res = await GET(makeGet()); const body = await json(res) as Record; const user = body.user as Record; expect(user.id).toBe(1); expect(user.name).toBe("Player One"); expect(user.level).toBe(5); expect(user.totalXp).toBe(1250); expect(user.currentXp).toBe(250); expect(user.streak).toBe(3); expect(user.longestStreak).toBe(7); expect(user.streakFreezes).toBe(1); expect(user.dailyGoalXp).toBe(100); expect(user.title).toBe("Apprentice"); }); it("computes xpToNextLevel via xpForLevel(level + 1)", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const res = await GET(makeGet()); const body = await json(res) as Record; const user = body.user as Record; // xpForLevel(6) — just verify it's a positive number expect(typeof user.xpToNextLevel).toBe("number"); expect(user.xpToNextLevel as number).toBeGreaterThan(0); }); it("maps categorySkills correctly (core fields)", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const res = await GET(makeGet()); const body = await json(res) as Record; const skills = body.categorySkills as Array>; expect(skills).toHaveLength(2); expect(skills[0]).toMatchObject({ category: "CHESS", level: 2, totalXp: 300, currentXp: 50, xpToNext: 150, }); expect(skills[1]).toMatchObject({ category: "FEYNMAN", level: 1, }); }); it("maps recentActivities with all required fields", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const res = await GET(makeGet()); const body = await json(res) as Record; const activities = body.recentActivities as Array>; expect(activities).toHaveLength(2); expect(activities[0]).toMatchObject({ id: 10, category: "CHESS", exerciseType: "chess-puzzle", description: "Solved a puzzle", totalXp: 40, isCriticalHit: false, }); expect(activities[0]).toHaveProperty("createdAt"); }); it("maps weeklyLogs correctly", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const res = await GET(makeGet()); const body = await json(res) as Record; const logs = body.weeklyLogs as Array>; expect(logs).toHaveLength(2); expect(logs[0]).toMatchObject({ xpEarned: 80, activityCount: 3, goalMet: false, }); expect(logs[1]).toMatchObject({ xpEarned: 120, activityCount: 5, goalMet: true, }); }); it("queries daily log with today UTC boundaries", async () => { mockUserFindFirst.mockResolvedValue(baseUser); mockDailyLogFindFirst.mockResolvedValue(null); await GET(makeGet()); expect(mockDailyLogFindFirst).toHaveBeenCalledWith( expect.objectContaining({ where: expect.objectContaining({ userId: 1, date: expect.objectContaining({ gte: expect.any(Date), lt: expect.any(Date), }), }), }), ); }); it("queries activities with take: 10 ordered desc", async () => { mockUserFindFirst.mockResolvedValue(baseUser); await GET(makeGet()); expect(mockActivityFindMany).toHaveBeenCalledWith( expect.objectContaining({ where: { userId: 1 }, orderBy: { createdAt: "desc" }, take: 10, }), ); }); it("queries weekly logs with take: 7 ordered desc", async () => { mockUserFindFirst.mockResolvedValue(baseUser); await GET(makeGet()); expect(mockDailyLogFindMany).toHaveBeenCalledWith( expect.objectContaining({ where: { userId: 1 }, orderBy: { date: "desc" }, take: 7, }), ); }); it("handles empty categorySkills array", async () => { mockUserFindFirst.mockResolvedValue({ ...baseUser, categorySkills: [] }); const res = await GET(makeGet()); const body = await json(res) as Record; expect(body.categorySkills).toEqual([]); }); it("handles empty activities array", async () => { mockUserFindFirst.mockResolvedValue(baseUser); mockActivityFindMany.mockResolvedValue([]); const res = await GET(makeGet()); const body = await json(res) as Record; expect(body.recentActivities).toEqual([]); }); it("handles empty weeklyLogs array", async () => { mockUserFindFirst.mockResolvedValue(baseUser); mockDailyLogFindMany.mockResolvedValue([]); const res = await GET(makeGet()); const body = await json(res) as Record; expect(body.weeklyLogs).toEqual([]); }); it("propagates DB errors as 500", async () => { mockUserFindFirst.mockRejectedValue(new Error("DB connection failed")); const res = await GET(makeGet()); expect(res.status).toBe(500); }); // ── lastPlayedAt ─────────────────────────────────────────────────────────── describe("lastPlayedAt per category", () => { it("categorySkills include a lastPlayedAt field", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const res = await GET(makeGet()); const body = await json(res) as Record; const skills = body.categorySkills as Array>; expect(skills[0]).toHaveProperty("lastPlayedAt"); expect(skills[1]).toHaveProperty("lastPlayedAt"); }); it("lastPlayedAt is an ISO string when activity exists for that category", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const playedAt = new Date("2026-03-24T10:00:00Z"); mockActivityGroupBy.mockResolvedValue([ { category: "chess", _max: { createdAt: playedAt } }, ]); const res = await GET(makeGet()); const body = await json(res) as Record; const skills = body.categorySkills as Array>; const chess = skills.find((s) => s.category === "CHESS"); expect(chess?.lastPlayedAt).toBe(playedAt.toISOString()); }); it("lastPlayedAt is null when no activity exists for a category", async () => { mockUserFindFirst.mockResolvedValue(baseUser); // groupBy returns nothing for feynman — feynman has never been played mockActivityGroupBy.mockResolvedValue([ { category: "chess", _max: { createdAt: new Date("2026-03-24T10:00:00Z") } }, ]); const res = await GET(makeGet()); const body = await json(res) as Record; const skills = body.categorySkills as Array>; const feynman = skills.find((s) => s.category === "FEYNMAN"); expect(feynman?.lastPlayedAt).toBeNull(); }); it("lastPlayedAt is null when groupBy returns _max.createdAt = null", async () => { mockUserFindFirst.mockResolvedValue(baseUser); mockActivityGroupBy.mockResolvedValue([ { category: "chess", _max: { createdAt: null } }, ]); const res = await GET(makeGet()); const body = await json(res) as Record; const skills = body.categorySkills as Array>; const chess = skills.find((s) => s.category === "CHESS"); expect(chess?.lastPlayedAt).toBeNull(); }); it("lastPlayedAt matching is case-insensitive (category stored as uppercase in DB)", async () => { mockUserFindFirst.mockResolvedValue(baseUser); // DB stores category as "CHESS" but groupBy returns lowercase "chess" const playedAt = new Date("2026-03-25T12:00:00Z"); mockActivityGroupBy.mockResolvedValue([ { category: "chess", _max: { createdAt: playedAt } }, { category: "feynman", _max: { createdAt: new Date("2026-03-23T09:00:00Z") } }, ]); const res = await GET(makeGet()); const body = await json(res) as Record; const skills = body.categorySkills as Array>; const chess = skills.find((s) => s.category === "CHESS"); expect(chess?.lastPlayedAt).toBe(playedAt.toISOString()); }); it("all categories get lastPlayedAt when groupBy has an entry for each", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const d1 = new Date("2026-03-26T10:00:00Z"); const d2 = new Date("2026-03-25T11:00:00Z"); mockActivityGroupBy.mockResolvedValue([ { category: "chess", _max: { createdAt: d1 } }, { category: "feynman", _max: { createdAt: d2 } }, ]); const res = await GET(makeGet()); const body = await json(res) as Record; const skills = body.categorySkills as Array>; const chess = skills.find((s) => s.category === "CHESS"); const feynman = skills.find((s) => s.category === "FEYNMAN"); expect(chess?.lastPlayedAt).toBe(d1.toISOString()); expect(feynman?.lastPlayedAt).toBe(d2.toISOString()); }); it("when groupBy returns empty array, all categories have lastPlayedAt = null", async () => { mockUserFindFirst.mockResolvedValue(baseUser); mockActivityGroupBy.mockResolvedValue([]); const res = await GET(makeGet()); const body = await json(res) as Record; const skills = body.categorySkills as Array>; for (const skill of skills) { expect(skill.lastPlayedAt).toBeNull(); } }); it("calls activity.groupBy with userId: 1 and _max createdAt", async () => { mockUserFindFirst.mockResolvedValue(baseUser); await GET(makeGet()); expect(mockActivityGroupBy).toHaveBeenCalledWith( expect.objectContaining({ by: ["category"], where: { userId: 1 }, _max: { createdAt: true }, }), ); }); }); });