Download src/app/api/export/__tests__/route.test.ts from NAP1320/RotNot: direct link, hf CLI and curl.
- Browser
- Download file 13.3 kB
-
https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/app/api/export/__tests__/route.test.ts
- Command line
-
hf download hf://spaces/NAP1320/RotNot/src/app/api/export/__tests__/route.test.ts
-
curl -L -o route.test.ts https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/app/api/export/__tests__/route.test.ts
13.3 kB
| /** | |
| * Tests for GET /api/export | |
| * | |
| * Covers: | |
| * - 404 when no user found | |
| * - 200 response with Content-Type application/json | |
| * - Content-Disposition header includes attachment and filename with today's date | |
| * - Response body passes through buildExport shape (exportVersion, exportedAt, profile, etc.) | |
| * - Parallel DB queries: categorySkills, activities, dailyLogs, unlocks, spacedRepetition | |
| * - Unlocks query includes node relation with correct select fields | |
| * - DB errors propagate as 500 via withApiError | |
| * - Empty data sets return valid export (empty arrays) | |
| * - Response body is valid JSON (double-indented) | |
| */ | |
| 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(); | |
| const mockSrFindMany = 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) }, | |
| spacedRepetitionItem: { | |
| findMany: (...args: unknown[]) => mockSrFindMany(...args), | |
| }, | |
| }, | |
| })); | |
| import { GET } from "../route"; | |
| // --------------------------------------------------------------------------- | |
| // Fixtures | |
| // --------------------------------------------------------------------------- | |
| const baseUser = { | |
| id: 1, | |
| name: "Player One", | |
| level: 3, | |
| totalXp: 600, | |
| currentXp: 100, | |
| title: "Apprentice", | |
| dailyGoalXp: 100, | |
| streak: 5, | |
| longestStreak: 12, | |
| streakFreezes: 2, | |
| lichessUsername: null, | |
| chesscomUsername: null, | |
| createdAt: new Date("2026-01-01T00:00:00.000Z"), | |
| updatedAt: new Date("2026-03-01T00:00:00.000Z"), | |
| }; | |
| const baseSkills = [ | |
| { | |
| id: 10, | |
| userId: 1, | |
| category: "CHESS", | |
| level: 2, | |
| totalXp: 300, | |
| currentXp: 50, | |
| xpToNext: 150, | |
| createdAt: new Date("2026-01-01T00:00:00.000Z"), | |
| updatedAt: new Date("2026-02-01T00:00:00.000Z"), | |
| }, | |
| ]; | |
| const baseActivities = [ | |
| { | |
| id: 100, | |
| userId: 1, | |
| category: "CHESS", | |
| exerciseType: "puzzle", | |
| xpEarned: 30, | |
| score: 0.9, | |
| durationSeconds: 120, | |
| metadata: null, | |
| createdAt: new Date("2026-03-10T12:00:00.000Z"), | |
| }, | |
| ]; | |
| const baseDailyLogs = [ | |
| { | |
| id: 200, | |
| userId: 1, | |
| date: new Date("2026-03-10T00:00:00.000Z"), | |
| xpEarned: 90, | |
| goalMet: false, | |
| streakFreezeUsed: false, | |
| createdAt: new Date("2026-03-10T00:00:00.000Z"), | |
| updatedAt: new Date("2026-03-10T23:59:00.000Z"), | |
| }, | |
| ]; | |
| const baseUnlocks = [ | |
| { | |
| id: 300, | |
| userId: 1, | |
| nodeId: 5, | |
| unlockedAt: new Date("2026-03-01T00:00:00.000Z"), | |
| node: { | |
| category: "CHESS", | |
| name: "Opening Theory", | |
| nodeType: "SKILL", | |
| levelRequired: 2, | |
| }, | |
| }, | |
| ]; | |
| const baseSR = [ | |
| { | |
| id: 400, | |
| userId: 1, | |
| topicId: "topic-1", | |
| stage: 2, | |
| nextReviewAt: new Date("2026-03-25T00:00:00.000Z"), | |
| lastReviewAt: new Date("2026-03-18T00:00:00.000Z"), | |
| lastScore: 0.85, | |
| totalReviews: 3, | |
| successCount: 2, | |
| createdAt: new Date("2026-03-10T00:00:00.000Z"), | |
| updatedAt: new Date("2026-03-18T00:00:00.000Z"), | |
| }, | |
| ]; | |
| function makeRequest() { | |
| return new NextRequest("http://localhost/api/export"); | |
| } | |
| function setupHappyPath() { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockCategorySkillFindMany.mockResolvedValue(baseSkills); | |
| mockActivityFindMany.mockResolvedValue(baseActivities); | |
| mockDailyLogFindMany.mockResolvedValue(baseDailyLogs); | |
| mockUnlockFindMany.mockResolvedValue(baseUnlocks); | |
| mockSrFindMany.mockResolvedValue(baseSR); | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Tests | |
| // --------------------------------------------------------------------------- | |
| describe("GET /api/export", () => { | |
| beforeEach(() => { | |
| vi.clearAllMocks(); | |
| }); | |
| // ------------------------------------------------------------------------- | |
| // 404 / user not found | |
| // ------------------------------------------------------------------------- | |
| it("returns 404 when no user found", async () => { | |
| mockUserFindFirst.mockResolvedValue(null); | |
| mockCategorySkillFindMany.mockResolvedValue([]); | |
| mockActivityFindMany.mockResolvedValue([]); | |
| mockDailyLogFindMany.mockResolvedValue([]); | |
| mockUnlockFindMany.mockResolvedValue([]); | |
| mockSrFindMany.mockResolvedValue([]); | |
| const res = await GET(makeRequest()); | |
| expect(res.status).toBe(404); | |
| const body = await res.json(); | |
| expect(body.error).toBeDefined(); | |
| }); | |
| // ------------------------------------------------------------------------- | |
| // Happy path — response headers | |
| // ------------------------------------------------------------------------- | |
| it("returns 200 on success", async () => { | |
| setupHappyPath(); | |
| const res = await GET(makeRequest()); | |
| expect(res.status).toBe(200); | |
| }); | |
| it("sets Content-Type to application/json", async () => { | |
| setupHappyPath(); | |
| const res = await GET(makeRequest()); | |
| expect(res.headers.get("content-type")).toBe("application/json"); | |
| }); | |
| it("sets Content-Disposition as attachment with a filename", async () => { | |
| setupHappyPath(); | |
| const res = await GET(makeRequest()); | |
| const disposition = res.headers.get("content-disposition"); | |
| expect(disposition).toMatch(/attachment/); | |
| expect(disposition).toMatch(/rotnot-export-/); | |
| expect(disposition).toMatch(/\.json/); | |
| }); | |
| it("includes today's date in the Content-Disposition filename", async () => { | |
| setupHappyPath(); | |
| const res = await GET(makeRequest()); | |
| const disposition = res.headers.get("content-disposition") ?? ""; | |
| const today = new Date().toISOString().slice(0, 10); // YYYY-MM-DD | |
| expect(disposition).toContain(today); | |
| }); | |
| // ------------------------------------------------------------------------- | |
| // Response body shape | |
| // ------------------------------------------------------------------------- | |
| it("response body is valid JSON", async () => { | |
| setupHappyPath(); | |
| const res = await GET(makeRequest()); | |
| const text = await res.text(); | |
| expect(() => JSON.parse(text)).not.toThrow(); | |
| }); | |
| it("response body contains exportVersion: 1", async () => { | |
| setupHappyPath(); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json(); | |
| expect(body.exportVersion).toBe(1); | |
| }); | |
| it("response body contains exportedAt ISO string", async () => { | |
| setupHappyPath(); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json(); | |
| expect(typeof body.exportedAt).toBe("string"); | |
| expect(() => new Date(body.exportedAt)).not.toThrow(); | |
| }); | |
| it("response body contains profile section", async () => { | |
| setupHappyPath(); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json(); | |
| expect(body.profile).toBeDefined(); | |
| expect(body.profile.name).toBe("Player One"); | |
| }); | |
| it("response body contains categorySkills array", async () => { | |
| setupHappyPath(); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json(); | |
| expect(Array.isArray(body.categorySkills)).toBe(true); | |
| expect(body.categorySkills).toHaveLength(1); | |
| expect(body.categorySkills[0].category).toBe("CHESS"); | |
| }); | |
| it("response body contains activities array", async () => { | |
| setupHappyPath(); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json(); | |
| expect(Array.isArray(body.activities)).toBe(true); | |
| expect(body.activities).toHaveLength(1); | |
| }); | |
| it("response body contains dailyLogs array", async () => { | |
| setupHappyPath(); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json(); | |
| expect(Array.isArray(body.dailyLogs)).toBe(true); | |
| expect(body.dailyLogs).toHaveLength(1); | |
| }); | |
| it("response body contains unlocks array", async () => { | |
| setupHappyPath(); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json(); | |
| expect(Array.isArray(body.unlocks)).toBe(true); | |
| expect(body.unlocks).toHaveLength(1); | |
| expect(body.unlocks[0].nodeName).toBe("Opening Theory"); | |
| }); | |
| it("response body contains spacedRepetition array", async () => { | |
| setupHappyPath(); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json(); | |
| expect(Array.isArray(body.spacedRepetition)).toBe(true); | |
| expect(body.spacedRepetition).toHaveLength(1); | |
| expect(body.spacedRepetition[0].topicId).toBe("topic-1"); | |
| }); | |
| it("response body contains summary section", async () => { | |
| setupHappyPath(); | |
| const res = await GET(makeRequest()); | |
| const body = await res.json(); | |
| expect(body.summary).toBeDefined(); | |
| expect(typeof body.summary.totalActivities).toBe("number"); | |
| }); | |
| // ------------------------------------------------------------------------- | |
| // Empty data — valid export with empty arrays | |
| // ------------------------------------------------------------------------- | |
| it("handles empty data sets gracefully", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockCategorySkillFindMany.mockResolvedValue([]); | |
| mockActivityFindMany.mockResolvedValue([]); | |
| mockDailyLogFindMany.mockResolvedValue([]); | |
| mockUnlockFindMany.mockResolvedValue([]); | |
| mockSrFindMany.mockResolvedValue([]); | |
| const res = await GET(makeRequest()); | |
| expect(res.status).toBe(200); | |
| const body = await res.json(); | |
| expect(body.categorySkills).toEqual([]); | |
| expect(body.activities).toEqual([]); | |
| expect(body.dailyLogs).toEqual([]); | |
| expect(body.unlocks).toEqual([]); | |
| expect(body.spacedRepetition).toEqual([]); | |
| }); | |
| // ------------------------------------------------------------------------- | |
| // DB query parameters | |
| // ------------------------------------------------------------------------- | |
| it("queries user with id: 1", async () => { | |
| setupHappyPath(); | |
| await GET(makeRequest()); | |
| expect(mockUserFindFirst).toHaveBeenCalledWith({ where: { id: 1 } }); | |
| }); | |
| it("queries categorySkills filtered to userId 1 ordered by category asc", async () => { | |
| setupHappyPath(); | |
| await GET(makeRequest()); | |
| expect(mockCategorySkillFindMany).toHaveBeenCalledWith({ | |
| where: { userId: 1 }, | |
| orderBy: { category: "asc" }, | |
| }); | |
| }); | |
| it("queries activities filtered to userId 1 ordered by createdAt desc", async () => { | |
| setupHappyPath(); | |
| await GET(makeRequest()); | |
| expect(mockActivityFindMany).toHaveBeenCalledWith({ | |
| where: { userId: 1 }, | |
| orderBy: { createdAt: "desc" }, | |
| }); | |
| }); | |
| it("queries dailyLogs filtered to userId 1 ordered by date asc", async () => { | |
| setupHappyPath(); | |
| await GET(makeRequest()); | |
| expect(mockDailyLogFindMany).toHaveBeenCalledWith({ | |
| where: { userId: 1 }, | |
| orderBy: { date: "asc" }, | |
| }); | |
| }); | |
| it("queries unlocks with node include selecting category, name, nodeType, levelRequired", async () => { | |
| setupHappyPath(); | |
| await GET(makeRequest()); | |
| expect(mockUnlockFindMany).toHaveBeenCalledWith( | |
| expect.objectContaining({ | |
| where: { userId: 1 }, | |
| include: { | |
| node: { | |
| select: { | |
| category: true, | |
| name: true, | |
| nodeType: true, | |
| levelRequired: true, | |
| }, | |
| }, | |
| }, | |
| }) | |
| ); | |
| }); | |
| it("queries spacedRepetitionItem filtered to userId 1 ordered by createdAt asc", async () => { | |
| setupHappyPath(); | |
| await GET(makeRequest()); | |
| expect(mockSrFindMany).toHaveBeenCalledWith({ | |
| where: { userId: 1 }, | |
| orderBy: { createdAt: "asc" }, | |
| }); | |
| }); | |
| // ------------------------------------------------------------------------- | |
| // Error propagation | |
| // ------------------------------------------------------------------------- | |
| it("returns 500 when DB throws on user lookup", async () => { | |
| mockUserFindFirst.mockRejectedValue(new Error("DB offline")); | |
| // Other mocks don't matter — Promise.all won't be reached | |
| mockCategorySkillFindMany.mockResolvedValue([]); | |
| mockActivityFindMany.mockResolvedValue([]); | |
| mockDailyLogFindMany.mockResolvedValue([]); | |
| mockUnlockFindMany.mockResolvedValue([]); | |
| mockSrFindMany.mockResolvedValue([]); | |
| const res = await GET(makeRequest()); | |
| expect(res.status).toBe(500); | |
| }); | |
| it("returns 500 when a parallel DB query throws", async () => { | |
| mockUserFindFirst.mockResolvedValue(baseUser); | |
| mockCategorySkillFindMany.mockRejectedValue(new Error("query failed")); | |
| mockActivityFindMany.mockResolvedValue([]); | |
| mockDailyLogFindMany.mockResolvedValue([]); | |
| mockUnlockFindMany.mockResolvedValue([]); | |
| mockSrFindMany.mockResolvedValue([]); | |
| const res = await GET(makeRequest()); | |
| expect(res.status).toBe(500); | |
| }); | |
| }); | |