Download src/app/api/stats/__tests__/route.test.ts from NAP1320/RotNot: direct link, hf CLI and curl.
- Browser
- Download file 34.7 kB
-
https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/app/api/stats/__tests__/route.test.ts
- Command line
-
hf download hf://spaces/NAP1320/RotNot/src/app/api/stats/__tests__/route.test.ts
-
curl -L -o route.test.ts https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/app/api/stats/__tests__/route.test.ts
34.7 kB
| /** | |
| * Tests for GET /api/stats | |
| * | |
| * Covers: | |
| * - 404 when no user found | |
| * - response shape: windowDays, dailyXp, categoryBreakdown, recentActivities, summary | |
| * - dailyXp: maps dailyLogs to { date, xpEarned, activityCount, goalMet } | |
| * - categoryBreakdown: accumulates totalXp, count, avgScore, totalDuration per category | |
| * - avgScore: averaged correctly over SCORED activities only (null scores excluded from denominator) | |
| * - recentActivities: limited to first 25, maps all fields | |
| * - summary: totalExercises, totalXpEarned, criticalHits, criticalHitRate, goalDaysMet | |
| * - summary: correctSolves and correctSolveRate (score > 0 out of scored exercises) | |
| * - summary: streak and level from user | |
| * - empty data cases | |
| * - DB errors propagate as 500 | |
| * - ?days param: windowDays 7/30/90 (default 30), invalid values fall back to 30 | |
| * - ?days param: DB gte boundary verified for 7-day and 90-day windows | |
| */ | |
| import { describe, it, expect, vi, beforeEach } from "vitest"; | |
| import { NextRequest } from "next/server"; | |
| // --------------------------------------------------------------------------- | |
| // Mock prisma | |
| // --------------------------------------------------------------------------- | |
| const mockUserFindFirst = vi.fn(); | |
| const mockDailyLogFindMany = vi.fn(); | |
| const mockActivityFindMany = vi.fn(); | |
| vi.mock("@/lib/db", () => ({ | |
| prisma: { | |
| user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) }, | |
| dailyLog: { findMany: (...args: unknown[]) => mockDailyLogFindMany(...args) }, | |
| activity: { findMany: (...args: unknown[]) => mockActivityFindMany(...args) }, | |
| }, | |
| })); | |
| import { GET } from "../route"; | |
| // --------------------------------------------------------------------------- | |
| // Fixtures | |
| // --------------------------------------------------------------------------- | |
| const baseUser = { | |
| id: 1, | |
| name: "Player One", | |
| level: 5, | |
| streak: 3, | |
| longestStreak: 10, | |
| categorySkills: [], | |
| }; | |
| function makeActivity(overrides: Partial<{ | |
| id: number; category: string; exerciseType: string; description: string; | |
| baseXp: number; qualityBonus: number; isCriticalHit: boolean; totalXp: number; | |
| score: number | null; durationSecs: number | null; createdAt: Date; | |
| }> = {}) { | |
| return { | |
| id: 1, | |
| category: "CHESS", | |
| exerciseType: "chess-puzzle", | |
| description: "Solved a puzzle", | |
| baseXp: 30, | |
| qualityBonus: 10, | |
| isCriticalHit: false, | |
| totalXp: 40, | |
| score: 0.8, | |
| durationSecs: 120, | |
| createdAt: new Date("2026-03-24T10:00:00Z"), | |
| ...overrides, | |
| }; | |
| } | |
| function makeDailyLog(overrides: Partial<{ | |
| date: Date; xpEarned: number; activityCount: number; goalMet: boolean; | |
| }> = {}) { | |
| return { | |
| date: new Date("2026-03-24T00:00:00Z"), | |
| xpEarned: 80, | |
| activityCount: 3, | |
| goalMet: false, | |
| ...overrides, | |
| }; | |
| } | |
| function makeGet(params?: Record<string, string>): NextRequest { | |
| const url = new URL("http://localhost/api/stats"); | |
| if (params) { | |
| for (const [k, v] of Object.entries(params)) { | |
| url.searchParams.set(k, v); | |
| } | |
| } | |
| return new NextRequest(url.toString()); | |
| } | |
| async function json(res: Response): Promise<unknown> { | |
| return res.json(); | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Tests | |
| // --------------------------------------------------------------------------- | |
| describe("GET /api/stats", () => { | |
| beforeEach(() => { | |
| vi.clearAllMocks(); | |
| mockDailyLogFindMany.mockResolvedValue([]); | |
| mockActivityFindMany.mockResolvedValue([]); | |
| }); | |
| 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<string, unknown>; | |
| expect(body).toHaveProperty("windowDays"); | |
| expect(body).toHaveProperty("dailyXp"); | |
| expect(body).toHaveProperty("categoryBreakdown"); | |
| expect(body).toHaveProperty("recentActivities"); | |
| expect(body).toHaveProperty("summary"); | |
| }); | |
| it("maps dailyXp from logs", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockDailyLogFindMany.mockResolvedValue([ | |
| makeDailyLog({ xpEarned: 100, activityCount: 4, goalMet: true }), | |
| makeDailyLog({ date: new Date("2026-03-23T00:00:00Z"), xpEarned: 50, activityCount: 2, goalMet: false }), | |
| ]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const dailyXp = body.dailyXp as Array<Record<string, unknown>>; | |
| expect(dailyXp).toHaveLength(2); | |
| expect(dailyXp[0]).toMatchObject({ xpEarned: 100, activityCount: 4, goalMet: true }); | |
| expect(dailyXp[1]).toMatchObject({ xpEarned: 50, activityCount: 2, goalMet: false }); | |
| expect(dailyXp[0]).toHaveProperty("date"); | |
| }); | |
| it("builds categoryBreakdown accumulating XP and count", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([ | |
| makeActivity({ id: 1, category: "CHESS", totalXp: 40, score: 0.8, durationSecs: 120 }), | |
| makeActivity({ id: 2, category: "CHESS", totalXp: 30, score: 0.6, durationSecs: 90 }), | |
| makeActivity({ id: 3, category: "FEYNMAN", totalXp: 50, score: 1.0, durationSecs: 300 }), | |
| ]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const breakdown = body.categoryBreakdown as Record<string, Record<string, number>>; | |
| expect(breakdown.CHESS.totalXp).toBe(70); | |
| expect(breakdown.CHESS.count).toBe(2); | |
| expect(breakdown.CHESS.totalDuration).toBe(210); | |
| expect(breakdown.FEYNMAN.totalXp).toBe(50); | |
| expect(breakdown.FEYNMAN.count).toBe(1); | |
| }); | |
| it("computes avgScore as mean of non-null scores", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([ | |
| makeActivity({ id: 1, category: "CHESS", score: 0.8 }), | |
| makeActivity({ id: 2, category: "CHESS", score: 0.6 }), | |
| ]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const breakdown = body.categoryBreakdown as Record<string, Record<string, number>>; | |
| // (0.8 + 0.6) / 2 = 0.7, rounded to 2dp | |
| expect(breakdown.CHESS.avgScore).toBe(0.7); | |
| }); | |
| it("ignores null scores in avgScore denominator — divides by scored count only", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([ | |
| makeActivity({ id: 1, category: "CHESS", score: 0.8 }), | |
| makeActivity({ id: 2, category: "CHESS", score: null }), | |
| ]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const breakdown = body.categoryBreakdown as Record<string, Record<string, number>>; | |
| // 1 scored activity with score=0.8 → avgScore = 0.8/1 = 0.8 (not 0.8/2 = 0.4) | |
| expect(breakdown.CHESS.avgScore).toBe(0.8); | |
| }); | |
| it("returns avgScore 0 when no scored activities in a category", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([ | |
| makeActivity({ id: 1, category: "CHESS", score: null }), | |
| makeActivity({ id: 2, category: "CHESS", score: null }), | |
| ]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const breakdown = body.categoryBreakdown as Record<string, Record<string, number>>; | |
| expect(breakdown.CHESS.avgScore).toBe(0); | |
| }); | |
| it("limits recentActivities to 25", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| const activities = Array.from({ length: 30 }, (_, i) => | |
| makeActivity({ id: i + 1 }) | |
| ); | |
| mockActivityFindMany.mockResolvedValue(activities); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const recent = body.recentActivities as unknown[]; | |
| expect(recent).toHaveLength(25); | |
| }); | |
| it("maps all recentActivity fields", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([ | |
| makeActivity({ id: 42, category: "FEYNMAN", exerciseType: "explain", description: "Black holes", baseXp: 30, qualityBonus: 10, isCriticalHit: true, totalXp: 80, score: 0.9, durationSecs: 180 }), | |
| ]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const recent = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(recent[0]).toMatchObject({ | |
| id: 42, | |
| category: "FEYNMAN", | |
| exerciseType: "explain", | |
| description: "Black holes", | |
| baseXp: 30, | |
| qualityBonus: 10, | |
| isCriticalHit: true, | |
| totalXp: 80, | |
| score: 0.9, | |
| durationSecs: 180, | |
| }); | |
| expect(recent[0]).toHaveProperty("createdAt"); | |
| }); | |
| it("counts totalExercises in summary", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([ | |
| makeActivity({ id: 1 }), | |
| makeActivity({ id: 2 }), | |
| makeActivity({ id: 3 }), | |
| ]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const summary = body.summary as Record<string, unknown>; | |
| expect(summary.totalExercises).toBe(3); | |
| }); | |
| it("sums totalXpEarned in summary", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([ | |
| makeActivity({ id: 1, totalXp: 40 }), | |
| makeActivity({ id: 2, totalXp: 60 }), | |
| ]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const summary = body.summary as Record<string, unknown>; | |
| expect(summary.totalXpEarned).toBe(100); | |
| }); | |
| it("counts criticalHits in summary", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([ | |
| makeActivity({ id: 1, isCriticalHit: true }), | |
| makeActivity({ id: 2, isCriticalHit: false }), | |
| makeActivity({ id: 3, isCriticalHit: true }), | |
| ]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const summary = body.summary as Record<string, unknown>; | |
| expect(summary.criticalHits).toBe(2); | |
| }); | |
| it("computes criticalHitRate as percentage", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([ | |
| makeActivity({ id: 1, isCriticalHit: true }), | |
| makeActivity({ id: 2, isCriticalHit: false }), | |
| makeActivity({ id: 3, isCriticalHit: false }), | |
| makeActivity({ id: 4, isCriticalHit: false }), | |
| ]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const summary = body.summary as Record<string, unknown>; | |
| // 1/4 = 25.0 | |
| expect(summary.criticalHitRate).toBe(25); | |
| }); | |
| it("returns criticalHitRate 0 when no activities", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const summary = body.summary as Record<string, unknown>; | |
| expect(summary.criticalHitRate).toBe(0); | |
| }); | |
| // ── Correct Solve Rate ──────────────────────────────────────────────────── | |
| it("counts correctSolves as activities with score > 0", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([ | |
| makeActivity({ id: 1, score: 0.8 }), | |
| makeActivity({ id: 2, score: 0.0 }), // zero score = incorrect | |
| makeActivity({ id: 3, score: 1.0 }), | |
| makeActivity({ id: 4, score: null }), // no score = unscored | |
| ]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const summary = body.summary as Record<string, unknown>; | |
| // Only id=1 (0.8) and id=3 (1.0) are correct solves | |
| expect(summary.correctSolves).toBe(2); | |
| }); | |
| it("computes correctSolveRate as percentage of scored exercises", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([ | |
| makeActivity({ id: 1, score: 1.0 }), // correct | |
| makeActivity({ id: 2, score: 0.8 }), // correct | |
| makeActivity({ id: 3, score: 0.0 }), // incorrect | |
| makeActivity({ id: 4, score: null }), // unscored — excluded from denominator | |
| ]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const summary = body.summary as Record<string, unknown>; | |
| // 2 correct out of 3 scored = 66.7% | |
| expect(summary.correctSolveRate).toBe(66.7); | |
| }); | |
| it("returns correctSolveRate 100 when all scored exercises correct", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([ | |
| makeActivity({ id: 1, score: 0.9 }), | |
| makeActivity({ id: 2, score: 1.0 }), | |
| ]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const summary = body.summary as Record<string, unknown>; | |
| expect(summary.correctSolveRate).toBe(100); | |
| }); | |
| it("returns correctSolveRate 0 when no scored activities", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([ | |
| makeActivity({ id: 1, score: null }), | |
| makeActivity({ id: 2, score: null }), | |
| ]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const summary = body.summary as Record<string, unknown>; | |
| expect(summary.correctSolveRate).toBe(0); | |
| expect(summary.correctSolves).toBe(0); | |
| }); | |
| it("returns correctSolveRate 0 when no activities at all", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const summary = body.summary as Record<string, unknown>; | |
| expect(summary.correctSolveRate).toBe(0); | |
| }); | |
| it("summary includes correctSolves and correctSolveRate fields", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([makeActivity({ id: 1, score: 0.7 })]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const summary = body.summary as Record<string, unknown>; | |
| expect(summary).toHaveProperty("correctSolves"); | |
| expect(summary).toHaveProperty("correctSolveRate"); | |
| }); | |
| it("counts goalDaysMet from daily logs", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockDailyLogFindMany.mockResolvedValue([ | |
| makeDailyLog({ goalMet: true }), | |
| makeDailyLog({ goalMet: false }), | |
| makeDailyLog({ goalMet: true }), | |
| ]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const summary = body.summary as Record<string, unknown>; | |
| expect(summary.goalDaysMet).toBe(2); | |
| }); | |
| it("includes streak and longestStreak from user", async () => { | |
| mockUserFindFirst.mockResolvedValue({ ...baseUser, streak: 7, longestStreak: 14 }); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const summary = body.summary as Record<string, unknown>; | |
| expect(summary.currentStreak).toBe(7); | |
| expect(summary.longestStreak).toBe(14); | |
| }); | |
| it("includes user level in summary", async () => { | |
| mockUserFindFirst.mockResolvedValue({ ...baseUser, level: 8 }); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const summary = body.summary as Record<string, unknown>; | |
| expect(summary.level).toBe(8); | |
| }); | |
| it("handles null durationSecs gracefully", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([ | |
| makeActivity({ id: 1, durationSecs: null }), | |
| makeActivity({ id: 2, durationSecs: 60 }), | |
| ]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const summary = body.summary as Record<string, unknown>; | |
| expect(summary.totalDuration).toBe(60); | |
| }); | |
| it("returns empty collections when no activity", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockActivityFindMany.mockResolvedValue([]); | |
| mockDailyLogFindMany.mockResolvedValue([]); | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| expect(body.dailyXp).toEqual([]); | |
| expect(body.categoryBreakdown).toEqual({}); | |
| expect(body.recentActivities).toEqual([]); | |
| }); | |
| it("queries daily logs from last 30 days ordered asc", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| await GET(makeGet()); | |
| const call = mockDailyLogFindMany.mock.calls[0][0]; | |
| expect(call).toMatchObject({ | |
| where: { userId: 1, date: { gte: expect.any(Date) } }, | |
| orderBy: { date: "asc" }, | |
| }); | |
| // gte is UTC midnight ~30 days ago; tolerance ±24h for midnight truncation | |
| const gteDate: Date = call.where.date.gte; | |
| const nowMs = Date.now(); | |
| const diffMs = nowMs - gteDate.getTime(); | |
| const thirtyDaysMs = 30 * 24 * 60 * 60 * 1000; | |
| const oneDayMs = 24 * 60 * 60 * 1000; | |
| expect(diffMs).toBeGreaterThanOrEqual(thirtyDaysMs - oneDayMs); | |
| expect(diffMs).toBeLessThanOrEqual(thirtyDaysMs + oneDayMs); | |
| }); | |
| it("propagates DB errors as 500", async () => { | |
| mockUserFindFirst.mockRejectedValue(new Error("DB down")); | |
| const res = await GET(makeGet()); | |
| expect(res.status).toBe(500); | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // ?days query parameter | |
| // --------------------------------------------------------------------------- | |
| describe("GET /api/stats — ?days query param", () => { | |
| beforeEach(() => { | |
| vi.clearAllMocks(); | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockDailyLogFindMany.mockResolvedValue([]); | |
| mockActivityFindMany.mockResolvedValue([]); | |
| }); | |
| it("defaults to windowDays=30 when ?days is omitted", async () => { | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| expect(body.windowDays).toBe(30); | |
| }); | |
| it("returns windowDays=7 when ?days=7", async () => { | |
| const res = await GET(makeGet({ days: "7" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| expect(body.windowDays).toBe(7); | |
| }); | |
| it("returns windowDays=30 when ?days=30", async () => { | |
| const res = await GET(makeGet({ days: "30" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| expect(body.windowDays).toBe(30); | |
| }); | |
| it("returns windowDays=90 when ?days=90", async () => { | |
| const res = await GET(makeGet({ days: "90" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| expect(body.windowDays).toBe(90); | |
| }); | |
| it("falls back to windowDays=30 for invalid ?days value (e.g. 14)", async () => { | |
| const res = await GET(makeGet({ days: "14" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| expect(body.windowDays).toBe(30); | |
| }); | |
| it("falls back to windowDays=30 for non-numeric ?days", async () => { | |
| const res = await GET(makeGet({ days: "week" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| expect(body.windowDays).toBe(30); | |
| }); | |
| it("queries daily logs with gte set to UTC midnight ~7 days ago when ?days=7", async () => { | |
| await GET(makeGet({ days: "7" })); | |
| const call = mockDailyLogFindMany.mock.calls[0][0]; | |
| const gteDate: Date = call.where.date.gte; | |
| // The route zeroes time to UTC midnight; gte is at midnight of (today - 7 days). | |
| // Tolerance: ±24h accounts for the midnight truncation at any time of day. | |
| expect(gteDate).toBeInstanceOf(Date); | |
| const nowMs = Date.now(); | |
| const diffMs = nowMs - gteDate.getTime(); | |
| const sevenDaysMs = 7 * 24 * 60 * 60 * 1000; | |
| const oneDayMs = 24 * 60 * 60 * 1000; | |
| expect(diffMs).toBeGreaterThanOrEqual(sevenDaysMs - oneDayMs); | |
| expect(diffMs).toBeLessThanOrEqual(sevenDaysMs + oneDayMs); | |
| }); | |
| it("queries daily logs with gte set to UTC midnight ~90 days ago when ?days=90", async () => { | |
| await GET(makeGet({ days: "90" })); | |
| const call = mockDailyLogFindMany.mock.calls[0][0]; | |
| const gteDate: Date = call.where.date.gte; | |
| expect(gteDate).toBeInstanceOf(Date); | |
| const nowMs = Date.now(); | |
| const diffMs = nowMs - gteDate.getTime(); | |
| const ninetyDaysMs = 90 * 24 * 60 * 60 * 1000; | |
| const oneDayMs = 24 * 60 * 60 * 1000; | |
| expect(diffMs).toBeGreaterThanOrEqual(ninetyDaysMs - oneDayMs); | |
| expect(diffMs).toBeLessThanOrEqual(ninetyDaysMs + oneDayMs); | |
| }); | |
| it("response includes windowDays alongside dailyXp, summary, etc.", async () => { | |
| const res = await GET(makeGet({ days: "7" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| expect(body).toHaveProperty("windowDays", 7); | |
| expect(body).toHaveProperty("dailyXp"); | |
| expect(body).toHaveProperty("summary"); | |
| expect(body).toHaveProperty("categoryBreakdown"); | |
| expect(body).toHaveProperty("recentActivities"); | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // Activity pagination (?activityOffset / ?activityLimit) | |
| // --------------------------------------------------------------------------- | |
| describe("GET /api/stats — activity pagination", () => { | |
| // Build a pool of 60 activities with sequential IDs | |
| const POOL = Array.from({ length: 60 }, (_, i) => | |
| makeActivity({ id: i + 1, totalXp: 10 + i, createdAt: new Date(Date.now() - i * 1000) }), | |
| ); | |
| beforeEach(() => { | |
| vi.clearAllMocks(); | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockDailyLogFindMany.mockResolvedValue([]); | |
| mockActivityFindMany.mockResolvedValue(POOL); | |
| }); | |
| it("returns activityTotal equal to all activities in the pool", async () => { | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| expect(body.activityTotal).toBe(60); | |
| }); | |
| it("returns first 25 activities by default (no offset/limit params)", async () => { | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(25); | |
| expect(activities[0].id).toBe(1); // most recent (index 0 in pool) | |
| expect(activities[24].id).toBe(25); | |
| }); | |
| it("respects activityOffset — skips the first N activities", async () => { | |
| const res = await GET(makeGet({ activityOffset: "25" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(25); | |
| expect(activities[0].id).toBe(26); | |
| expect(activities[24].id).toBe(50); | |
| }); | |
| it("respects activityLimit — returns fewer activities than default", async () => { | |
| const res = await GET(makeGet({ activityLimit: "10" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(10); | |
| }); | |
| it("respects both activityOffset and activityLimit together", async () => { | |
| const res = await GET(makeGet({ activityOffset: "10", activityLimit: "5" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(5); | |
| expect(activities[0].id).toBe(11); | |
| expect(activities[4].id).toBe(15); | |
| }); | |
| it("caps activityLimit at MAX (50)", async () => { | |
| const res = await GET(makeGet({ activityLimit: "9999" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(50); // pool has 60, but cap is 50 | |
| }); | |
| it("returns fewer than limit when near end of pool", async () => { | |
| const res = await GET(makeGet({ activityOffset: "55", activityLimit: "25" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(5); // only 5 left (55..59) | |
| }); | |
| it("returns empty array when offset equals pool size", async () => { | |
| const res = await GET(makeGet({ activityOffset: "60" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(0); | |
| }); | |
| it("returns empty array when offset exceeds pool size", async () => { | |
| const res = await GET(makeGet({ activityOffset: "100" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(0); | |
| }); | |
| it("treats invalid activityOffset as 0", async () => { | |
| const res = await GET(makeGet({ activityOffset: "abc" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(25); | |
| expect((activities[0] as Record<string, unknown>).id).toBe(1); | |
| }); | |
| it("treats invalid activityLimit as default (25)", async () => { | |
| const res = await GET(makeGet({ activityLimit: "banana" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(25); | |
| }); | |
| it("treats negative activityOffset as 0", async () => { | |
| const res = await GET(makeGet({ activityOffset: "-10" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities[0].id).toBe(1); | |
| }); | |
| it("activityTotal is stable regardless of pagination params", async () => { | |
| const [r1, r2] = await Promise.all([ | |
| GET(makeGet({ activityOffset: "0", activityLimit: "10" })), | |
| GET(makeGet({ activityOffset: "50", activityLimit: "10" })), | |
| ]); | |
| const b1 = await json(r1) as Record<string, unknown>; | |
| const b2 = await json(r2) as Record<string, unknown>; | |
| expect(b1.activityTotal).toBe(60); | |
| expect(b2.activityTotal).toBe(60); | |
| }); | |
| it("response always contains activityTotal field", async () => { | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| expect(body).toHaveProperty("activityTotal"); | |
| expect(typeof body.activityTotal).toBe("number"); | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // ?activityCategory filter | |
| // --------------------------------------------------------------------------- | |
| describe("GET /api/stats — ?activityCategory filter", () => { | |
| const CHESS_ACTIVITY = makeActivity({ | |
| id: 1, | |
| category: "chess", | |
| exerciseType: "chess-puzzle", | |
| totalXp: 40, | |
| }); | |
| const READING_ACTIVITY = makeActivity({ | |
| id: 2, | |
| category: "reading", | |
| exerciseType: "comprehension", | |
| totalXp: 50, | |
| }); | |
| const FEYNMAN_ACTIVITY = makeActivity({ | |
| id: 3, | |
| category: "feynman", | |
| exerciseType: "explain", | |
| totalXp: 60, | |
| }); | |
| const MIXED_POOL = [CHESS_ACTIVITY, READING_ACTIVITY, FEYNMAN_ACTIVITY]; | |
| beforeEach(() => { | |
| vi.clearAllMocks(); | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockDailyLogFindMany.mockResolvedValue([]); | |
| mockActivityFindMany.mockResolvedValue(MIXED_POOL); | |
| }); | |
| it("returns only chess activities when activityCategory=chess", async () => { | |
| const res = await GET(makeGet({ activityCategory: "chess" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(1); | |
| expect(activities[0].id).toBe(1); | |
| expect(activities[0].category).toBe("chess"); | |
| }); | |
| it("returns only reading activities when activityCategory=reading", async () => { | |
| const res = await GET(makeGet({ activityCategory: "reading" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(1); | |
| expect(activities[0].category).toBe("reading"); | |
| }); | |
| it("returns all activities when activityCategory=all", async () => { | |
| const res = await GET(makeGet({ activityCategory: "all" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(3); | |
| }); | |
| it("returns all activities when ?activityCategory is omitted", async () => { | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(3); | |
| }); | |
| it("treats an invalid category value as 'all' (returns all activities)", async () => { | |
| const res = await GET(makeGet({ activityCategory: "basketweaving" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(3); | |
| }); | |
| it("activityTotal reflects the filtered count, not the full pool", async () => { | |
| const res = await GET(makeGet({ activityCategory: "chess" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| expect(body.activityTotal).toBe(1); | |
| }); | |
| it("activityTotal is full pool size when no filter", async () => { | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| expect(body.activityTotal).toBe(3); | |
| }); | |
| it("activityCategory field in response is the active category when filtered", async () => { | |
| const res = await GET(makeGet({ activityCategory: "feynman" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| expect(body.activityCategory).toBe("feynman"); | |
| }); | |
| it("activityCategory field in response is null when no filter", async () => { | |
| const res = await GET(makeGet()); | |
| const body = await json(res) as Record<string, unknown>; | |
| expect(body.activityCategory).toBeNull(); | |
| }); | |
| it("activityCategory field in response is null when activityCategory=all", async () => { | |
| const res = await GET(makeGet({ activityCategory: "all" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| expect(body.activityCategory).toBeNull(); | |
| }); | |
| it("activityCategory field in response is null for invalid category", async () => { | |
| const res = await GET(makeGet({ activityCategory: "invalid" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| expect(body.activityCategory).toBeNull(); | |
| }); | |
| it("category breakdown is not affected by activityCategory filter (uses full pool)", async () => { | |
| const res = await GET(makeGet({ activityCategory: "chess" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const breakdown = body.categoryBreakdown as Record<string, Record<string, unknown>>; | |
| // All 3 categories still appear in breakdown | |
| expect(breakdown).toHaveProperty("chess"); | |
| expect(breakdown).toHaveProperty("reading"); | |
| expect(breakdown).toHaveProperty("feynman"); | |
| }); | |
| it("summary stats are not affected by activityCategory filter (uses full pool)", async () => { | |
| const res = await GET(makeGet({ activityCategory: "chess" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const summary = body.summary as Record<string, unknown>; | |
| // All 3 activities counted in summary despite chess-only filter | |
| expect(summary.totalExercises).toBe(3); | |
| }); | |
| it("category filter is case-insensitive (DB category stored as lowercase)", async () => { | |
| // Activity has category "chess" (lowercase), param is "chess" — should match | |
| const res = await GET(makeGet({ activityCategory: "chess" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(1); | |
| }); | |
| it("filter works with hyphenated category (critical-thinking)", async () => { | |
| const ctActivity = makeActivity({ | |
| id: 10, | |
| category: "critical-thinking", | |
| exerciseType: "flaw-finder", | |
| totalXp: 70, | |
| }); | |
| mockActivityFindMany.mockResolvedValue([...MIXED_POOL, ctActivity]); | |
| const res = await GET(makeGet({ activityCategory: "critical-thinking" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(1); | |
| expect(activities[0].id).toBe(10); | |
| }); | |
| it("returns empty activities (not 404) when filter matches no activities", async () => { | |
| const res = await GET(makeGet({ activityCategory: "quests" })); | |
| expect(res.status).toBe(200); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(0); | |
| expect(body.activityTotal).toBe(0); | |
| }); | |
| it("pagination still works within a filtered set", async () => { | |
| // Build 5 chess activities + 2 reading | |
| const pool = [ | |
| ...Array.from({ length: 5 }, (_, i) => | |
| makeActivity({ id: i + 1, category: "chess", totalXp: 10 }), | |
| ), | |
| makeActivity({ id: 10, category: "reading", totalXp: 10 }), | |
| makeActivity({ id: 11, category: "reading", totalXp: 10 }), | |
| ]; | |
| mockActivityFindMany.mockResolvedValue(pool); | |
| const res = await GET(makeGet({ activityCategory: "chess", activityOffset: "2", activityLimit: "2" })); | |
| const body = await json(res) as Record<string, unknown>; | |
| const activities = body.recentActivities as Array<Record<string, unknown>>; | |
| expect(activities).toHaveLength(2); | |
| expect(activities[0].id).toBe(3); // 3rd chess activity (0-indexed: [2]) | |
| expect(body.activityTotal).toBe(5); // only chess total | |
| }); | |
| }); | |