RotNot / src /app /api /reading /__tests__ /routes.test.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
42.2 kB
/** * Tests for Reading API route handlers. * * Covers: * GET /api/reading/content * - list mode: returns article metadata (no body field) * - slug mode: returns specific article; 404 on unknown slug * - random mode: returns some article; respects difficulty filter * * POST /api/reading/fetch * - invalid JSON body β†’ 400 * - missing url and text β†’ 400 * - invalid URL format β†’ 400 * - non-http/https protocol β†’ 400 * - URL fetch: delegates to fetchAndExtract, returns { article, source: "url" } * - URL fetch error: propagates error message as 422 * - text paste: delegates to createFromText, returns { article, source: "text" } * - text paste error: propagates error message as 422 * * POST /api/reading/questions * - API key guard (503 when missing, no Claude call) * - invalid JSON body β†’ 400 * - missing slug and content β†’ 400 * - invalid slug β†’ 404 * - valid content object accepted alongside slug * - Claude called with article title and body in prompt * - haiku model used * - returns { questions } array on success * - invalid JSON from Claude β†’ 500 * - network error from Claude β†’ 500 * * POST /api/reading/score * - API key guard (503 when missing, no Claude call) * - invalid JSON body β†’ 400 * - missing answers/questions β†’ 400 * - invalid slug β†’ 404 * - missing content object β†’ 400 * - user not found β†’ 404 * - missing reading CategorySkill β†’ 500 * - Claude integration: prompt includes article title + QA pairs * - haiku model used * - invalid JSON from Claude β†’ 500 * - network error from Claude β†’ 500 * - response shape: scores, overallFeedback, avgScore, xp, levelUp, categoryXp, unlocks * - XP: quality score derived from avgScore/10; qualityBonus for high scores * - XP: critical hit doubles totalXp * - XP: multiplier bonus reflected in response * - custom content: sets isCustomContent path (exerciseType "comprehension-custom") * - DailyLog: created when no existing log; updated when log exists * - goalMet flag when XP reaches dailyGoalXp * - processSkillUnlocks called on category level-up; not called otherwise */ import { describe, it, expect, vi, beforeEach } from "vitest"; import { NextRequest } from "next/server"; // --------------------------------------------------------------------------- // Mock Prisma // --------------------------------------------------------------------------- const mockUserFindFirst = vi.fn(); const mockDailyLogFindFirst = vi.fn(); const mockTransaction = vi.fn(); vi.mock("@/lib/db", () => ({ prisma: { user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) }, dailyLog: { findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args) }, $transaction: (...args: unknown[]) => mockTransaction(...args), }, })); // --------------------------------------------------------------------------- // Mock Claude // --------------------------------------------------------------------------- const mockClaudeCreate = vi.fn(); vi.mock("@/lib/claude", () => ({ claude: { messages: { create: (...args: unknown[]) => mockClaudeCreate(...args) }, }, parseClaudeJson: (text: string) => JSON.parse(text.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```\s*$/, "").trim()), })); // --------------------------------------------------------------------------- // Mock rollCriticalHit (deterministic) // --------------------------------------------------------------------------- const mockRollCriticalHit = vi.fn(() => false); vi.mock("@/lib/xp", async (importOriginal) => { const actual = await importOriginal<typeof import("@/lib/xp")>(); return { ...actual, rollCriticalHit: () => mockRollCriticalHit(), }; }); // --------------------------------------------------------------------------- // Mock getMultiplierPercent // --------------------------------------------------------------------------- const mockGetMultiplierPercent = vi.fn(() => Promise.resolve(0)); vi.mock("@/lib/multiplier", () => ({ getMultiplierPercent: (...args: unknown[]) => (mockGetMultiplierPercent as (...a: unknown[]) => unknown)(...args), })); // --------------------------------------------------------------------------- // Mock processSkillUnlocks // --------------------------------------------------------------------------- const mockProcessSkillUnlocks = vi.fn((): Promise<{ unlocked: string[]; streakFreezesGranted: number }> => Promise.resolve({ unlocked: [], streakFreezesGranted: 0 }), ); vi.mock("@/lib/skill-unlock", () => ({ processSkillUnlocks: (...args: unknown[]) => (mockProcessSkillUnlocks as (...a: unknown[]) => unknown)(...args), })); // --------------------------------------------------------------------------- // Mock processEndOfDay (no-op β€” streak logic is tested separately) // --------------------------------------------------------------------------- vi.mock("@/lib/streak", () => ({ processEndOfDay: vi.fn(() => Promise.resolve({ streak: 1, freezeUsed: false, streakBroken: false, alreadyProcessed: false, })), })); // --------------------------------------------------------------------------- // Mock extract library (for /api/reading/fetch) // --------------------------------------------------------------------------- const mockFetchAndExtract = vi.fn(); const mockCreateFromText = vi.fn(); vi.mock("@/lib/reading/extract", () => ({ fetchAndExtract: (...args: unknown[]) => mockFetchAndExtract(...args), createFromText: (...args: unknown[]) => mockCreateFromText(...args), })); // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- function makeRequest(method: "GET" | "POST", url: string, body?: unknown): NextRequest { return new NextRequest(url, { method, body: body !== undefined ? JSON.stringify(body) : undefined, headers: body !== undefined ? { "content-type": "application/json" } : {}, }); } function makeUser(overrides: Record<string, unknown> = {}) { return { id: 1, currentXp: 50, xpToNextLevel: 100, level: 1, totalXp: 50, dailyGoalXp: 100, title: "Smooth Brain", categorySkills: [ { id: 10, category: "reading", level: 1, currentXp: 20, xpToNext: 100, totalXp: 20, }, ], ...overrides, }; } function makeClaudeScoreResponse(avgScore = 7) { return { scores: [ { questionId: 1, score: avgScore, feedback: "Good recall." }, { questionId: 2, score: avgScore, feedback: "Solid inference." }, { questionId: 3, score: avgScore, feedback: "Decent inference." }, { questionId: 4, score: avgScore, feedback: "Good critical thinking." }, ], overallFeedback: "Strong comprehension overall.", }; } function makeClaudeMsg(text: string) { return { content: [{ type: "text", text }] }; } const SAMPLE_QUESTIONS = [ { id: 1, type: "recall" as const, question: "What did the article state?" }, { id: 2, type: "inference" as const, question: "What can we infer?" }, { id: 3, type: "inference" as const, question: "What follows from this?" }, { id: 4, type: "critical" as const, question: "Evaluate the argument." }, ]; const SAMPLE_ANSWERS = [ { questionId: 1, answer: "The article stated X." }, { questionId: 2, answer: "We can infer Y." }, { questionId: 3, answer: "Z follows." }, { questionId: 4, answer: "The argument is sound because W." }, ]; // --------------------------------------------------------------------------- // GET /api/reading/content // --------------------------------------------------------------------------- describe("GET /api/reading/content", () => { it("list mode: returns metadata without body field", async () => { const { GET } = await import("@/app/api/reading/content/route"); const req = makeRequest("GET", "http://localhost/api/reading/content?list=1"); const res = await GET(req); const data = await res.json(); expect(res.status).toBe(200); expect(Array.isArray(data.articles)).toBe(true); expect(data.articles.length).toBeGreaterThan(0); // No body field in list mode for (const a of data.articles) { expect(a).not.toHaveProperty("body"); expect(a).toHaveProperty("slug"); expect(a).toHaveProperty("title"); expect(a).toHaveProperty("difficulty"); } }); it("slug mode: returns specific article", async () => { const { GET } = await import("@/app/api/reading/content/route"); const req = makeRequest("GET", "http://localhost/api/reading/content?slug=fermi-estimation"); const res = await GET(req); const data = await res.json(); expect(res.status).toBe(200); expect(data.article.slug).toBe("fermi-estimation"); expect(data.article).toHaveProperty("body"); expect(data.article.body.length).toBeGreaterThan(0); }); it("slug mode: 404 on unknown slug", async () => { const { GET } = await import("@/app/api/reading/content/route"); const req = makeRequest("GET", "http://localhost/api/reading/content?slug=does-not-exist"); const res = await GET(req); const data = await res.json(); expect(res.status).toBe(404); expect(data).toHaveProperty("error"); }); it("random mode: returns some article", async () => { const { GET } = await import("@/app/api/reading/content/route"); const req = makeRequest("GET", "http://localhost/api/reading/content"); const res = await GET(req); const data = await res.json(); expect(res.status).toBe(200); expect(data.article).toHaveProperty("slug"); expect(data.article).toHaveProperty("body"); }); it("random mode with difficulty: returns article of that difficulty (or any if none match)", async () => { const { GET } = await import("@/app/api/reading/content/route"); const req = makeRequest( "GET", "http://localhost/api/reading/content?difficulty=beginner", ); const res = await GET(req); const data = await res.json(); expect(res.status).toBe(200); // Should return an article expect(data.article).toHaveProperty("slug"); }); }); // --------------------------------------------------------------------------- // POST /api/reading/fetch // --------------------------------------------------------------------------- describe("POST /api/reading/fetch", () => { beforeEach(() => { vi.clearAllMocks(); }); it("invalid JSON body β†’ 400", async () => { const { POST } = await import("@/app/api/reading/fetch/route"); const req = new NextRequest("http://localhost/api/reading/fetch", { method: "POST", body: "not-json", headers: { "content-type": "application/json" }, }); const res = await POST(req); expect(res.status).toBe(400); const data = await res.json(); expect(data).toHaveProperty("error"); }); it("missing url and text β†’ 400", async () => { const { POST } = await import("@/app/api/reading/fetch/route"); const req = makeRequest("POST", "http://localhost/api/reading/fetch", {}); const res = await POST(req); expect(res.status).toBe(400); const data = await res.json(); expect(data.error).toMatch(/url.*text|text.*url/i); }); it("invalid URL format β†’ 400", async () => { const { POST } = await import("@/app/api/reading/fetch/route"); const req = makeRequest("POST", "http://localhost/api/reading/fetch", { url: "not-a-valid-url", }); const res = await POST(req); expect(res.status).toBe(400); const data = await res.json(); expect(data.error).toMatch(/invalid url/i); }); it("non-http protocol β†’ 400", async () => { const { POST } = await import("@/app/api/reading/fetch/route"); const req = makeRequest("POST", "http://localhost/api/reading/fetch", { url: "ftp://example.com/file", }); const res = await POST(req); expect(res.status).toBe(400); const data = await res.json(); expect(data.error).toMatch(/http/i); }); it("URL fetch success: calls fetchAndExtract and returns article with source=url", async () => { mockFetchAndExtract.mockResolvedValueOnce({ title: "Test Article", body: "Test content here.", domain: "example.com", wordCount: 3, estimatedMinutes: 1, sourceUrl: "https://example.com/article", }); const { POST } = await import("@/app/api/reading/fetch/route"); const req = makeRequest("POST", "http://localhost/api/reading/fetch", { url: "https://example.com/article", }); const res = await POST(req); const data = await res.json(); expect(res.status).toBe(200); expect(data.source).toBe("url"); expect(data.article.title).toBe("Test Article"); expect(mockFetchAndExtract).toHaveBeenCalledWith("https://example.com/article"); }); it("URL fetch error: returns 422 with error message", async () => { mockFetchAndExtract.mockRejectedValueOnce(new Error("Page not found")); const { POST } = await import("@/app/api/reading/fetch/route"); const req = makeRequest("POST", "http://localhost/api/reading/fetch", { url: "https://example.com/missing", }); const res = await POST(req); const data = await res.json(); expect(res.status).toBe(422); expect(data.error).toContain("Page not found"); }); it("text paste success: calls createFromText and returns article with source=text", async () => { mockCreateFromText.mockReturnValueOnce({ title: "My Pasted Text", body: "This is the pasted content.", domain: "custom", wordCount: 5, estimatedMinutes: 1, sourceUrl: "", }); const { POST } = await import("@/app/api/reading/fetch/route"); const req = makeRequest("POST", "http://localhost/api/reading/fetch", { text: "This is the pasted content.", title: "My Pasted Text", }); const res = await POST(req); const data = await res.json(); expect(res.status).toBe(200); expect(data.source).toBe("text"); expect(data.article.title).toBe("My Pasted Text"); expect(mockCreateFromText).toHaveBeenCalledWith( "This is the pasted content.", "My Pasted Text", ); }); it("text paste error: returns 422 with error message", async () => { mockCreateFromText.mockImplementationOnce(() => { throw new Error("Text too short"); }); const { POST } = await import("@/app/api/reading/fetch/route"); const req = makeRequest("POST", "http://localhost/api/reading/fetch", { text: "x", }); const res = await POST(req); const data = await res.json(); expect(res.status).toBe(422); expect(data.error).toContain("Text too short"); }); }); // --------------------------------------------------------------------------- // POST /api/reading/questions // --------------------------------------------------------------------------- describe("POST /api/reading/questions", () => { beforeEach(() => { vi.clearAllMocks(); process.env.ANTHROPIC_API_KEY = "test-key"; }); it("503 when API key missing, no Claude call", async () => { delete process.env.ANTHROPIC_API_KEY; const { POST } = await import("@/app/api/reading/questions/route"); const req = makeRequest("POST", "http://localhost/api/reading/questions", { slug: "fermi-estimation", }); const res = await POST(req); expect(res.status).toBe(503); expect(mockClaudeCreate).not.toHaveBeenCalled(); }); it("503 when API key is empty string, no Claude call", async () => { process.env.ANTHROPIC_API_KEY = ""; const { POST } = await import("@/app/api/reading/questions/route"); const req = makeRequest("POST", "http://localhost/api/reading/questions", { slug: "fermi-estimation", }); const res = await POST(req); expect(res.status).toBe(503); expect(mockClaudeCreate).not.toHaveBeenCalled(); }); it("invalid JSON body β†’ 400", async () => { const { POST } = await import("@/app/api/reading/questions/route"); const req = new NextRequest("http://localhost/api/reading/questions", { method: "POST", body: "{bad json", headers: { "content-type": "application/json" }, }); const res = await POST(req); expect(res.status).toBe(400); }); it("missing slug and content β†’ 400", async () => { const { POST } = await import("@/app/api/reading/questions/route"); const req = makeRequest("POST", "http://localhost/api/reading/questions", {}); const res = await POST(req); expect(res.status).toBe(400); const data = await res.json(); expect(data.error).toMatch(/slug.*content|content.*slug/i); }); it("unknown slug β†’ 404", async () => { const { POST } = await import("@/app/api/reading/questions/route"); const req = makeRequest("POST", "http://localhost/api/reading/questions", { slug: "nonexistent-slug", }); const res = await POST(req); expect(res.status).toBe(404); }); it("slug success: Claude called with article title in prompt", async () => { const questions = [ { id: 1, type: "recall", question: "What is the main idea?" }, { id: 2, type: "inference", question: "What can we infer?" }, { id: 3, type: "inference", question: "What follows?" }, { id: 4, type: "critical", question: "Evaluate the argument." }, ]; mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(questions)), ); const { POST } = await import("@/app/api/reading/questions/route"); const req = makeRequest("POST", "http://localhost/api/reading/questions", { slug: "fermi-estimation", }); const res = await POST(req); expect(res.status).toBe(200); const data = await res.json(); expect(Array.isArray(data.questions)).toBe(true); expect(data.questions.length).toBe(4); const promptText = mockClaudeCreate.mock.calls[0][0].messages[0].content as string; expect(promptText).toContain("Fermi Estimation"); }); it("custom content object: Claude called with custom title in prompt", async () => { const questions = [ { id: 1, type: "recall", question: "What was said?" }, { id: 2, type: "inference", question: "What can be inferred?" }, { id: 3, type: "inference", question: "What follows?" }, { id: 4, type: "critical", question: "Evaluate the logic." }, ]; mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(questions)), ); const { POST } = await import("@/app/api/reading/questions/route"); const req = makeRequest("POST", "http://localhost/api/reading/questions", { content: { title: "My Custom Article", body: "This is the custom body text for reading comprehension.", }, }); const res = await POST(req); expect(res.status).toBe(200); const promptText = mockClaudeCreate.mock.calls[0][0].messages[0].content as string; expect(promptText).toContain("My Custom Article"); }); it("uses claude-3-5-haiku model", async () => { const questions = [ { id: 1, type: "recall", question: "Q1?" }, { id: 2, type: "inference", question: "Q2?" }, { id: 3, type: "inference", question: "Q3?" }, { id: 4, type: "critical", question: "Q4?" }, ]; mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(questions)), ); const { POST } = await import("@/app/api/reading/questions/route"); const req = makeRequest("POST", "http://localhost/api/reading/questions", { slug: "fermi-estimation", }); await POST(req); const callArgs = mockClaudeCreate.mock.calls[0][0]; expect(callArgs.model).toContain("haiku"); }); it("invalid JSON from Claude β†’ 500", async () => { mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg("this is not valid json {{{{"), ); const { POST } = await import("@/app/api/reading/questions/route"); const req = makeRequest("POST", "http://localhost/api/reading/questions", { slug: "fermi-estimation", }); const res = await POST(req); expect(res.status).toBe(500); }); it("network error from Claude β†’ 500", async () => { mockClaudeCreate.mockRejectedValueOnce(new Error("Connection refused")); const { POST } = await import("@/app/api/reading/questions/route"); const req = makeRequest("POST", "http://localhost/api/reading/questions", { slug: "fermi-estimation", }); const res = await POST(req); expect(res.status).toBe(500); }); }); // --------------------------------------------------------------------------- // POST /api/reading/score // --------------------------------------------------------------------------- describe("POST /api/reading/score", () => { beforeEach(() => { vi.resetAllMocks(); // reset implementations too, not just call counts process.env.ANTHROPIC_API_KEY = "test-key"; mockRollCriticalHit.mockReturnValue(false); mockGetMultiplierPercent.mockResolvedValue(0); mockProcessSkillUnlocks.mockResolvedValue({ unlocked: [], streakFreezesGranted: 0 }); mockTransaction.mockImplementation(async (fn: (tx: unknown) => Promise<unknown>) => { const tx = { activity: { create: vi.fn().mockResolvedValue({}) }, user: { update: vi.fn().mockResolvedValue({}) }, categorySkill: { update: vi.fn().mockResolvedValue({}) }, dailyLog: { update: vi.fn().mockResolvedValue({}), create: vi.fn().mockResolvedValue({}), }, }; return fn(tx); }); mockDailyLogFindFirst.mockResolvedValue(null); }); it("503 when API key missing, no Claude call", async () => { delete process.env.ANTHROPIC_API_KEY; const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); expect(res.status).toBe(503); expect(mockClaudeCreate).not.toHaveBeenCalled(); }); it("503 when API key is empty string", async () => { process.env.ANTHROPIC_API_KEY = ""; const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); expect(res.status).toBe(503); }); it("invalid JSON body β†’ 400", async () => { const { POST } = await import("@/app/api/reading/score/route"); const req = new NextRequest("http://localhost/api/reading/score", { method: "POST", body: "{bad json", headers: { "content-type": "application/json" }, }); const res = await POST(req); expect(res.status).toBe(400); }); it("missing answers β†’ 400", async () => { const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); expect(res.status).toBe(400); }); it("missing questions β†’ 400", async () => { const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, durationSecs: 300, }); const res = await POST(req); expect(res.status).toBe(400); }); it("empty answers array β†’ 400", async () => { const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: [], questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); expect(res.status).toBe(400); }); it("unknown slug β†’ 404", async () => { const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "nonexistent-article", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); expect(res.status).toBe(404); }); it("missing content and slug β†’ 400", async () => { const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); expect(res.status).toBe(400); }); it("user not found β†’ 404", async () => { mockUserFindFirst.mockResolvedValueOnce(null); mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(7))), ); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); expect(res.status).toBe(404); }); it("missing reading CategorySkill β†’ 500", async () => { mockUserFindFirst.mockResolvedValueOnce({ ...makeUser(), categorySkills: [], // no reading skill }); mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(7))), ); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); expect(res.status).toBe(500); }); it("success: response shape is correct", async () => { mockUserFindFirst.mockResolvedValueOnce(makeUser()); mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(8))), ); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); expect(res.status).toBe(200); const data = await res.json(); expect(data).toHaveProperty("scores"); expect(data).toHaveProperty("overallFeedback"); expect(data).toHaveProperty("avgScore"); expect(data).toHaveProperty("xp"); expect(data.xp).toHaveProperty("baseXp"); expect(data.xp).toHaveProperty("totalXp"); expect(data.xp).toHaveProperty("qualityBonus"); expect(data.xp).toHaveProperty("isCriticalHit"); expect(data).toHaveProperty("levelUp"); expect(data).toHaveProperty("categoryXp"); expect(data.categoryXp).toHaveProperty("level"); expect(data.categoryXp).toHaveProperty("levelUp"); expect(data).toHaveProperty("unlocks"); }); it("Claude prompt includes article title and Q&A pairs", async () => { mockUserFindFirst.mockResolvedValueOnce(makeUser()); mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(5))), ); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); await POST(req); const promptText = mockClaudeCreate.mock.calls[0][0].messages[0].content as string; expect(promptText).toContain("Fermi Estimation"); expect(promptText).toContain("What did the article state?"); expect(promptText).toContain("The article stated X."); }); it("uses claude-3-5-haiku model", async () => { mockUserFindFirst.mockResolvedValueOnce(makeUser()); mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(5))), ); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); await POST(req); const callArgs = mockClaudeCreate.mock.calls[0][0]; expect(callArgs.model).toContain("haiku"); }); it("invalid JSON from Claude β†’ 500", async () => { mockUserFindFirst.mockResolvedValueOnce(makeUser()); mockClaudeCreate.mockResolvedValueOnce(makeClaudeMsg("{ corrupt json ]")); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); expect(res.status).toBe(500); }); it("network error from Claude β†’ 500", async () => { mockUserFindFirst.mockResolvedValueOnce(makeUser()); mockClaudeCreate.mockRejectedValueOnce(new Error("Network unreachable")); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); expect(res.status).toBe(500); }); it("XP: quality bonus is non-zero for high scores", async () => { mockUserFindFirst.mockResolvedValueOnce(makeUser()); // All scores of 10/10 β†’ qualityScore=1.0 β†’ max quality bonus mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(10))), ); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); const data = await res.json(); expect(data.xp.qualityBonus).toBeGreaterThan(0); expect(data.xp.totalXp).toBeGreaterThan(data.xp.baseXp); }); it("XP: zero quality bonus for score of 0", async () => { mockUserFindFirst.mockResolvedValueOnce(makeUser()); mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(0))), ); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); const data = await res.json(); expect(data.xp.qualityBonus).toBe(0); expect(data.xp.totalXp).toBe(data.xp.baseXp); }); it("XP: critical hit doubles totalXp", async () => { mockRollCriticalHit.mockReturnValue(true); mockUserFindFirst.mockResolvedValueOnce(makeUser()); mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(0))), ); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); const data = await res.json(); expect(data.xp.isCriticalHit).toBe(true); expect(data.xp.totalXp).toBe(data.xp.baseXp * 2); }); it("XP: multiplier bonus reflected in response", async () => { mockGetMultiplierPercent.mockResolvedValue(10); mockUserFindFirst.mockResolvedValueOnce(makeUser()); mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(0))), ); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); const data = await res.json(); expect(data.xp.multiplierPercent).toBe(10); expect(data.xp.multiplierBonus).toBeGreaterThan(0); expect(data.xp.totalXp).toBeGreaterThan(data.xp.baseXp); }); it("custom content: accepted and exerciseType is comprehension-custom in activity", async () => { mockUserFindFirst.mockResolvedValueOnce(makeUser()); mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(7))), ); let capturedExerciseType = ""; mockTransaction.mockImplementationOnce( async (fn: (tx: unknown) => Promise<unknown>) => { const tx = { activity: { create: vi.fn().mockImplementation((args: { data: { exerciseType: string } }) => { capturedExerciseType = args.data.exerciseType; return {}; }), }, user: { update: vi.fn().mockResolvedValue({}) }, categorySkill: { update: vi.fn().mockResolvedValue({}) }, dailyLog: { update: vi.fn().mockResolvedValue({}), create: vi.fn().mockResolvedValue({}), }, }; return fn(tx); }, ); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { content: { title: "Custom Read", body: "Custom body text for this article.", sourceUrl: "https://example.com/custom", }, answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); expect(res.status).toBe(200); expect(capturedExerciseType).toBe("comprehension-custom"); }); it("DailyLog created when no existing log", async () => { mockUserFindFirst.mockResolvedValueOnce(makeUser()); mockDailyLogFindFirst.mockResolvedValue(null); mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(5))), ); let dailyLogCreated = false; let dailyLogUpdated = false; mockTransaction.mockImplementationOnce( async (fn: (tx: unknown) => Promise<unknown>) => { const tx = { activity: { create: vi.fn().mockResolvedValue({}) }, user: { update: vi.fn().mockResolvedValue({}) }, categorySkill: { update: vi.fn().mockResolvedValue({}) }, dailyLog: { update: vi.fn().mockImplementation(() => { dailyLogUpdated = true; return {}; }), create: vi.fn().mockImplementation(() => { dailyLogCreated = true; return {}; }), }, }; return fn(tx); }, ); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); await POST(req); expect(dailyLogCreated).toBe(true); expect(dailyLogUpdated).toBe(false); }); it("DailyLog updated when log exists", async () => { mockUserFindFirst.mockResolvedValueOnce(makeUser()); mockDailyLogFindFirst.mockResolvedValue({ id: 99, xpEarned: 40, activityCount: 1, }); mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(5))), ); let dailyLogCreated = false; let dailyLogUpdated = false; mockTransaction.mockImplementationOnce( async (fn: (tx: unknown) => Promise<unknown>) => { const tx = { activity: { create: vi.fn().mockResolvedValue({}) }, user: { update: vi.fn().mockResolvedValue({}) }, categorySkill: { update: vi.fn().mockResolvedValue({}) }, dailyLog: { update: vi.fn().mockImplementation(() => { dailyLogUpdated = true; return {}; }), create: vi.fn().mockImplementation(() => { dailyLogCreated = true; return {}; }), }, }; return fn(tx); }, ); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); await POST(req); expect(dailyLogUpdated).toBe(true); expect(dailyLogCreated).toBe(false); }); it("goalMet is true when XP meets dailyGoalXp", async () => { // User has dailyGoalXp=30, xpEarned so far=0, baseXp for reading=30 // A perfect score (30+30=60 XP) should easily meet the goal of 30 const user = makeUser({ dailyGoalXp: 30 }); mockUserFindFirst.mockResolvedValue(user); mockDailyLogFindFirst.mockResolvedValue(null); mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(10))), // perfect score ); let capturedGoalMet = false; // Use mockImplementationOnce so this custom tx doesn't bleed into later tests mockTransaction.mockImplementationOnce( async (fn: (tx: unknown) => Promise<unknown>) => { const tx = { activity: { create: vi.fn().mockResolvedValue({}) }, user: { update: vi.fn().mockResolvedValue({}) }, categorySkill: { update: vi.fn().mockResolvedValue({}) }, dailyLog: { update: vi.fn().mockResolvedValue({}), create: vi.fn().mockImplementation((args: { data: { goalMet: boolean } }) => { capturedGoalMet = args.data.goalMet; return {}; }), }, }; mockProcessSkillUnlocks.mockResolvedValueOnce({ unlocked: [], streakFreezesGranted: 0 }); return fn(tx); }, ); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); expect(res.status).toBe(200); expect(capturedGoalMet).toBe(true); }); it("processSkillUnlocks called on category level-up", async () => { // Force a category level-up: currentXp=9999 well exceeds xpToNext=1 const user = makeUser(); user.categorySkills[0].currentXp = 9999; user.categorySkills[0].xpToNext = 1; mockUserFindFirst.mockResolvedValue(user); mockDailyLogFindFirst.mockResolvedValue(null); mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(5))), ); let processSkillUnlocksCalled = false; // Use mockImplementationOnce so this override doesn't bleed into later tests mockTransaction.mockImplementationOnce(async (fn: (tx: unknown) => Promise<unknown>) => { const tx = { activity: { create: vi.fn().mockResolvedValue({}) }, user: { update: vi.fn().mockResolvedValue({}) }, categorySkill: { update: vi.fn().mockResolvedValue({}) }, dailyLog: { create: vi.fn().mockResolvedValue({}), update: vi.fn().mockResolvedValue({}) }, }; mockProcessSkillUnlocks.mockImplementationOnce(() => { processSkillUnlocksCalled = true; return Promise.resolve({ unlocked: [], streakFreezesGranted: 0 }); }); return fn(tx); }); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); expect(res.status).toBe(200); expect(processSkillUnlocksCalled).toBe(true); }); it("processSkillUnlocks not called when no category level-up", async () => { // Category XP won't reach next level const user = makeUser(); user.categorySkills[0].currentXp = 0; user.categorySkills[0].xpToNext = 1000; mockUserFindFirst.mockResolvedValueOnce(user); mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(0))), // minimal XP ); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); await POST(req); expect(mockProcessSkillUnlocks).not.toHaveBeenCalled(); }); it("unlocks populated in response when skill unlocks occur", async () => { mockProcessSkillUnlocks.mockResolvedValue({ unlocked: ["Deep Diver", "Focus Boost"], streakFreezesGranted: 0, }); const user = makeUser(); user.categorySkills[0].currentXp = 99; user.categorySkills[0].xpToNext = 100; mockUserFindFirst.mockResolvedValueOnce(user); mockClaudeCreate.mockResolvedValueOnce( makeClaudeMsg(JSON.stringify(makeClaudeScoreResponse(10))), ); const { POST } = await import("@/app/api/reading/score/route"); const req = makeRequest("POST", "http://localhost/api/reading/score", { slug: "fermi-estimation", answers: SAMPLE_ANSWERS, questions: SAMPLE_QUESTIONS, durationSecs: 300, }); const res = await POST(req); const data = await res.json(); expect(data.unlocks).toEqual(["Deep Diver", "Focus Boost"]); }); });
/**
* Tests for Reading API route handlers.
*
* Covers:
* GET /api/reading/content
* - list mode: returns article metadata (no body field)
* - slug mode: returns specific article; 404 on unknown slug
* - random mode: returns some article; respects difficulty filter
*
* POST /api/reading/fetch
* - invalid JSON body β†’ 400
* - missing url and text β†’ 400
* - invalid URL format β†’ 400
* - non-http/https protocol β†’ 400
* - URL fetch: delegates to fetchAndExtract, returns { article, source: "url" }
* - URL fetch error: propagates error message as 422
* - text paste: delegates to createFromText, returns { article, source: "text" }
* - text paste error: propagates error message as 422
*
* POST /api/reading/questions
* - API key guard (503 when missing, no Claude call)
* - invalid JSON body β†’ 400
* - missing slug and content β†’ 400
* - invalid slug β†’ 404
* - valid content object accepted alongside slug
* - Claude called with article title and body in prompt
* - haiku model used
* - returns { questions } array on success
* - invalid JSON from Claude β†’ 500
* - network error from Claude β†’ 500
*
* POST /api/reading/score
* - API key guard (503 when missing, no Claude call)
* - invalid JSON body β†’ 400
* - missing answers/questions β†’ 400
* - invalid slug β†’ 404
* - missing content object β†’ 400
* - user not found β†’ 404
* - missing reading CategorySkill β†’ 500
* - Claude integration: prompt includes article title + QA pairs
* - haiku model used
* - invalid JSON from Claude β†’ 500
* - network error from Claude β†’ 500
* - response shape: scores, overallFeedback, avgScore, xp, levelUp, categoryXp, unlocks
* - XP: quality score derived from avgScore/10; qualityBonus for high scores
* - XP: critical hit doubles totalXp
* - XP: multiplier bonus reflected in response
* - custom content: sets isCustomContent path (exerciseType "comprehension-custom")
* - DailyLog: created when no existing log; updated when log exists
* - goalMet flag when XP reaches dailyGoalXp
* - processSkillUnlocks called on category level-up; not called otherwise
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
// ---------------------------------------------------------------------------
// Mock Prisma
// ---------------------------------------------------------------------------
const mockUserFindFirst = vi.fn();
const mockDailyLogFindFirst = vi.fn();
const mockTransaction = vi.fn();
vi.mock("@/lib/db", () => ({
prisma: {
user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) },
dailyLog: { findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args) },
$transaction: (...args: unknown[]) => mockTransaction(...args),
},
}));
// ---------------------------------------------------------------------------
// Mock Claude
// ---------------------------------------------------------------------------
const mockClaudeCreate = vi.fn();
vi.mock("@/lib/claude", () => ({
claude: {
messages: { create: (...args: unknown[]) => mockClaudeCreate(...args) },
},
parseClaudeJson: (text: string) => JSON.parse(text.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```\s*$/, "").trim()),
}));
// ---------------------------------------------------------------------------
// Mock rollCriticalHit (deterministic)
// ---------------------------------------------------------------------------
const mockRollCriticalHit = vi.fn(() => false);
vi.mock("@/lib/xp", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/xp")>();
return {
...actual,
rollCriticalHit: () => mockRollCriticalHit(),
};
});
// ---------------------------------------------------------------------------