import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { apiClient, ApiClientError, setApiBaseUrl, getApiBaseUrl, } from "../api-client"; // --------------------------------------------------------------------------- // Fetch mock helpers // --------------------------------------------------------------------------- function makeResponse(body: unknown, status = 200): Response { return { ok: status >= 200 && status < 300, status, json: async () => body, headers: new Headers(), } as unknown as Response; } function makeErrorResponse(body: unknown, status: number): Response { return makeResponse(body, status); } // --------------------------------------------------------------------------- // Base URL management // --------------------------------------------------------------------------- describe("setApiBaseUrl / getApiBaseUrl", () => { afterEach(() => setApiBaseUrl("")); it("defaults to empty string", () => { expect(getApiBaseUrl()).toBe(""); }); it("stores an absolute base URL", () => { setApiBaseUrl("https://api.example.com"); expect(getApiBaseUrl()).toBe("https://api.example.com"); }); it("strips trailing slash", () => { setApiBaseUrl("https://api.example.com/"); expect(getApiBaseUrl()).toBe("https://api.example.com"); }); it("resets to empty string on setApiBaseUrl('')", () => { setApiBaseUrl("https://api.example.com"); setApiBaseUrl(""); expect(getApiBaseUrl()).toBe(""); }); }); // --------------------------------------------------------------------------- // ApiClientError // --------------------------------------------------------------------------- describe("ApiClientError", () => { it("is an instance of Error", () => { const err = new ApiClientError(404, { error: "not found" }); expect(err).toBeInstanceOf(Error); }); it("has name ApiClientError", () => { expect(new ApiClientError(404, null).name).toBe("ApiClientError"); }); it("exposes status and body", () => { const body = { error: "forbidden" }; const err = new ApiClientError(403, body); expect(err.status).toBe(403); expect(err.body).toBe(body); }); it("uses default message when not provided", () => { const err = new ApiClientError(500, null); expect(err.message).toBe("API error 500"); }); it("uses custom message when provided", () => { const err = new ApiClientError(422, null, "Validation failed"); expect(err.message).toBe("Validation failed"); }); it("has a stack trace", () => { const err = new ApiClientError(400, null); expect(err.stack).toBeDefined(); expect(err.stack).toContain("ApiClientError"); }); }); // --------------------------------------------------------------------------- // Core fetch behaviour // --------------------------------------------------------------------------- describe("core fetch behaviour", () => { const mockFetch = vi.fn(); beforeEach(() => { vi.stubGlobal("fetch", mockFetch); mockFetch.mockReset(); setApiBaseUrl(""); }); afterEach(() => { vi.unstubAllGlobals(); setApiBaseUrl(""); }); it("sends Content-Type: application/json", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ ok: true })); await apiClient.getDashboard(); expect(mockFetch).toHaveBeenCalledWith( "/api/dashboard", expect.objectContaining({ headers: expect.objectContaining({ "Content-Type": "application/json", }), }), ); }); it("prepends baseUrl when set", async () => { setApiBaseUrl("https://myapi.example.com"); mockFetch.mockResolvedValueOnce(makeResponse({ ok: true })); await apiClient.getDashboard(); expect(mockFetch).toHaveBeenCalledWith( "https://myapi.example.com/api/dashboard", expect.anything(), ); }); it("throws ApiClientError on 4xx", async () => { mockFetch.mockResolvedValueOnce(makeErrorResponse({ error: "not found" }, 404)); await expect(apiClient.getDashboard()).rejects.toBeInstanceOf(ApiClientError); }); it("exposes status and body on error", async () => { const errorBody = { error: "unauthorized" }; mockFetch.mockResolvedValueOnce(makeErrorResponse(errorBody, 401)); try { await apiClient.getDashboard(); expect.fail("should have thrown"); } catch (err) { expect(err).toBeInstanceOf(ApiClientError); expect((err as ApiClientError).status).toBe(401); expect((err as ApiClientError).body).toEqual(errorBody); } }); it("throws ApiClientError on 5xx", async () => { mockFetch.mockResolvedValueOnce(makeErrorResponse({ error: "server error" }, 500)); await expect(apiClient.getDashboard()).rejects.toBeInstanceOf(ApiClientError); }); it("returns parsed JSON on success", async () => { const data = { user: { id: 1, name: "Test" } }; mockFetch.mockResolvedValueOnce(makeResponse(data)); const result = await apiClient.getDashboard(); expect(result).toEqual(data); }); it("propagates network errors", async () => { mockFetch.mockRejectedValueOnce(new TypeError("Network request failed")); await expect(apiClient.getDashboard()).rejects.toThrow("Network request failed"); }); it("handles non-JSON response body gracefully (returns null body on error)", async () => { mockFetch.mockResolvedValueOnce({ ok: false, status: 503, json: async () => { throw new SyntaxError("not json"); }, } as unknown as Response); try { await apiClient.getDashboard(); expect.fail("should throw"); } catch (err) { expect(err).toBeInstanceOf(ApiClientError); expect((err as ApiClientError).status).toBe(503); expect((err as ApiClientError).body).toBeNull(); } }); }); // --------------------------------------------------------------------------- // Individual endpoint tests // --------------------------------------------------------------------------- describe("apiClient endpoints", () => { const mockFetch = vi.fn(); beforeEach(() => { vi.stubGlobal("fetch", mockFetch); mockFetch.mockReset(); setApiBaseUrl(""); }); afterEach(() => vi.unstubAllGlobals()); // ── Dashboard ────────────────────────────────────────────────────────────── it("getDashboard → GET /api/dashboard", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ user: {} })); await apiClient.getDashboard(); expect(mockFetch).toHaveBeenCalledWith( "/api/dashboard", expect.objectContaining({ headers: expect.anything() }), ); expect((mockFetch.mock.calls[0][1] as RequestInit).method).toBeUndefined(); }); // ── Chess ────────────────────────────────────────────────────────────────── it("getChessPuzzle → GET /api/chess/puzzle (no params)", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ id: "abc" })); await apiClient.getChessPuzzle(); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/chess/puzzle"); }); it("getChessPuzzle → GET /api/chess/puzzle?daily=true", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ id: "daily" })); await apiClient.getChessPuzzle({ daily: true }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/chess/puzzle?daily=true"); }); it("submitChessPuzzle → POST /api/chess/submit with body", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ totalXp: 40 })); const body = { puzzleId: "abc", puzzleRating: 1500, solved: true, movesPlayed: 3, solutionLen: 3, }; await apiClient.submitChessPuzzle(body); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/chess/submit"); expect(init.method).toBe("POST"); expect(JSON.parse(init.body as string)).toEqual(body); }); // ── Logic ────────────────────────────────────────────────────────────────── it("generateLogicPuzzle → GET /api/logic/generate (no params)", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ type: "sudoku" })); await apiClient.generateLogicPuzzle(); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/logic/generate"); }); it("generateLogicPuzzle → includes query params", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ type: "sequence" })); await apiClient.generateLogicPuzzle({ type: "sequence", difficulty: "hard" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toContain("type=sequence"); expect(url).toContain("difficulty=hard"); }); it("generateLogicPuzzle → includes sequenceType", async () => { mockFetch.mockResolvedValueOnce(makeResponse({})); await apiClient.generateLogicPuzzle({ type: "sequence", sequenceType: "fibonacci" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toContain("sequenceType=fibonacci"); }); it("generateLogicPuzzle → includes wordCategory", async () => { mockFetch.mockResolvedValueOnce(makeResponse({})); await apiClient.generateLogicPuzzle({ type: "wordscramble", wordCategory: "nature" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toContain("wordCategory=nature"); }); it("submitLogicPuzzle → POST /api/logic/submit", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ correct: true })); const body = { puzzleType: "sudoku", playerGrid: [] }; await apiClient.submitLogicPuzzle(body); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/logic/submit"); expect(init.method).toBe("POST"); }); // ── Feynman ──────────────────────────────────────────────────────────────── it("scoreFeynman → POST /api/feynman/score", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ totalXp: 80 })); await apiClient.scoreFeynman({ topic: "Black holes", explanation: "..." }); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/feynman/score"); expect(init.method).toBe("POST"); }); it("teachFeynman → POST /api/feynman/teach", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ explanation: "..." })); await apiClient.teachFeynman({ topic: "Entropy" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/feynman/teach"); }); it("teachFeynmanDeep → POST /api/feynman/teach-deep", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ deeperExplanation: "..." })); await apiClient.teachFeynmanDeep({ topic: "Entropy" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/feynman/teach-deep"); }); it("assessFeynman → POST /api/feynman/assess", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ question: "What is...?" })); await apiClient.assessFeynman({ topic: "DNA" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/feynman/assess"); }); it("getCalibratedTopics → GET /api/feynman/calibrate (no params)", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ topics: [] })); await apiClient.getCalibratedTopics(); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/feynman/calibrate"); }); it("getCalibratedTopics → appends domain param", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ topics: [] })); await apiClient.getCalibratedTopics({ domain: "CS" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/feynman/calibrate?domain=CS"); }); it("getCalibratedTopics → appends count param", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ topics: [] })); await apiClient.getCalibratedTopics({ count: 5 }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/feynman/calibrate?count=5"); }); it("getCalibratedTopics → appends userId param", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ topics: [] })); await apiClient.getCalibratedTopics({ userId: 2 }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/feynman/calibrate?userId=2"); }); it("getCalibratedTopics → appends all three params", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ topics: [] })); await apiClient.getCalibratedTopics({ domain: "Physics", count: 4, userId: 3 }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/feynman/calibrate?domain=Physics&count=4&userId=3"); }); it("getCalibratedTopics → omits empty domain string", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ topics: [] })); await apiClient.getCalibratedTopics({ domain: "" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/feynman/calibrate"); }); it("getFeynmanReviews → GET /api/feynman/review (no params)", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ due: [] })); await apiClient.getFeynmanReviews(); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/feynman/review"); }); it("getFeynmanReviews → appends ?summary=true", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ summary: {} })); await apiClient.getFeynmanReviews({ summary: true }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/feynman/review?summary=true"); }); it("curateFeynmanSources → POST /api/feynman/curate", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ sources: [], sourceReady: false, sourceCount: 0 })); await apiClient.curateFeynmanSources({ topicId: "abc", grounded: true }); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/feynman/curate"); expect(init.method).toBe("POST"); expect(JSON.parse(init.body as string)).toEqual({ topicId: "abc", grounded: true }); }); it("verifyFeynmanSources → GET /api/feynman/verify (default)", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ total: 0 })); await apiClient.verifyFeynmanSources(); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/feynman/verify"); expect(init.method).toBeUndefined(); }); it("verifyFeynmanSources → POST /api/feynman/verify with limit", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ checked: 50 })); await apiClient.verifyFeynmanSources({ method: "POST", limit: 50 }); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/feynman/verify"); expect(init.method).toBe("POST"); expect(JSON.parse(init.body as string)).toEqual({ limit: 50 }); }); // ── Reading ──────────────────────────────────────────────────────────────── it("getReadingContent → GET /api/reading/content (no params)", async () => { mockFetch.mockResolvedValueOnce(makeResponse([])); await apiClient.getReadingContent(); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/reading/content"); }); it("getReadingContent → includes difficulty param", async () => { mockFetch.mockResolvedValueOnce(makeResponse([])); await apiClient.getReadingContent({ difficulty: "advanced" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toContain("difficulty=advanced"); }); it("getReadingContent → includes slug param", async () => { mockFetch.mockResolvedValueOnce(makeResponse({})); await apiClient.getReadingContent({ slug: "black-holes" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toContain("slug=black-holes"); }); it("fetchReadingContent → POST /api/reading/fetch with url", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ title: "Test" })); await apiClient.fetchReadingContent({ url: "https://example.com/article" }); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/reading/fetch"); expect(init.method).toBe("POST"); }); it("fetchReadingContent → POST /api/reading/fetch with text", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ title: "Custom" })); await apiClient.fetchReadingContent({ text: "Long text...", title: "My Article" }); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/reading/fetch"); expect(JSON.parse(init.body as string)).toEqual({ text: "Long text...", title: "My Article" }); }); it("generateReadingQuestions → POST /api/reading/questions", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ questions: [] })); await apiClient.generateReadingQuestions({ slug: "black-holes" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/reading/questions"); }); it("scoreReading → POST /api/reading/score", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ totalXp: 60 })); await apiClient.scoreReading({ slug: "black-holes", questions: ["Q1"], answers: ["A1"], durationSecs: 120, }); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/reading/score"); expect(init.method).toBe("POST"); }); // ── Critical Thinking ────────────────────────────────────────────────────── it("generateCriticalExercise → GET /api/critical/generate (no params)", async () => { mockFetch.mockResolvedValueOnce(makeResponse({})); await apiClient.generateCriticalExercise(); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/critical/generate"); }); it("generateCriticalExercise → includes type and difficulty", async () => { mockFetch.mockResolvedValueOnce(makeResponse({})); await apiClient.generateCriticalExercise({ type: "steelman", difficulty: "hard" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toContain("type=steelman"); expect(url).toContain("difficulty=hard"); }); it("scoreCritical → POST /api/critical/score", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ totalXp: 50 })); await apiClient.scoreCritical({ exerciseType: "flaw-finder", passageId: "p1", response: "The argument is flawed because...", }); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/critical/score"); expect(init.method).toBe("POST"); }); // ── Skill Quests ─────────────────────────────────────────────────────────── it("generateQuest → GET /api/quests/generate (no params)", async () => { mockFetch.mockResolvedValueOnce(makeResponse({})); await apiClient.generateQuest(); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/quests/generate"); }); it("generateQuest → includes domain and difficulty", async () => { mockFetch.mockResolvedValueOnce(makeResponse({})); await apiClient.generateQuest({ domain: "music", difficulty: "easy" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toContain("domain=music"); expect(url).toContain("difficulty=easy"); }); it("submitQuest → POST /api/quests/submit with correct body shape", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ correctCount: 2, totalExercises: 3 })); const exercises = [ { id: 1, type: "multiple-choice" as const, question: "What is C?", options: ["A","B","C"], correctAnswer: "C" }, { id: 2, type: "short-answer" as const, question: "Describe a scale.", correctAnswer: "A set of notes." }, ]; const answers: Record = { 1: "C", 2: "ascending notes" }; await apiClient.submitQuest({ domain: "Music Theory", title: "Music Scales", exercises, answers, }); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/quests/submit"); expect(init.method).toBe("POST"); const body = JSON.parse(init.body as string) as { domain: string; title: string; exercises: typeof exercises; answers: typeof answers }; expect(body.domain).toBe("Music Theory"); expect(body.title).toBe("Music Scales"); expect(body.exercises).toHaveLength(2); expect(body.answers[1]).toBe("C"); }); // ── Profile ──────────────────────────────────────────────────────────────── it("getProfile → GET /api/profile", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ user: {} })); await apiClient.getProfile(); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/profile"); }); // ── Settings ─────────────────────────────────────────────────────────────── it("getSettings → GET /api/settings", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ name: "Player" })); await apiClient.getSettings(); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/settings"); }); it("updateSettings → PATCH /api/settings with body", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ name: "New Name" })); await apiClient.updateSettings({ name: "New Name", dailyGoalXp: 150 }); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/settings"); expect(init.method).toBe("PATCH"); expect(JSON.parse(init.body as string)).toEqual({ name: "New Name", dailyGoalXp: 150 }); }); // ── Export ───────────────────────────────────────────────────────────────── it("exportData → GET /api/export", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ exportVersion: 1 })); await apiClient.exportData(); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/export"); }); // ── Stats ────────────────────────────────────────────────────────────────── it("getStats → GET /api/stats (no params)", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ dailyXp: [] })); await apiClient.getStats(); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/stats"); }); it("getStats({ days: 7 }) → GET /api/stats?days=7", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ dailyXp: [] })); await apiClient.getStats({ days: 7 }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/stats?days=7"); }); it("getStats({ days: 90 }) → GET /api/stats?days=90", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ dailyXp: [] })); await apiClient.getStats({ days: 90 }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/stats?days=90"); }); it("getStats({ days: 30 }) → GET /api/stats?days=30", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ dailyXp: [] })); await apiClient.getStats({ days: 30 }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/stats?days=30"); }); it("getStats({ activityOffset: 25 }) → includes activityOffset in query string", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ dailyXp: [] })); await apiClient.getStats({ activityOffset: 25 }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/stats?activityOffset=25"); }); it("getStats({ activityLimit: 10 }) → includes activityLimit in query string", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ dailyXp: [] })); await apiClient.getStats({ activityLimit: 10 }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/stats?activityLimit=10"); }); it("getStats({ days: 7, activityOffset: 25, activityLimit: 10 }) → all three params in query string", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ dailyXp: [] })); await apiClient.getStats({ days: 7, activityOffset: 25, activityLimit: 10 }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/stats?days=7&activityOffset=25&activityLimit=10"); }); it("getStats({ activityOffset: 0 }) → includes activityOffset=0 in query string", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ dailyXp: [] })); await apiClient.getStats({ activityOffset: 0 }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/stats?activityOffset=0"); }); it("getStats({ activityCategory: 'chess' }) → includes activityCategory in query string", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ dailyXp: [] })); await apiClient.getStats({ activityCategory: "chess" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/stats?activityCategory=chess"); }); it("getStats({ activityCategory: 'all' }) → omits activityCategory from query string", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ dailyXp: [] })); await apiClient.getStats({ activityCategory: "all" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/stats"); }); it("getStats({ activityCategory: 'critical-thinking' }) → hyphenated category included", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ dailyXp: [] })); await apiClient.getStats({ activityCategory: "critical-thinking" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/stats?activityCategory=critical-thinking"); }); it("getStats with all four params together → correct query string order", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ dailyXp: [] })); await apiClient.getStats({ days: 30, activityOffset: 25, activityLimit: 10, activityCategory: "feynman" }); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/stats?days=30&activityOffset=25&activityLimit=10&activityCategory=feynman"); }); it("getBestScores → GET /api/stats/best-scores", async () => { mockFetch.mockResolvedValueOnce( makeResponse({ byExerciseType: [], byCategory: [] }), ); await apiClient.getBestScores(); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/stats/best-scores"); }); // ── Coach ────────────────────────────────────────────────────────────────── it("getCoachPerformance → GET /api/coach/performance", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ categories: [] })); await apiClient.getCoachPerformance(); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/coach/performance"); }); it("getCoachDifficulty → GET /api/coach/difficulty", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ recommendations: {} })); await apiClient.getCoachDifficulty(); const [url] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/coach/difficulty"); }); it("getCoachFeedback → POST /api/coach/feedback", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ feedback: "..." })); await apiClient.getCoachFeedback(); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/coach/feedback"); expect(init.method).toBe("POST"); }); it("getCoachFeedback → sends override flag", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ feedback: "..." })); await apiClient.getCoachFeedback({ override: true }); const [, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(JSON.parse(init.body as string)).toEqual({ override: true }); }); it("getWeeklyReport → POST /api/coach/weekly-report", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ report: "..." })); await apiClient.getWeeklyReport(); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/coach/weekly-report"); expect(init.method).toBe("POST"); }); it("getWeeklyReport → sends force flag", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ report: "..." })); await apiClient.getWeeklyReport({ force: true }); const [, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(JSON.parse(init.body as string)).toEqual({ force: true }); }); // ── Debate Arena ─────────────────────────────────────────────────────────── it("startDebate → POST /api/debate/start with full body", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ topic: {}, opponent: {}, rounds: 3, userSide: "pro" })); const body = { topicId: "dt-phil-01", opponentId: "socrates", rounds: 3 as const, userSide: "pro" as const, }; await apiClient.startDebate(body); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/debate/start"); expect(init.method).toBe("POST"); expect(JSON.parse(init.body as string)).toEqual(body); }); it("startDebate → sends customTopic and difficulty", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ topic: {}, opponent: {}, rounds: 5, userSide: "con" })); const body = { customTopic: "AI should be regulated by governments", difficulty: "hard" as const, rounds: 5 as const, userSide: "con" as const, }; await apiClient.startDebate(body); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/debate/start"); expect(JSON.parse(init.body as string)).toEqual(body); }); it("startDebate → minimal body (random topic, default opponent)", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ topic: {}, opponent: {}, rounds: 3, userSide: "pro" })); await apiClient.startDebate({}); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/debate/start"); expect(init.method).toBe("POST"); expect(JSON.parse(init.body as string)).toEqual({}); }); it("debateRespond → POST /api/debate/respond with required fields", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ round: 1, opponentName: "Socrates", opponentArgument: "Consider this..." })); const body = { topic: "Free will is an illusion", opponentId: "socrates", round: 1, totalRounds: 3, userSide: "pro" as const, userArgument: "Free will cannot exist in a deterministic universe governed by physical laws.", }; await apiClient.debateRespond(body); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/debate/respond"); expect(init.method).toBe("POST"); expect(JSON.parse(init.body as string)).toEqual(body); }); it("debateRespond → sends conversation history", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ round: 2, opponentName: "Socrates", opponentArgument: "But tell me..." })); const history = [ { round: 1, userArgument: "My first argument.", opponentArgument: "Socrates' first reply." }, ]; const body = { topic: "Free will is an illusion", opponentId: "socrates", round: 2, totalRounds: 3, userSide: "pro" as const, userArgument: "My second argument.", history, }; await apiClient.debateRespond(body); const [, init] = mockFetch.mock.calls[0] as [string, RequestInit]; const parsed = JSON.parse(init.body as string); expect(parsed.history).toEqual(history); expect(parsed.round).toBe(2); }); it("debateJudge → POST /api/debate/judge with required fields", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ round: 1, user: { dimensionScores: {}, overallScore: 7, analysis: "Good." }, opponent: { dimensionScores: {}, overallScore: 6, analysis: "Decent." }, roundWinner: "user", roundSummary: "User edges round 1.", })); const body = { topic: "Capital punishment should be abolished", round: 1, totalRounds: 3, userArgument: "The death penalty is irreversible and risks executing innocents.", opponentArgument: "Certain crimes warrant the ultimate sanction as deterrence.", opponentName: "Frederick Douglass", }; await apiClient.debateJudge(body); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/debate/judge"); expect(init.method).toBe("POST"); expect(JSON.parse(init.body as string)).toEqual(body); }); it("debateJudge → sends previousRounds context", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ round: 2, user: { dimensionScores: {}, overallScore: 8, analysis: "Stronger in round 2." }, opponent: { dimensionScores: {}, overallScore: 7, analysis: "Solid." }, roundWinner: "user", roundSummary: "User wins round 2.", })); const previousRounds = [ { round: 1, user: { dimensionScores: { "argument-structure": 7 }, overallScore: 7, analysis: "Good." }, opponent: { dimensionScores: { "argument-structure": 6 }, overallScore: 6, analysis: "Ok." }, roundWinner: "user" as const, roundSummary: "User wins round 1.", langsmithRunId: null, }, ]; const body = { topic: "AI will eliminate more jobs than it creates", round: 2, totalRounds: 3, userArgument: "Historical technology transitions created net jobs; AI will too.", opponentArgument: "AI uniquely threatens cognitive labour at unprecedented scale.", opponentName: "The Sharp Analyst", previousRounds, }; await apiClient.debateJudge(body); const [, init] = mockFetch.mock.calls[0] as [string, RequestInit]; const parsed = JSON.parse(init.body as string); expect(parsed.previousRounds).toHaveLength(1); expect(parsed.previousRounds[0].round).toBe(1); }); it("debateSummary → POST /api/debate/summary with rounds array", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ judgement: { rounds: [], userTotalScore: 21, opponentTotalScore: 18, winner: "user", overallAnalysis: "...", userStrengths: [], userWeaknesses: [], suggestions: [] }, xp: { baseXp: 50, totalXp: 75, qualityBonus: 25, multiplierBonus: 0, multiplierPercent: 0, isCriticalHit: false }, qualityScore: 0.7, levelUp: false, categoryXp: { currentXp: 75, xpToNext: 100, level: 1, levelUp: false }, unlocks: [], streakFreezesGranted: 0, })); const rounds = [ { round: 1, user: { dimensionScores: {}, overallScore: 7, analysis: "Good." }, opponent: { dimensionScores: {}, overallScore: 6, analysis: "Ok." }, roundWinner: "user" as const, roundSummary: "User wins.", langsmithRunId: null, }, ]; const body = { topic: "Social media is net negative for democracy", opponentName: "Voltaire", opponentId: "voltaire", opponentDifficulty: "hard" as const, rounds, totalRounds: 1, userSide: "pro" as const, }; await apiClient.debateSummary(body); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/debate/summary"); expect(init.method).toBe("POST"); const parsed = JSON.parse(init.body as string); expect(parsed.topic).toBe(body.topic); expect(parsed.opponentId).toBe("voltaire"); expect(parsed.rounds).toHaveLength(1); }); it("debateSummary → sends durationSecs when provided", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ judgement: { rounds: [], userTotalScore: 18, opponentTotalScore: 20, winner: "opponent", overallAnalysis: "...", userStrengths: [], userWeaknesses: [], suggestions: [] }, xp: { baseXp: 50, totalXp: 50, qualityBonus: 0, multiplierBonus: 0, multiplierPercent: 0, isCriticalHit: false }, qualityScore: 0.4, levelUp: false, categoryXp: { currentXp: 50, xpToNext: 100, level: 1, levelUp: false }, unlocks: [], streakFreezesGranted: 0, })); const body = { topic: "Universal basic income is economically viable", opponentName: "Abraham Lincoln", opponentId: "lincoln", opponentDifficulty: "hard" as const, rounds: [], totalRounds: 3, userSide: "con" as const, durationSecs: 720, }; await apiClient.debateSummary(body); const [, init] = mockFetch.mock.calls[0] as [string, RequestInit]; const parsed = JSON.parse(init.body as string); expect(parsed.durationSecs).toBe(720); }); }); // --------------------------------------------------------------------------- // submitDebateFeedback // --------------------------------------------------------------------------- describe("apiClient.submitDebateFeedback", () => { const mockFetch = vi.fn(); beforeEach(() => { mockFetch.mockReset(); vi.spyOn(globalThis, "fetch").mockImplementation(mockFetch); }); afterEach(() => { vi.restoreAllMocks(); }); it("submitDebateFeedback → POST /api/debate/feedback", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ submitted: 3 })); await apiClient.submitDebateFeedback("run-abc-123", { "argument-structure": 7, persuasiveness: 8, "flaw-detection": 6, }); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; expect(url).toBe("/api/debate/feedback"); expect(init.method).toBe("POST"); }); it("submitDebateFeedback → sends runId in body", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ submitted: 1 })); await apiClient.submitDebateFeedback("run-xyz-999", { "argument-structure": 9, }); const [, init] = mockFetch.mock.calls[0] as [string, RequestInit]; const parsed = JSON.parse(init.body as string); expect(parsed.runId).toBe("run-xyz-999"); }); it("submitDebateFeedback → sends scores map in body", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ submitted: 2 })); const scores = { persuasiveness: 5, "intellectual-honesty": 8 }; await apiClient.submitDebateFeedback("run-abc-456", scores); const [, init] = mockFetch.mock.calls[0] as [string, RequestInit]; const parsed = JSON.parse(init.body as string); expect(parsed.scores).toEqual(scores); }); it("submitDebateFeedback → Content-Type is application/json", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ submitted: 0, skipped: "no key" })); await apiClient.submitDebateFeedback("run-test", {}); const [, init] = mockFetch.mock.calls[0] as [string, RequestInit]; const headers = init.headers as Record; expect(headers["Content-Type"]).toBe("application/json"); }); it("submitDebateFeedback → returns DebateFeedbackResponse with submitted count", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ submitted: 5 })); const result = await apiClient.submitDebateFeedback("run-abc", { "flaw-detection": 7, steelman: 6, persuasiveness: 8, "argument-structure": 9, "intellectual-honesty": 5, }); expect(result.submitted).toBe(5); }); it("submitDebateFeedback → returns skipped field when LangSmith not configured", async () => { mockFetch.mockResolvedValueOnce(makeResponse({ submitted: 0, skipped: "LANGSMITH_API_KEY not configured", })); const result = await apiClient.submitDebateFeedback("run-abc", { "argument-structure": 7, }); expect(result.submitted).toBe(0); expect(typeof result.skipped).toBe("string"); }); });