/** * Tests for chess puzzle and submit routes. * * Covers: * GET /api/chess/puzzle * - random puzzle fetch (default) * - daily puzzle fetch (?daily=true) * - 502 when Lichess returns null * - response shape (id, solution, rating, themes, plays, gameUrl, pgn, fen computed server-side) * * POST /api/chess/submit — calcQualityScore (pure) * - solved = false → 0 * - perfect efficiency (movesPlayed === solutionLen) → 1.0 * - extra moves reduce quality * * POST /api/chess/submit — handler * - input validation: missing puzzleId, non-string puzzleId, non-number puzzleRating, non-boolean solved * - invalid JSON body → 400 * - user not found → 404 * - missing chess CategorySkill → 500 * - success shape: solved, qualityScore, xp breakdown, levelUp, categoryXp, unlocks * - XP: unsolved puzzle gets quality 0 (base XP only, no quality bonus) * - XP: critical hit doubles totalXp * - XP: multiplier bonus reflected in response * - DailyLog: created when no existing log * - DailyLog: updated when existing log exists * - goalMet flag set when XP reaches dailyGoalXp * - processSkillUnlocks called on category level-up * - processSkillUnlocks NOT called when no category level-up */ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { NextRequest } from "next/server"; // --------------------------------------------------------------------------- // Mock Lichess API (for puzzle route) // --------------------------------------------------------------------------- const mockGetLichessPuzzle = vi.fn(); const mockGetLichessDailyPuzzle = vi.fn(); vi.mock("@/lib/lichess", () => ({ getLichessPuzzle: (...args: unknown[]) => mockGetLichessPuzzle(...args), getLichessDailyPuzzle: (...args: unknown[]) => mockGetLichessDailyPuzzle(...args), })); // --------------------------------------------------------------------------- // Mock Prisma (for submit route) // --------------------------------------------------------------------------- const mockUserFindFirst = vi.fn(); const mockDailyLogFindFirst = vi.fn(); const mockTransaction = vi.fn(); const mockActivityCreate = vi.fn(); const mockUserUpdate = vi.fn(); const mockCategorySkillUpdate = vi.fn(); const mockDailyLogCreate = vi.fn(); const mockDailyLogUpdate = vi.fn(); vi.mock("@/lib/db", () => ({ prisma: { user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args), }, dailyLog: { findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args), }, $transaction: (...args: unknown[]) => mockTransaction(...args), }, })); // --------------------------------------------------------------------------- // Mock rollCriticalHit (deterministic XP) // --------------------------------------------------------------------------- const mockRollCriticalHit = vi.fn(() => false); vi.mock("@/lib/xp", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, rollCriticalHit: () => mockRollCriticalHit(), }; }); // --------------------------------------------------------------------------- // Mock getMultiplierPercent // --------------------------------------------------------------------------- const mockGetMultiplierPercent = vi.fn(() => Promise.resolve(0)); vi.mock("@/lib/multiplier", () => ({ getMultiplierPercent: (...args: unknown[]) => (mockGetMultiplierPercent as (...a: unknown[]) => unknown)(...args), })); // --------------------------------------------------------------------------- // Mock processSkillUnlocks // --------------------------------------------------------------------------- const mockProcessSkillUnlocks = vi.fn((): Promise<{ unlocked: string[]; streakFreezesGranted: number }> => Promise.resolve({ unlocked: [], streakFreezesGranted: 0 }), ); vi.mock("@/lib/skill-unlock", () => ({ processSkillUnlocks: (...args: unknown[]) => (mockProcessSkillUnlocks as (...a: unknown[]) => unknown)(...args), })); // --------------------------------------------------------------------------- // Mock processEndOfDay (no-op — streak logic is tested separately) // --------------------------------------------------------------------------- vi.mock("@/lib/streak", () => ({ processEndOfDay: vi.fn(() => Promise.resolve({ streak: 1, freezeUsed: false, streakBroken: false, alreadyProcessed: false, })), })); // --------------------------------------------------------------------------- // Import routes (after mocks are hoisted) // --------------------------------------------------------------------------- import { GET } from "../puzzle/route"; import { POST, calcQualityScore } from "../submit/route"; // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- const originalEnv = { ...process.env }; async function json(res: Response): Promise { return res.json(); } function makeGet(url: string): NextRequest { return new NextRequest(url, { method: "GET" }); } function makePost(body?: Record): NextRequest { return new NextRequest("http://localhost/api/chess/submit", { method: "POST", body: body !== undefined ? JSON.stringify(body) : undefined, headers: { "Content-Type": "application/json" }, }); } /** A representative raw Lichess puzzle API response */ function makeLichessPuzzle() { return { puzzle: { id: "pzl123", solution: ["e2e4", "e7e5", "g1f3"], rating: 1500, themes: ["fork", "middlegame"], plays: 9876, }, game: { id: "game456", pgn: "1. e4 e5 2. Nf3 Nc6", }, }; } /** Stub user with chess CategorySkill */ function makeUser(overrides: Record = {}) { return { id: 1, name: "Player One", level: 1, totalXp: 0, currentXp: 0, xpToNextLevel: 100, title: "Smooth Brain", dailyGoalXp: 100, streak: 3, longestStreak: 10, streakFreezes: 1, lichessUsername: null, chesscomUsername: null, createdAt: new Date(), categorySkills: [ { id: 10, userId: 1, category: "chess", level: 1, totalXp: 0, currentXp: 0, xpToNext: 100, }, ], ...overrides, }; } /** Wire up mockTransaction to call the callback with a fake tx client */ function setupTransaction() { mockTransaction.mockImplementation( async (callback: (tx: Record) => Promise) => { const tx = { activity: { create: mockActivityCreate }, user: { update: mockUserUpdate }, categorySkill: { update: mockCategorySkillUpdate }, dailyLog: { create: mockDailyLogCreate, update: mockDailyLogUpdate, }, }; return callback(tx); }, ); } beforeEach(() => { vi.clearAllMocks(); process.env = { ...originalEnv }; // Default happy-path state mockUserFindFirst.mockResolvedValue(makeUser()); mockDailyLogFindFirst.mockResolvedValue(null); mockRollCriticalHit.mockReturnValue(false); mockGetMultiplierPercent.mockResolvedValue(0); mockProcessSkillUnlocks.mockResolvedValue({ unlocked: [], streakFreezesGranted: 0 }); setupTransaction(); mockActivityCreate.mockResolvedValue({}); mockUserUpdate.mockResolvedValue({}); mockCategorySkillUpdate.mockResolvedValue({}); mockDailyLogCreate.mockResolvedValue({}); mockDailyLogUpdate.mockResolvedValue({}); }); afterEach(() => { process.env = originalEnv; }); // ═══════════════════════════════════════════════════════════════════════════ // GET /api/chess/puzzle // ═══════════════════════════════════════════════════════════════════════════ describe("GET /api/chess/puzzle — random puzzle (default)", () => { it("calls getLichessPuzzle (not daily) when no ?daily param", async () => { mockGetLichessPuzzle.mockResolvedValueOnce(makeLichessPuzzle()); await GET(makeGet("http://localhost/api/chess/puzzle")); expect(mockGetLichessPuzzle).toHaveBeenCalledTimes(1); expect(mockGetLichessDailyPuzzle).not.toHaveBeenCalled(); }); it("calls getLichessPuzzle when ?daily=false", async () => { mockGetLichessPuzzle.mockResolvedValueOnce(makeLichessPuzzle()); await GET(makeGet("http://localhost/api/chess/puzzle?daily=false")); expect(mockGetLichessPuzzle).toHaveBeenCalledTimes(1); expect(mockGetLichessDailyPuzzle).not.toHaveBeenCalled(); }); it("returns 200 with correct response shape", async () => { mockGetLichessPuzzle.mockResolvedValueOnce(makeLichessPuzzle()); const res = await GET(makeGet("http://localhost/api/chess/puzzle")); expect(res.status).toBe(200); const body = await json(res) as { id: string; fen: string; solution: string[]; rating: number; themes: string[]; plays: number; gameUrl: string; pgn: string; }; expect(body.id).toBe("pzl123"); expect(body.solution).toEqual(["e2e4", "e7e5", "g1f3"]); expect(body.rating).toBe(1500); expect(body.themes).toEqual(["fork", "middlegame"]); expect(body.plays).toBe(9876); expect(body.gameUrl).toBe("https://lichess.org/game456"); expect(body.pgn).toBe("1. e4 e5 2. Nf3 Nc6"); // fen is now computed server-side from the game PGN expect(body.fen).toBe("r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 2 3"); }); it("returns 502 when getLichessPuzzle returns null", async () => { mockGetLichessPuzzle.mockResolvedValueOnce(null); const res = await GET(makeGet("http://localhost/api/chess/puzzle")); expect(res.status).toBe(502); const body = await json(res) as { error: string }; expect(body.error).toBeTruthy(); }); }); describe("GET /api/chess/puzzle — daily puzzle (?daily=true)", () => { it("calls getLichessDailyPuzzle when ?daily=true", async () => { mockGetLichessDailyPuzzle.mockResolvedValueOnce(makeLichessPuzzle()); await GET(makeGet("http://localhost/api/chess/puzzle?daily=true")); expect(mockGetLichessDailyPuzzle).toHaveBeenCalledTimes(1); expect(mockGetLichessPuzzle).not.toHaveBeenCalled(); }); it("returns 200 with the same shape as random puzzles", async () => { mockGetLichessDailyPuzzle.mockResolvedValueOnce(makeLichessPuzzle()); const res = await GET(makeGet("http://localhost/api/chess/puzzle?daily=true")); expect(res.status).toBe(200); const body = await json(res) as { id: string; rating: number }; expect(body.id).toBe("pzl123"); expect(body.rating).toBe(1500); }); it("returns 502 when getLichessDailyPuzzle returns null", async () => { mockGetLichessDailyPuzzle.mockResolvedValueOnce(null); const res = await GET(makeGet("http://localhost/api/chess/puzzle?daily=true")); expect(res.status).toBe(502); }); }); // ═══════════════════════════════════════════════════════════════════════════ // calcQualityScore — pure function // ═══════════════════════════════════════════════════════════════════════════ describe("calcQualityScore", () => { it("returns 0 when solved = false regardless of moves", () => { expect(calcQualityScore(false, 3, 3)).toBe(0); expect(calcQualityScore(false, 10, 3)).toBe(0); expect(calcQualityScore(false, 1, 5)).toBe(0); }); it("returns 1.0 for a solved puzzle with perfect efficiency (movesPlayed === solutionLen)", () => { // efficiency = solutionLen / movesPlayed = 1.0 → 0.5 + 1.0*0.5 = 1.0 expect(calcQualityScore(true, 3, 3)).toBeCloseTo(1.0, 5); expect(calcQualityScore(true, 5, 5)).toBeCloseTo(1.0, 5); }); it("returns 0.5 for a solved puzzle with zero efficiency (huge mistake count)", () => { // efficiency → 0 as movesPlayed → ∞ → 0.5 + 0*0.5 = 0.5 expect(calcQualityScore(true, 1_000_000, 1)).toBeCloseTo(0.5, 1); }); it("penalises extra moves (more moves = lower quality)", () => { const perfect = calcQualityScore(true, 3, 3); const oneExtra = calcQualityScore(true, 4, 3); const twoExtra = calcQualityScore(true, 5, 3); expect(perfect).toBeGreaterThan(oneExtra); expect(oneExtra).toBeGreaterThan(twoExtra); }); it("quality is always in [0, 1] for any inputs", () => { const cases = [ [true, 1, 1], [true, 5, 3], [true, 100, 2], [false, 1, 1], [false, 0, 0], ] as Array<[boolean, number, number]>; for (const [solved, moves, len] of cases) { const q = calcQualityScore(solved, moves, len); expect(q).toBeGreaterThanOrEqual(0); expect(q).toBeLessThanOrEqual(1); } }); it("caps efficiency at 1.0 when movesPlayed < solutionLen (shouldn't happen in practice)", () => { // If somehow movesPlayed < solutionLen, efficiency is capped at 1.0 expect(calcQualityScore(true, 1, 5)).toBeCloseTo(1.0, 5); }); }); // ═══════════════════════════════════════════════════════════════════════════ // POST /api/chess/submit — input validation // ═══════════════════════════════════════════════════════════════════════════ describe("POST /api/chess/submit — input validation", () => { it("returns 400 for invalid JSON body", async () => { const req = new NextRequest("http://localhost/api/chess/submit", { method: "POST", body: "not-json", headers: { "Content-Type": "application/json" }, }); const res = await POST(req); expect(res.status).toBe(400); }); it("returns 400 when puzzleId is missing", async () => { const res = await POST(makePost({ puzzleRating: 1500, solved: true, movesPlayed: 3, solutionLen: 3, })); expect(res.status).toBe(400); const body = await json(res) as { error: string }; expect(body.error).toMatch(/puzzleId/i); }); it("returns 400 when puzzleId is not a string", async () => { const res = await POST(makePost({ puzzleId: 12345, puzzleRating: 1500, solved: true, movesPlayed: 3, solutionLen: 3, })); expect(res.status).toBe(400); const body = await json(res) as { error: string }; expect(body.error).toMatch(/puzzleId/i); }); it("returns 400 when puzzleRating is not a number", async () => { const res = await POST(makePost({ puzzleId: "pzl123", puzzleRating: "hard", solved: true, movesPlayed: 3, solutionLen: 3, })); expect(res.status).toBe(400); const body = await json(res) as { error: string }; expect(body.error).toMatch(/puzzleRating/i); }); it("returns 400 when solved is not a boolean", async () => { const res = await POST(makePost({ puzzleId: "pzl123", puzzleRating: 1500, solved: "yes", movesPlayed: 3, solutionLen: 3, })); expect(res.status).toBe(400); const body = await json(res) as { error: string }; expect(body.error).toMatch(/solved/i); }); }); // ═══════════════════════════════════════════════════════════════════════════ // POST /api/chess/submit — DB error paths // ═══════════════════════════════════════════════════════════════════════════ describe("POST /api/chess/submit — DB error paths", () => { it("returns 404 when user is not found", async () => { mockUserFindFirst.mockResolvedValueOnce(null); const res = await POST(makePost({ puzzleId: "pzl123", puzzleRating: 1500, solved: true, movesPlayed: 3, solutionLen: 3, })); expect(res.status).toBe(404); const body = await json(res) as { error: string }; expect(body.error).toMatch(/user/i); }); it("returns 500 when chess CategorySkill is missing", async () => { mockUserFindFirst.mockResolvedValueOnce(makeUser({ categorySkills: [] })); const res = await POST(makePost({ puzzleId: "pzl123", puzzleRating: 1500, solved: true, movesPlayed: 3, solutionLen: 3, })); expect(res.status).toBe(500); const body = await json(res) as { error: string }; expect(body.error).toMatch(/CategorySkill/i); }); }); // ═══════════════════════════════════════════════════════════════════════════ // POST /api/chess/submit — success path: response shape // ═══════════════════════════════════════════════════════════════════════════ describe("POST /api/chess/submit — success response shape", () => { const defaultBody = { puzzleId: "pzl123", puzzleRating: 1500, solved: true, movesPlayed: 3, solutionLen: 3, }; it("returns 200 on success", async () => { const res = await POST(makePost(defaultBody)); expect(res.status).toBe(200); }); it("response includes solved field matching the input", async () => { const res = await POST(makePost(defaultBody)); const body = await json(res) as { solved: boolean }; expect(body.solved).toBe(true); }); it("response includes qualityScore in [0, 1]", async () => { const res = await POST(makePost(defaultBody)); const body = await json(res) as { qualityScore: number }; expect(body.qualityScore).toBeGreaterThanOrEqual(0); expect(body.qualityScore).toBeLessThanOrEqual(1); }); it("response includes full xp breakdown", async () => { const res = await POST(makePost(defaultBody)); const body = await json(res) as { xp: { totalXp: number; baseXp: number; qualityBonus: number; multiplierBonus: number; multiplierPercent: number; isCriticalHit: boolean; }; }; expect(typeof body.xp.totalXp).toBe("number"); expect(typeof body.xp.baseXp).toBe("number"); expect(typeof body.xp.qualityBonus).toBe("number"); expect(typeof body.xp.multiplierBonus).toBe("number"); expect(typeof body.xp.multiplierPercent).toBe("number"); expect(typeof body.xp.isCriticalHit).toBe("boolean"); }); it("response includes levelUp flag and newLevel", async () => { const res = await POST(makePost(defaultBody)); const body = await json(res) as { levelUp: boolean; newLevel: number }; expect(typeof body.levelUp).toBe("boolean"); expect(typeof body.newLevel).toBe("number"); }); it("response includes categoryXp breakdown", async () => { const res = await POST(makePost(defaultBody)); const body = await json(res) as { categoryXp: { currentXp: number; xpToNext: number; level: number; levelUp: boolean; }; }; expect(typeof body.categoryXp.currentXp).toBe("number"); expect(typeof body.categoryXp.xpToNext).toBe("number"); expect(typeof body.categoryXp.level).toBe("number"); expect(typeof body.categoryXp.levelUp).toBe("boolean"); }); it("response includes unlocks array", async () => { const res = await POST(makePost(defaultBody)); const body = await json(res) as { unlocks: string[] }; expect(Array.isArray(body.unlocks)).toBe(true); }); }); // ═══════════════════════════════════════════════════════════════════════════ // POST /api/chess/submit — XP calculations // ═══════════════════════════════════════════════════════════════════════════ describe("POST /api/chess/submit — XP calculations", () => { it("unsolved puzzle: qualityScore is 0 and qualityBonus is 0", async () => { const res = await POST(makePost({ puzzleId: "pzl123", puzzleRating: 1500, solved: false, movesPlayed: 3, solutionLen: 3, })); const body = await json(res) as { qualityScore: number; xp: { qualityBonus: number } }; expect(body.qualityScore).toBe(0); expect(body.xp.qualityBonus).toBe(0); }); it("solved puzzle: qualityBonus > 0 for perfect play", async () => { const res = await POST(makePost({ puzzleId: "pzl123", puzzleRating: 1500, solved: true, movesPlayed: 3, solutionLen: 3, })); const body = await json(res) as { xp: { qualityBonus: number } }; expect(body.xp.qualityBonus).toBeGreaterThan(0); }); it("critical hit doubles totalXp", async () => { mockRollCriticalHit.mockReturnValue(true); const resCrit = await POST(makePost({ puzzleId: "pzl123", puzzleRating: 1500, solved: true, movesPlayed: 3, solutionLen: 3, })); const bodyCrit = await json(resCrit) as { xp: { totalXp: number; isCriticalHit: boolean } }; mockRollCriticalHit.mockReturnValue(false); const resNorm = await POST(makePost({ puzzleId: "pzl123", puzzleRating: 1500, solved: true, movesPlayed: 3, solutionLen: 3, })); const bodyNorm = await json(resNorm) as { xp: { totalXp: number } }; expect(bodyCrit.xp.isCriticalHit).toBe(true); expect(bodyCrit.xp.totalXp).toBeGreaterThan(bodyNorm.xp.totalXp); }); it("multiplierPercent is reflected in response xp.multiplierPercent", async () => { mockGetMultiplierPercent.mockResolvedValueOnce(25); const res = await POST(makePost({ puzzleId: "pzl123", puzzleRating: 1500, solved: true, movesPlayed: 3, solutionLen: 3, })); const body = await json(res) as { xp: { multiplierPercent: number; multiplierBonus: number } }; expect(body.xp.multiplierPercent).toBe(25); expect(body.xp.multiplierBonus).toBeGreaterThan(0); }); it("multiplierBonus is 0 when multiplierPercent is 0", async () => { mockGetMultiplierPercent.mockResolvedValueOnce(0); const res = await POST(makePost({ puzzleId: "pzl123", puzzleRating: 1500, solved: true, movesPlayed: 3, solutionLen: 3, })); const body = await json(res) as { xp: { multiplierBonus: number } }; expect(body.xp.multiplierBonus).toBe(0); }); }); // ═══════════════════════════════════════════════════════════════════════════ // POST /api/chess/submit — DailyLog // ═══════════════════════════════════════════════════════════════════════════ describe("POST /api/chess/submit — DailyLog", () => { const defaultBody = { puzzleId: "pzl123", puzzleRating: 1500, solved: true, movesPlayed: 3, solutionLen: 3, }; it("creates a new DailyLog when none exists for today", async () => { mockDailyLogFindFirst.mockResolvedValueOnce(null); await POST(makePost(defaultBody)); expect(mockDailyLogCreate).toHaveBeenCalledTimes(1); expect(mockDailyLogUpdate).not.toHaveBeenCalled(); }); it("updates the existing DailyLog when one exists for today", async () => { mockDailyLogFindFirst.mockResolvedValueOnce({ id: 99, xpEarned: 50, activityCount: 2, goalMet: false, }); await POST(makePost(defaultBody)); expect(mockDailyLogUpdate).toHaveBeenCalledTimes(1); expect(mockDailyLogCreate).not.toHaveBeenCalled(); }); it("sets goalMet=true when accumulated XP reaches dailyGoalXp", async () => { // User has dailyGoalXp of 100; give them 95 already earned + ≥5 XP from puzzle mockUserFindFirst.mockResolvedValueOnce(makeUser({ dailyGoalXp: 100 })); mockDailyLogFindFirst.mockResolvedValueOnce({ id: 99, xpEarned: 95, activityCount: 3, goalMet: false, }); await POST(makePost(defaultBody)); expect(mockDailyLogUpdate).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ goalMet: true }), }), ); }); }); // ═══════════════════════════════════════════════════════════════════════════ // POST /api/chess/submit — skill unlocks // ═══════════════════════════════════════════════════════════════════════════ describe("POST /api/chess/submit — skill unlocks", () => { it("calls processSkillUnlocks when category levels up", async () => { // Set chess skill so that adding any XP causes a level-up const highXpUser = makeUser({ categorySkills: [ { id: 10, userId: 1, category: "chess", level: 1, totalXp: 90, currentXp: 90, xpToNext: 10, // 10 XP needed → puzzle awards ≥10 XP → level-up }, ], }); mockUserFindFirst.mockResolvedValueOnce(highXpUser); await POST(makePost({ puzzleId: "pzl123", puzzleRating: 1500, solved: true, movesPlayed: 3, solutionLen: 3, })); expect(mockProcessSkillUnlocks).toHaveBeenCalledTimes(1); expect(mockProcessSkillUnlocks).toHaveBeenCalledWith( expect.anything(), 1, "chess", expect.any(Number), ); }); it("does NOT call processSkillUnlocks when no category level-up occurs", async () => { // Chess skill needs 10000 XP to level-up → won't level from one puzzle const user = makeUser({ categorySkills: [ { id: 10, userId: 1, category: "chess", level: 1, totalXp: 0, currentXp: 0, xpToNext: 10_000, }, ], }); mockUserFindFirst.mockResolvedValueOnce(user); await POST(makePost({ puzzleId: "pzl123", puzzleRating: 1500, solved: true, movesPlayed: 3, solutionLen: 3, })); expect(mockProcessSkillUnlocks).not.toHaveBeenCalled(); }); it("includes unlocks array in response from processSkillUnlocks", async () => { const highXpUser = makeUser({ categorySkills: [ { id: 10, userId: 1, category: "chess", level: 1, totalXp: 90, currentXp: 90, xpToNext: 10, }, ], }); mockUserFindFirst.mockResolvedValueOnce(highXpUser); mockProcessSkillUnlocks.mockResolvedValueOnce({ unlocked: ["Tactical Vision", "Endgame Basics"], streakFreezesGranted: 1, }); const res = await POST(makePost({ puzzleId: "pzl123", puzzleRating: 1500, solved: true, movesPlayed: 3, solutionLen: 3, })); const body = await json(res) as { unlocks: string[]; streakFreezesGranted: number }; expect(body.unlocks).toEqual(["Tactical Vision", "Endgame Basics"]); expect(body.streakFreezesGranted).toBe(1); }); }); // ═══════════════════════════════════════════════════════════════════════════ // POST /api/chess/submit — activity persistence // ═══════════════════════════════════════════════════════════════════════════ describe("POST /api/chess/submit — activity persistence", () => { it("creates an activity record with chess category and puzzle metadata", async () => { await POST(makePost({ puzzleId: "pzl999", puzzleRating: 1800, solved: true, movesPlayed: 4, solutionLen: 3, })); expect(mockActivityCreate).toHaveBeenCalledTimes(1); const callArg = mockActivityCreate.mock.calls[0][0] as { data: { category: string; exerciseType: string; description: string; score: number; metadata: string; }; }; expect(callArg.data.category).toBe("chess"); expect(callArg.data.exerciseType).toBe("puzzle"); expect(callArg.data.description).toContain("pzl999"); expect(callArg.data.description).toContain("1800"); const metadata = JSON.parse(callArg.data.metadata) as { puzzleId: string; puzzleRating: number; solved: boolean; }; expect(metadata.puzzleId).toBe("pzl999"); expect(metadata.puzzleRating).toBe(1800); expect(metadata.solved).toBe(true); }); }); // ═══════════════════════════════════════════════════════════════════════════ // POST /api/chess/submit — durationSecs persistence // ═══════════════════════════════════════════════════════════════════════════ describe("POST /api/chess/submit — durationSecs", () => { const baseBody = { puzzleId: "pzl123", puzzleRating: 1500, solved: true, movesPlayed: 3, solutionLen: 3, }; function getActivityData() { return (mockActivityCreate.mock.calls[0][0] as { data: Record }).data; } it("persists durationSecs when provided", async () => { await POST(makePost({ ...baseBody, durationSecs: 90 })); expect(getActivityData().durationSecs).toBe(90); }); it("rounds durationSecs to the nearest integer", async () => { await POST(makePost({ ...baseBody, durationSecs: 45.7 })); expect(getActivityData().durationSecs).toBe(46); }); it("stores null when durationSecs is omitted", async () => { await POST(makePost(baseBody)); expect(getActivityData().durationSecs).toBeNull(); }); it("stores null when durationSecs is negative", async () => { await POST(makePost({ ...baseBody, durationSecs: -5 })); expect(getActivityData().durationSecs).toBeNull(); }); it("persists durationSecs of 0 (instant solve)", async () => { await POST(makePost({ ...baseBody, durationSecs: 0 })); expect(getActivityData().durationSecs).toBe(0); }); });