/** * Tests for GET /api/profile * * Covers: * - 404 when no user found * - response shape: user, stats, categorySkills, skillTree, unlocks, chesscomStats, dailyActivity * - user fields: all fields including xpToNextLevel (computed) * - stats: totalExercises, totalTimeSecs, totalXpAllTime, exercisesByCat * - exercisesByCat: aggregated per category * - categorySkills: mapped correctly * - skillTree: all nodes with unlocked flag * - unlocked flag: true for nodes in user.unlocks, false otherwise * - unlocks: maps nodeId, nodeName, unlockedAt * - null durationSecs handled gracefully * - empty activities and nodes * - DB errors propagate as 500 * - Chess.com stats: null when chesscomUsername is null * - Chess.com stats: null when getPlayerStats returns null (unknown username) * - Chess.com stats: populated with ratings when chesscomUsername is set and API succeeds * - Chess.com stats: includes rapid, blitz, bullet, daily, best ratings, puzzle rush, tactics * - Chess.com stats: fields are null when time class is absent from API response * - getPlayerStats not called when chesscomUsername is null * - dailyActivity: included in response (empty when no logs) * - dailyActivity: maps date, xpEarned, activityCount, goalMet from daily logs * - dailyActivity: queries last 90 days (gte filter) */ import { describe, it, expect, vi, beforeEach } from "vitest"; import { NextRequest } from "next/server"; // --------------------------------------------------------------------------- // Mock prisma // --------------------------------------------------------------------------- const mockUserFindFirst = vi.fn(); const mockSkillTreeNodeFindMany = vi.fn(); const mockActivityFindMany = vi.fn(); const mockDailyLogFindMany = vi.fn(); vi.mock("@/lib/db", () => ({ prisma: { user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) }, skillTreeNode: { findMany: (...args: unknown[]) => mockSkillTreeNodeFindMany(...args) }, activity: { findMany: (...args: unknown[]) => mockActivityFindMany(...args) }, dailyLog: { findMany: (...args: unknown[]) => mockDailyLogFindMany(...args) }, }, })); // --------------------------------------------------------------------------- // Mock Chess.com client // --------------------------------------------------------------------------- const mockGetPlayerStats = vi.fn(); const mockGetBestRating = vi.fn(); vi.mock("@/lib/chesscom", () => ({ getPlayerStats: (...args: unknown[]) => mockGetPlayerStats(...args), getBestRating: (...args: unknown[]) => mockGetBestRating(...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: 10, streakFreezes: 2, lichessUsername: "player1", chesscomUsername: null, createdAt: new Date("2026-01-01T00:00:00Z"), categorySkills: [ { category: "CHESS", level: 2, totalXp: 300, currentXp: 50, xpToNext: 150 }, { category: "FEYNMAN", level: 1, totalXp: 100, currentXp: 100, xpToNext: 100 }, ], unlocks: [ { nodeId: 10, node: { name: "Chess Basics" }, unlockedAt: new Date("2026-02-01T00:00:00Z") }, ], }; const baseNodes = [ { id: 10, category: "CHESS", name: "Chess Basics", description: "Beginner chess concepts", levelRequired: 1, parentNodeId: null, nodeType: "skill" }, { id: 11, category: "CHESS", name: "Tactical Patterns", description: "Common tactics", levelRequired: 2, parentNodeId: 10, nodeType: "skill" }, { id: 20, category: "FEYNMAN", name: "Feynman Foundations", description: "Core Feynman method", levelRequired: 1, parentNodeId: null, nodeType: "skill" }, ]; const baseActivities = [ { category: "CHESS", durationSecs: 120, createdAt: new Date("2026-03-24T10:00:00Z"), totalXp: 40 }, { category: "CHESS", durationSecs: 90, createdAt: new Date("2026-03-23T09:00:00Z"), totalXp: 30 }, { category: "FEYNMAN", durationSecs: null, createdAt: new Date("2026-03-22T08:00:00Z"), totalXp: 50 }, ]; function makeGet(): NextRequest { return new NextRequest("http://localhost/api/profile"); } async function json(res: Response): Promise { return res.json(); } // --------------------------------------------------------------------------- // Tests // --------------------------------------------------------------------------- const baseDailyLogs = [ { date: new Date("2026-03-24T00:00:00Z"), xpEarned: 120, activityCount: 3, goalMet: true }, { date: new Date("2026-03-23T00:00:00Z"), xpEarned: 60, activityCount: 1, goalMet: false }, ]; describe("GET /api/profile", () => { beforeEach(() => { vi.clearAllMocks(); mockSkillTreeNodeFindMany.mockResolvedValue(baseNodes); mockActivityFindMany.mockResolvedValue(baseActivities); mockDailyLogFindMany.mockResolvedValue(baseDailyLogs); // Default: Chess.com not called (user has no chesscomUsername in baseUser) mockGetPlayerStats.mockResolvedValue(null); mockGetBestRating.mockReturnValue(null); }); it("returns 404 when no user found", async () => { mockUserFindFirst.mockResolvedValue(null); const res = await GET(makeGet()); expect(res.status).toBe(404); }); it("returns 200 with full response shape", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const res = await GET(makeGet()); expect(res.status).toBe(200); const body = await json(res) as Record; expect(body).toHaveProperty("user"); expect(body).toHaveProperty("stats"); expect(body).toHaveProperty("categorySkills"); expect(body).toHaveProperty("skillTree"); expect(body).toHaveProperty("unlocks"); expect(body).toHaveProperty("dailyActivity"); }); it("maps user fields correctly", 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.title).toBe("Apprentice"); expect(user.dailyGoalXp).toBe(100); expect(user.streak).toBe(3); expect(user.longestStreak).toBe(10); expect(user.streakFreezes).toBe(2); expect(user.lichessUsername).toBe("player1"); expect(user.chesscomUsername).toBeNull(); expect(user).toHaveProperty("createdAt"); }); 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; expect(typeof user.xpToNextLevel).toBe("number"); expect(user.xpToNextLevel as number).toBeGreaterThan(0); }); it("computes stats.totalExercises", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const res = await GET(makeGet()); const body = await json(res) as Record; const stats = body.stats as Record; expect(stats.totalExercises).toBe(3); }); it("computes stats.totalTimeSecs (null treated as 0)", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const res = await GET(makeGet()); const body = await json(res) as Record; const stats = body.stats as Record; // 120 + 90 + 0 (null) = 210 expect(stats.totalTimeSecs).toBe(210); }); it("computes stats.totalXpAllTime", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const res = await GET(makeGet()); const body = await json(res) as Record; const stats = body.stats as Record; // 40 + 30 + 50 = 120 expect(stats.totalXpAllTime).toBe(120); }); it("builds exercisesByCat per category", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const res = await GET(makeGet()); const body = await json(res) as Record; const stats = body.stats as Record; const byCat = stats.exercisesByCat as Record; expect(byCat.CHESS).toBe(2); expect(byCat.FEYNMAN).toBe(1); }); it("maps categorySkills correctly", 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, }); }); it("maps skill tree nodes with unlocked flag", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const res = await GET(makeGet()); const body = await json(res) as Record; const skillTree = body.skillTree as Array>; expect(skillTree).toHaveLength(3); // Node 10 is in user.unlocks — should be unlocked: true const node10 = skillTree.find((n) => n.id === 10); expect(node10?.unlocked).toBe(true); expect(node10?.name).toBe("Chess Basics"); expect(node10?.category).toBe("CHESS"); expect(node10?.levelRequired).toBe(1); expect(node10?.parentNodeId).toBeNull(); expect(node10?.nodeType).toBe("skill"); // Node 11 is not unlocked const node11 = skillTree.find((n) => n.id === 11); expect(node11?.unlocked).toBe(false); // Node 20 is not unlocked const node20 = skillTree.find((n) => n.id === 20); expect(node20?.unlocked).toBe(false); }); it("maps unlocks with nodeId, nodeName, unlockedAt", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const res = await GET(makeGet()); const body = await json(res) as Record; const unlocks = body.unlocks as Array>; expect(unlocks).toHaveLength(1); expect(unlocks[0].nodeId).toBe(10); expect(unlocks[0].nodeName).toBe("Chess Basics"); expect(unlocks[0]).toHaveProperty("unlockedAt"); }); it("handles empty activities gracefully", async () => { mockUserFindFirst.mockResolvedValue(baseUser); mockActivityFindMany.mockResolvedValue([]); const res = await GET(makeGet()); const body = await json(res) as Record; const stats = body.stats as Record; expect(stats.totalExercises).toBe(0); expect(stats.totalTimeSecs).toBe(0); expect(stats.totalXpAllTime).toBe(0); expect(stats.exercisesByCat).toEqual({}); }); it("handles empty skill tree nodes", async () => { mockUserFindFirst.mockResolvedValue(baseUser); mockSkillTreeNodeFindMany.mockResolvedValue([]); const res = await GET(makeGet()); const body = await json(res) as Record; expect(body.skillTree).toEqual([]); }); it("handles user with no unlocks", async () => { mockUserFindFirst.mockResolvedValue({ ...baseUser, unlocks: [] }); const res = await GET(makeGet()); const body = await json(res) as Record; const skillTree = body.skillTree as Array>; expect(body.unlocks).toEqual([]); // All nodes should be unlocked: false for (const node of skillTree) { expect(node.unlocked).toBe(false); } }); it("queries skill tree nodes ordered by category then levelRequired", async () => { mockUserFindFirst.mockResolvedValue(baseUser); await GET(makeGet()); expect(mockSkillTreeNodeFindMany).toHaveBeenCalledWith({ orderBy: [{ category: "asc" }, { levelRequired: "asc" }], }); }); it("queries activities selecting minimal fields", async () => { mockUserFindFirst.mockResolvedValue(baseUser); await GET(makeGet()); expect(mockActivityFindMany).toHaveBeenCalledWith( expect.objectContaining({ where: { userId: 1 }, select: expect.objectContaining({ category: true, durationSecs: true, totalXp: true, }), }), ); }); it("propagates DB errors as 500", async () => { mockUserFindFirst.mockRejectedValue(new Error("DB down")); const res = await GET(makeGet()); expect(res.status).toBe(500); }); // --------------------------------------------------------------------------- // Chess.com stats // --------------------------------------------------------------------------- it("returns chesscomStats: null when user has no chesscomUsername", async () => { mockUserFindFirst.mockResolvedValue({ ...baseUser, chesscomUsername: null }); const res = await GET(makeGet()); const body = await json(res) as Record; expect(body.chesscomStats).toBeNull(); expect(mockGetPlayerStats).not.toHaveBeenCalled(); }); it("does not call getPlayerStats when chesscomUsername is null", async () => { mockUserFindFirst.mockResolvedValue({ ...baseUser, chesscomUsername: null }); await GET(makeGet()); expect(mockGetPlayerStats).not.toHaveBeenCalled(); }); it("returns chesscomStats: null when getPlayerStats returns null (unknown user)", async () => { mockUserFindFirst.mockResolvedValue({ ...baseUser, chesscomUsername: "hikaru" }); mockGetPlayerStats.mockResolvedValue(null); const res = await GET(makeGet()); const body = await json(res) as Record; expect(body.chesscomStats).toBeNull(); }); it("calls getPlayerStats with the chesscomUsername", async () => { mockUserFindFirst.mockResolvedValue({ ...baseUser, chesscomUsername: "hikaru" }); mockGetPlayerStats.mockResolvedValue(null); await GET(makeGet()); expect(mockGetPlayerStats).toHaveBeenCalledWith("hikaru"); }); it("returns populated chesscomStats when API succeeds", async () => { mockUserFindFirst.mockResolvedValue({ ...baseUser, chesscomUsername: "hikaru" }); mockGetBestRating.mockReturnValue(3200); mockGetPlayerStats.mockResolvedValue({ chess_rapid: { last: { rating: 2900, date: 1700000000 }, best: { rating: 3000, date: 1690000000 }, record: { win: 100, loss: 20, draw: 10 }, }, chess_blitz: { last: { rating: 3100, date: 1700000000 }, best: { rating: 3200, date: 1690000000 }, record: { win: 200, loss: 30, draw: 20 }, }, chess_bullet: { last: { rating: 3150, date: 1700000000 }, best: { rating: 3250, date: 1690000000 }, record: { win: 150, loss: 25, draw: 15 }, }, chess_daily: { last: { rating: 2800, date: 1700000000 }, best: { rating: 2850, date: 1690000000 }, record: { win: 50, loss: 5, draw: 2 }, }, tactics: { highest: { rating: 2950, date: 0 }, lowest: { rating: 1500, date: 0 } }, puzzle_rush: { best: { total_attempts: 150, score: 87 } }, }); const res = await GET(makeGet()); const body = await json(res) as Record; const stats = body.chesscomStats as Record; expect(stats).not.toBeNull(); expect(stats.bestRating).toBe(3200); expect(stats.rapid).toBe(2900); expect(stats.blitz).toBe(3100); expect(stats.bullet).toBe(3150); expect(stats.daily).toBe(2800); expect(stats.rapidBest).toBe(3000); expect(stats.blitzBest).toBe(3200); expect(stats.bulletBest).toBe(3250); expect(stats.tacticsHighest).toBe(2950); expect(stats.puzzleRushBest).toBe(87); }); it("returns null for absent time classes", async () => { mockUserFindFirst.mockResolvedValue({ ...baseUser, chesscomUsername: "newplayer" }); mockGetBestRating.mockReturnValue(1500); mockGetPlayerStats.mockResolvedValue({ // Only rapid — no blitz, bullet, daily, tactics, puzzle_rush chess_rapid: { last: { rating: 1500, date: 1700000000 }, best: { rating: 1600, date: 1690000000 }, record: { win: 10, loss: 5, draw: 2 }, }, }); const res = await GET(makeGet()); const body = await json(res) as Record; const stats = body.chesscomStats as Record; expect(stats.rapid).toBe(1500); expect(stats.rapidBest).toBe(1600); expect(stats.blitz).toBeNull(); expect(stats.blitzBest).toBeNull(); expect(stats.bullet).toBeNull(); expect(stats.bulletBest).toBeNull(); expect(stats.daily).toBeNull(); expect(stats.tacticsHighest).toBeNull(); expect(stats.puzzleRushBest).toBeNull(); }); it("includes chesscomStats in the response shape when username is set", async () => { mockUserFindFirst.mockResolvedValue({ ...baseUser, chesscomUsername: "magnus" }); mockGetBestRating.mockReturnValue(2800); mockGetPlayerStats.mockResolvedValue({ chess_rapid: { last: { rating: 2800, date: 0 }, best: { rating: 2850, date: 0 }, record: { win: 1, loss: 0, draw: 0 } }, }); const res = await GET(makeGet()); const body = await json(res) as Record; // chesscomStats key should exist (not missing from response) expect(Object.prototype.hasOwnProperty.call(body, "chesscomStats")).toBe(true); }); // --------------------------------------------------------------------------- // dailyActivity (streak calendar heatmap) // --------------------------------------------------------------------------- it("dailyActivity is an array in response", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const res = await GET(makeGet()); const body = await json(res) as Record; expect(Array.isArray(body.dailyActivity)).toBe(true); }); it("dailyActivity is empty when no daily logs exist", async () => { mockDailyLogFindMany.mockResolvedValue([]); mockUserFindFirst.mockResolvedValue(baseUser); const res = await GET(makeGet()); const body = await json(res) as Record; expect(body.dailyActivity).toEqual([]); }); it("dailyActivity maps date, xpEarned, activityCount, goalMet", async () => { mockUserFindFirst.mockResolvedValue(baseUser); const res = await GET(makeGet()); const body = await json(res) as Record; const activity = body.dailyActivity as Array>; expect(activity).toHaveLength(2); const first = activity[0]; expect(first).toHaveProperty("date"); expect(first.xpEarned).toBe(120); expect(first.activityCount).toBe(3); expect(first.goalMet).toBe(true); const second = activity[1]; expect(second.xpEarned).toBe(60); expect(second.activityCount).toBe(1); expect(second.goalMet).toBe(false); }); it("dailyActivity queries with gte filter (last 90 days)", async () => { mockUserFindFirst.mockResolvedValue(baseUser); await GET(makeGet()); expect(mockDailyLogFindMany).toHaveBeenCalledOnce(); const callArgs = mockDailyLogFindMany.mock.calls[0][0] as Record; const where = callArgs.where as Record; const dateFilter = (where.date as Record).gte as Date; // Should be ~89 days ago (within a day's tolerance) const nowMs = Date.now(); const diffDays = (nowMs - dateFilter.getTime()) / (1000 * 60 * 60 * 24); expect(diffDays).toBeGreaterThan(88); expect(diffDays).toBeLessThan(91); }); it("dailyActivity query uses userId filter", async () => { mockUserFindFirst.mockResolvedValue(baseUser); await GET(makeGet()); const callArgs = mockDailyLogFindMany.mock.calls[0][0] as Record; const where = callArgs.where as Record; expect(where.userId).toBe(1); }); it("dailyActivity query selects only needed fields", async () => { mockUserFindFirst.mockResolvedValue(baseUser); await GET(makeGet()); const callArgs = mockDailyLogFindMany.mock.calls[0][0] as Record; const select = callArgs.select as Record; expect(select).toHaveProperty("date"); expect(select).toHaveProperty("xpEarned"); expect(select).toHaveProperty("activityCount"); expect(select).toHaveProperty("goalMet"); }); });