Download src/app/api/stats/__tests__/achievements.test.ts from NAP1320/RotNot: direct link, hf CLI and curl.
- Browser
- Download file 19.2 kB
-
https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/app/api/stats/__tests__/achievements.test.ts
- Command line
-
hf download hf://spaces/NAP1320/RotNot/src/app/api/stats/__tests__/achievements.test.ts
-
curl -L -o achievements.test.ts https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/app/api/stats/__tests__/achievements.test.ts
19.2 kB
| /** | |
| * Tests for GET /api/stats/achievements | |
| * | |
| * Covers: | |
| * - 404 when no user found | |
| * - 500 on DB error (propagated via withApiError) | |
| * - response shape: achievements array + summary object | |
| * - achievements: each item has required fields (id, name, description, tier, icon, earned, earnedAt, progress) | |
| * - achievements: no duplicate IDs | |
| * - achievements: all tiers are valid strings | |
| * - achievements: earned=true items have earnedAt ISO string, unearned have earnedAt=null | |
| * - achievements: progress in [0, 100] | |
| * - summary: total matches achievements.length | |
| * - summary: earned matches sum of earned items | |
| * - summary: byTier counts sum to earned count | |
| * - summary: contains bronze/silver/gold/platinum keys | |
| * - DB query validation: user/categorySkills/activities/dailyLogs/unlocks all queried for userId=1 | |
| * - earned achievements reflect actual DB data (level milestone earned when user.level >= threshold) | |
| * - unearned achievements reflect actual DB data (level milestone not earned when level too low) | |
| * - activities passed to computeAchievements (critical hit milestone) | |
| * - dailyLogs passed to computeAchievements (goal-met milestone) | |
| * - unlocks passed to computeAchievements (unlock milestone) | |
| */ | |
| import { describe, it, expect, vi, beforeEach } from "vitest"; | |
| import { NextRequest } from "next/server"; | |
| // --------------------------------------------------------------------------- | |
| // Mock prisma | |
| // --------------------------------------------------------------------------- | |
| const mockUserFindFirst = vi.fn(); | |
| const mockCategorySkillFindMany = vi.fn(); | |
| const mockActivityFindMany = vi.fn(); | |
| const mockDailyLogFindMany = vi.fn(); | |
| const mockUnlockFindMany = vi.fn(); | |
| vi.mock("@/lib/db", () => ({ | |
| prisma: { | |
| user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) }, | |
| categorySkill: { findMany: (...args: unknown[]) => mockCategorySkillFindMany(...args) }, | |
| activity: { findMany: (...args: unknown[]) => mockActivityFindMany(...args) }, | |
| dailyLog: { findMany: (...args: unknown[]) => mockDailyLogFindMany(...args) }, | |
| unlock: { findMany: (...args: unknown[]) => mockUnlockFindMany(...args) }, | |
| }, | |
| })); | |
| import { GET } from "../achievements/route"; | |
| // --------------------------------------------------------------------------- | |
| // Fixtures | |
| // --------------------------------------------------------------------------- | |
| const baseUser = { | |
| level: 1, | |
| totalXp: 0, | |
| streak: 0, | |
| longestStreak: 0, | |
| createdAt: new Date("2026-01-01T00:00:00Z"), | |
| }; | |
| function makeRequest(): NextRequest { | |
| return new NextRequest("http://localhost/api/stats/achievements"); | |
| } | |
| function makeActivity(overrides: Partial<{ | |
| category: string; | |
| exerciseType: string; | |
| isCriticalHit: boolean; | |
| score: number | null; | |
| durationSecs: number | null; | |
| createdAt: Date; | |
| metadata: string | null; | |
| }> = {}) { | |
| return { | |
| category: "logic", | |
| exerciseType: "sudoku", | |
| isCriticalHit: false, | |
| score: 0.8, | |
| durationSecs: 120, | |
| createdAt: new Date("2026-03-01T10:00:00Z"), | |
| metadata: null, | |
| ...overrides, | |
| }; | |
| } | |
| function makeLog(overrides: Partial<{ | |
| date: Date; | |
| goalMet: boolean; | |
| activityCount: number; | |
| }> = {}) { | |
| return { | |
| date: new Date("2026-03-01T00:00:00Z"), | |
| goalMet: false, | |
| activityCount: 1, | |
| ...overrides, | |
| }; | |
| } | |
| function makeUnlock(overrides: Partial<{ unlockedAt: Date }> = {}) { | |
| return { | |
| unlockedAt: new Date("2026-03-01T00:00:00Z"), | |
| ...overrides, | |
| }; | |
| } | |
| // --------------------------------------------------------------------------- | |
| // beforeEach: reset mocks and set default happy-path returns | |
| // --------------------------------------------------------------------------- | |
| beforeEach(() => { | |
| vi.clearAllMocks(); | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockCategorySkillFindMany.mockResolvedValue([]); | |
| mockActivityFindMany.mockResolvedValue([]); | |
| mockDailyLogFindMany.mockResolvedValue([]); | |
| mockUnlockFindMany.mockResolvedValue([]); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // 404 / error paths | |
| // --------------------------------------------------------------------------- | |
| describe("GET /api/stats/achievements — error paths", () => { | |
| it("returns 404 when no user found", async () => { | |
| mockUserFindFirst.mockResolvedValue(null); | |
| const res = await GET(makeRequest()); | |
| expect(res.status).toBe(404); | |
| const body = await res.json() as Record<string, unknown>; | |
| expect(body.error).toBeDefined(); | |
| }); | |
| it("propagates DB errors as 500", async () => { | |
| mockUserFindFirst.mockRejectedValue(new Error("DB connection failed")); | |
| const res = await GET(makeRequest()); | |
| expect(res.status).toBe(500); | |
| }); | |
| it("propagates parallel query errors as 500", async () => { | |
| mockActivityFindMany.mockRejectedValue(new Error("activity query failed")); | |
| const res = await GET(makeRequest()); | |
| expect(res.status).toBe(500); | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // Response shape | |
| // --------------------------------------------------------------------------- | |
| describe("GET /api/stats/achievements — response shape", () => { | |
| it("returns 200 with achievements array and summary object", async () => { | |
| const res = await GET(makeRequest()); | |
| expect(res.status).toBe(200); | |
| const body = await res.json() as Record<string, unknown>; | |
| expect(Array.isArray(body.achievements)).toBe(true); | |
| expect(typeof body.summary).toBe("object"); | |
| expect(body.summary).not.toBeNull(); | |
| }); | |
| it("achievements array is non-empty", async () => { | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { achievements: unknown[] }; | |
| expect(body.achievements.length).toBeGreaterThan(0); | |
| }); | |
| it("each achievement has required fields", async () => { | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { | |
| achievements: Array<Record<string, unknown>>; | |
| }; | |
| for (const a of body.achievements) { | |
| expect(typeof a.id).toBe("string"); | |
| expect(typeof a.name).toBe("string"); | |
| expect(typeof a.description).toBe("string"); | |
| expect(typeof a.tier).toBe("string"); | |
| expect(typeof a.icon).toBe("string"); | |
| expect(typeof a.earned).toBe("boolean"); | |
| expect(typeof a.progress).toBe("number"); | |
| // earnedAt is string | null | |
| expect(a.earnedAt === null || typeof a.earnedAt === "string").toBe(true); | |
| } | |
| }); | |
| it("achievement IDs are unique", async () => { | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { achievements: Array<{ id: string }> }; | |
| const ids = body.achievements.map((a) => a.id); | |
| const uniqueIds = new Set(ids); | |
| expect(uniqueIds.size).toBe(ids.length); | |
| }); | |
| it("achievement tiers are valid values", async () => { | |
| const validTiers = new Set(["bronze", "silver", "gold", "platinum"]); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { achievements: Array<{ tier: string }> }; | |
| for (const a of body.achievements) { | |
| expect(validTiers.has(a.tier)).toBe(true); | |
| } | |
| }); | |
| it("progress values are in [0, 100]", async () => { | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { achievements: Array<{ progress: number }> }; | |
| for (const a of body.achievements) { | |
| expect(a.progress).toBeGreaterThanOrEqual(0); | |
| expect(a.progress).toBeLessThanOrEqual(100); | |
| } | |
| }); | |
| it("earned achievements have earnedAt as ISO string", async () => { | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { | |
| achievements: Array<{ earned: boolean; earnedAt: string | null }>; | |
| }; | |
| const earned = body.achievements.filter((a) => a.earned); | |
| // With base user (level 1, 0 XP, 0 activities) the "first solve" type | |
| // milestones won't be earned, but if any are, earnedAt must be a string. | |
| for (const a of earned) { | |
| expect(typeof a.earnedAt).toBe("string"); | |
| } | |
| }); | |
| it("unearned achievements have earnedAt=null", async () => { | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { | |
| achievements: Array<{ earned: boolean; earnedAt: string | null }>; | |
| }; | |
| const unearned = body.achievements.filter((a) => !a.earned); | |
| expect(unearned.length).toBeGreaterThan(0); // with level 1 / 0 XP, most are unearned | |
| for (const a of unearned) { | |
| expect(a.earnedAt).toBeNull(); | |
| } | |
| }); | |
| it("earned progress is capped at 100", async () => { | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { | |
| achievements: Array<{ earned: boolean; progress: number }>; | |
| }; | |
| const earned = body.achievements.filter((a) => a.earned); | |
| for (const a of earned) { | |
| expect(a.progress).toBe(100); | |
| } | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // Summary shape | |
| // --------------------------------------------------------------------------- | |
| describe("GET /api/stats/achievements — summary", () => { | |
| it("summary.total equals achievements.length", async () => { | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { | |
| achievements: unknown[]; | |
| summary: { total: number }; | |
| }; | |
| expect(body.summary.total).toBe(body.achievements.length); | |
| }); | |
| it("summary.earned equals count of earned achievements", async () => { | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { | |
| achievements: Array<{ earned: boolean }>; | |
| summary: { earned: number }; | |
| }; | |
| const earnedCount = body.achievements.filter((a) => a.earned).length; | |
| expect(body.summary.earned).toBe(earnedCount); | |
| }); | |
| it("summary.byTier has bronze/silver/gold/platinum keys with total and earned", async () => { | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { | |
| summary: { byTier: Record<string, { total: number; earned: number }> }; | |
| }; | |
| for (const tier of ["bronze", "silver", "gold", "platinum"]) { | |
| expect(typeof body.summary.byTier[tier].total).toBe("number"); | |
| expect(typeof body.summary.byTier[tier].earned).toBe("number"); | |
| } | |
| }); | |
| it("byTier earned counts sum to summary.earned", async () => { | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { | |
| summary: { | |
| earned: number; | |
| byTier: Record<string, { total: number; earned: number }>; | |
| }; | |
| }; | |
| const tierEarnedSum = | |
| body.summary.byTier.bronze.earned + | |
| body.summary.byTier.silver.earned + | |
| body.summary.byTier.gold.earned + | |
| body.summary.byTier.platinum.earned; | |
| expect(tierEarnedSum).toBe(body.summary.earned); | |
| }); | |
| it("byTier total counts sum to summary.total", async () => { | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { | |
| summary: { | |
| total: number; | |
| byTier: Record<string, { total: number; earned: number }>; | |
| }; | |
| }; | |
| const tierTotalSum = | |
| body.summary.byTier.bronze.total + | |
| body.summary.byTier.silver.total + | |
| body.summary.byTier.gold.total + | |
| body.summary.byTier.platinum.total; | |
| expect(tierTotalSum).toBe(body.summary.total); | |
| }); | |
| it("summary.earned is 0 for a brand-new user with no data", async () => { | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { summary: { earned: number } }; | |
| // Brand-new user: level 1, 0 XP, no activities — expect 0 earned | |
| expect(body.summary.earned).toBe(0); | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // DB query validation | |
| // --------------------------------------------------------------------------- | |
| describe("GET /api/stats/achievements — DB queries", () => { | |
| it("queries user with userId=1", async () => { | |
| await GET(makeRequest()); | |
| expect(mockUserFindFirst).toHaveBeenCalledWith( | |
| expect.objectContaining({ where: { id: 1 } }) | |
| ); | |
| }); | |
| it("queries categorySkills with userId=1", async () => { | |
| await GET(makeRequest()); | |
| expect(mockCategorySkillFindMany).toHaveBeenCalledWith( | |
| expect.objectContaining({ where: { userId: 1 } }) | |
| ); | |
| }); | |
| it("queries activities with userId=1", async () => { | |
| await GET(makeRequest()); | |
| expect(mockActivityFindMany).toHaveBeenCalledWith( | |
| expect.objectContaining({ where: { userId: 1 } }) | |
| ); | |
| }); | |
| it("queries dailyLogs with userId=1", async () => { | |
| await GET(makeRequest()); | |
| expect(mockDailyLogFindMany).toHaveBeenCalledWith( | |
| expect.objectContaining({ where: { userId: 1 } }) | |
| ); | |
| }); | |
| it("queries unlocks with userId=1", async () => { | |
| await GET(makeRequest()); | |
| expect(mockUnlockFindMany).toHaveBeenCalledWith( | |
| expect.objectContaining({ where: { userId: 1 } }) | |
| ); | |
| }); | |
| it("selects required user fields", async () => { | |
| await GET(makeRequest()); | |
| expect(mockUserFindFirst).toHaveBeenCalledWith( | |
| expect.objectContaining({ | |
| select: expect.objectContaining({ | |
| level: true, | |
| totalXp: true, | |
| streak: true, | |
| longestStreak: true, | |
| createdAt: true, | |
| }), | |
| }) | |
| ); | |
| }); | |
| it("orders activities by createdAt asc", async () => { | |
| await GET(makeRequest()); | |
| expect(mockActivityFindMany).toHaveBeenCalledWith( | |
| expect.objectContaining({ | |
| orderBy: { createdAt: "asc" }, | |
| }) | |
| ); | |
| }); | |
| it("orders unlocks by unlockedAt asc", async () => { | |
| await GET(makeRequest()); | |
| expect(mockUnlockFindMany).toHaveBeenCalledWith( | |
| expect.objectContaining({ | |
| orderBy: { unlockedAt: "asc" }, | |
| }) | |
| ); | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // Data-driven: achievements earned / unearned based on DB content | |
| // --------------------------------------------------------------------------- | |
| describe("GET /api/stats/achievements — earned based on DB data", () => { | |
| it("level-5 bronze achievement earned when user.level >= 5", async () => { | |
| mockUserFindFirst.mockResolvedValue({ ...baseUser, level: 5, totalXp: 800 }); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { achievements: Array<{ id: string; earned: boolean; progress: number }> }; | |
| const level5 = body.achievements.find((a) => a.id === "level-5"); | |
| expect(level5).toBeDefined(); | |
| expect(level5!.earned).toBe(true); | |
| expect(level5!.progress).toBe(100); | |
| }); | |
| it("level-5 bronze achievement not earned when user.level < 5", async () => { | |
| mockUserFindFirst.mockResolvedValue({ ...baseUser, level: 3, totalXp: 200 }); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { achievements: Array<{ id: string; earned: boolean; progress: number }> }; | |
| const level5 = body.achievements.find((a) => a.id === "level-5"); | |
| expect(level5).toBeDefined(); | |
| expect(level5!.earned).toBe(false); | |
| expect(level5!.progress).toBeLessThan(100); | |
| }); | |
| it("xp-1000 bronze achievement earned when totalXp >= 1000", async () => { | |
| mockUserFindFirst.mockResolvedValue({ ...baseUser, level: 5, totalXp: 1000 }); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { achievements: Array<{ id: string; earned: boolean }> }; | |
| const xp1k = body.achievements.find((a) => a.id === "xp-1000"); | |
| expect(xp1k).toBeDefined(); | |
| expect(xp1k!.earned).toBe(true); | |
| }); | |
| it("streak-7 silver achievement earned when longestStreak >= 7", async () => { | |
| mockUserFindFirst.mockResolvedValue({ ...baseUser, longestStreak: 7 }); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { achievements: Array<{ id: string; earned: boolean }> }; | |
| const s7 = body.achievements.find((a) => a.id === "streak-7"); | |
| expect(s7).toBeDefined(); | |
| expect(s7!.earned).toBe(true); | |
| }); | |
| it("critical hit achievement earned when isCriticalHit activities exist", async () => { | |
| mockActivityFindMany.mockResolvedValue([ | |
| makeActivity({ isCriticalHit: true }), | |
| ]); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { achievements: Array<{ id: string; earned: boolean }> }; | |
| const crit1 = body.achievements.find((a) => a.id === "crit-1"); | |
| expect(crit1).toBeDefined(); | |
| expect(crit1!.earned).toBe(true); | |
| }); | |
| it("goals-7 achievement earned when 7+ dailyLogs have goalMet=true", async () => { | |
| const logs = Array.from({ length: 7 }, (_, i) => | |
| makeLog({ | |
| date: new Date(`2026-03-${String(i + 1).padStart(2, "0")}T00:00:00Z`), | |
| goalMet: true, | |
| }) | |
| ); | |
| mockDailyLogFindMany.mockResolvedValue(logs); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { achievements: Array<{ id: string; earned: boolean }> }; | |
| const goal7 = body.achievements.find((a) => a.id === "goals-7"); | |
| expect(goal7).toBeDefined(); | |
| expect(goal7!.earned).toBe(true); | |
| }); | |
| it("unlock-1 achievement earned when at least 1 unlock exists", async () => { | |
| mockUnlockFindMany.mockResolvedValue([makeUnlock()]); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { achievements: Array<{ id: string; earned: boolean }> }; | |
| const u1 = body.achievements.find((a) => a.id === "unlock-1"); | |
| expect(u1).toBeDefined(); | |
| expect(u1!.earned).toBe(true); | |
| }); | |
| it("summary.earned increases when user data crosses thresholds", async () => { | |
| // First call: brand-new user | |
| const res1 = await GET(makeRequest()); | |
| const body1 = await res1.json() as { summary: { earned: number } }; | |
| const earnedBefore = body1.summary.earned; | |
| // Second call: user with level 5 | |
| mockUserFindFirst.mockResolvedValue({ ...baseUser, level: 5, totalXp: 1000 }); | |
| const res2 = await GET(makeRequest()); | |
| const body2 = await res2.json() as { summary: { earned: number } }; | |
| expect(body2.summary.earned).toBeGreaterThan(earnedBefore); | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // categorySkills passed through (mastery achievements) | |
| // --------------------------------------------------------------------------- | |
| describe("GET /api/stats/achievements — categorySkills data", () => { | |
| it("chess mastery-5 achievement earned when chess level >= 5", async () => { | |
| mockCategorySkillFindMany.mockResolvedValue([ | |
| { category: "chess", level: 5, totalXp: 500 }, | |
| ]); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { achievements: Array<{ id: string; earned: boolean }> }; | |
| const chessL5 = body.achievements.find((a) => a.id === "chess-level-5"); | |
| expect(chessL5).toBeDefined(); | |
| expect(chessL5!.earned).toBe(true); | |
| }); | |
| it("chess mastery-5 not earned when chess level < 5", async () => { | |
| mockCategorySkillFindMany.mockResolvedValue([ | |
| { category: "chess", level: 2, totalXp: 100 }, | |
| ]); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json() as { achievements: Array<{ id: string; earned: boolean }> }; | |
| const chessL5 = body.achievements.find((a) => a.id === "chess-level-5"); | |
| expect(chessL5).toBeDefined(); | |
| expect(chessL5!.earned).toBe(false); | |
| }); | |
| }); | |