File size: 20,548 Bytes
9580dce | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 | /**
* 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<unknown> {
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<string, unknown>;
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<string, unknown>;
const user = body.user as Record<string, unknown>;
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<string, unknown>;
const user = body.user as Record<string, unknown>;
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<string, unknown>;
const stats = body.stats as Record<string, unknown>;
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<string, unknown>;
const stats = body.stats as Record<string, unknown>;
// 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<string, unknown>;
const stats = body.stats as Record<string, unknown>;
// 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<string, unknown>;
const stats = body.stats as Record<string, unknown>;
const byCat = stats.exercisesByCat as Record<string, number>;
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<string, unknown>;
const skills = body.categorySkills as Array<Record<string, unknown>>;
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<string, unknown>;
const skillTree = body.skillTree as Array<Record<string, unknown>>;
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<string, unknown>;
const unlocks = body.unlocks as Array<Record<string, unknown>>;
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<string, unknown>;
const stats = body.stats as Record<string, unknown>;
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<string, unknown>;
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<string, unknown>;
const skillTree = body.skillTree as Array<Record<string, unknown>>;
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<string, unknown>;
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<string, unknown>;
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<string, unknown>;
const stats = body.chesscomStats as Record<string, unknown>;
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<string, unknown>;
const stats = body.chesscomStats as Record<string, unknown>;
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<string, unknown>;
// 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<string, unknown>;
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<string, unknown>;
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<string, unknown>;
const activity = body.dailyActivity as Array<Record<string, unknown>>;
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<string, unknown>;
const where = callArgs.where as Record<string, unknown>;
const dateFilter = (where.date as Record<string, unknown>).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<string, unknown>;
const where = callArgs.where as Record<string, unknown>;
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<string, unknown>;
const select = callArgs.select as Record<string, unknown>;
expect(select).toHaveProperty("date");
expect(select).toHaveProperty("xpEarned");
expect(select).toHaveProperty("activityCount");
expect(select).toHaveProperty("goalMet");
});
});
|