RotNot / src /lib /feynman /__tests__ /get-knowledge-profile.test.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
17.6 kB
/**
* Unit tests for getKnowledgeProfile (DB-backed).
*
* Covers:
* - DB query params: userId filter, feynman category filter,
* chronological asc ordering, select fields
* - Empty activity list: zero totals, empty domains/recentTopicIds,
* beginner recommendation
* - userId passthrough in returned profile
* - totalAttempts counts only parseable activities (skips null/malformed metadata)
* - recentTopicIds: last RECENCY_WINDOW (10) attempts, most-recent-first order
* - recommendedDifficulty derivation:
* < 3 β†’ beginner, moderate+low avg β†’ intermediate, β‰₯8 + avgβ‰₯0.65 β†’ expert
* - domains: correctly grouped and propagated from buildDomainProfiles()
* (domain key is the `domain` field from FEYNMAN_TOPICS, e.g. "CS", "Physics")
* - Error propagation: DB throws β†’ getKnowledgeProfile throws
*
* parseActivityMetadata matches by `meta.topic` string to a FEYNMAN_TOPICS entry,
* so we use real topic names from the library as metadata values.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
// ── Mock Prisma ──────────────────────────────────────────────────────────────
const mockActivityFindMany = vi.fn();
vi.mock("@/lib/db", () => ({
prisma: {
activity: {
findMany: (...args: unknown[]) => mockActivityFindMany(...args),
},
},
}));
// Import after mock hoisting
import { getKnowledgeProfile } from "../knowledge-profile";
// ── Known topic names from FEYNMAN_TOPICS (used in metadata) ─────────────────
// These must match exactly so parseActivityMetadata can look them up.
const TOPIC_CS_01 = "How a hash table works"; // cs-01, CS, beginner
const TOPIC_CS_02 = "Big O notation and time complexity"; // cs-02, CS, beginner
const TOPIC_CS_03 = "How recursion works"; // cs-03, CS, beginner
const TOPIC_PH_01 = "Newton's three laws of motion"; // ph-01, Physics, beginner
const TOPIC_MA_01 = "What a derivative represents in calculus"; // ma-01, Mathematics, beginner
const TOPIC_BI_01 = "How DNA replication works"; // bi-01, Biology, beginner
// ── Helpers ──────────────────────────────────────────────────────────────────
/**
* Build a raw activity row as Prisma would return it.
* Uses actual FEYNMAN_TOPICS topic strings so parseActivityMetadata can match them.
*/
function makeActivity(
topicString: string,
score: number,
createdAt: Date = new Date("2026-01-01T00:00:00Z"),
extra: Record<string, unknown> = {},
): { metadata: string | null; score: number; createdAt: Date } {
return {
metadata: JSON.stringify({ topic: topicString, ...extra }),
score,
createdAt,
};
}
// ── Tests ────────────────────────────────────────────────────────────────────
describe("getKnowledgeProfile", () => {
beforeEach(() => {
mockActivityFindMany.mockReset();
});
// ── DB query params ───────────────────────────────────────────────────────
it("queries DB with userId filter", async () => {
mockActivityFindMany.mockResolvedValue([]);
await getKnowledgeProfile(42);
expect(mockActivityFindMany).toHaveBeenCalledOnce();
const [args] = mockActivityFindMany.mock.calls[0];
expect(args.where.userId).toBe(42);
});
it("filters to feynman category only", async () => {
mockActivityFindMany.mockResolvedValue([]);
await getKnowledgeProfile(1);
const [args] = mockActivityFindMany.mock.calls[0];
expect(args.where.category).toBe("feynman");
});
it("orders activities ascending by createdAt", async () => {
mockActivityFindMany.mockResolvedValue([]);
await getKnowledgeProfile(1);
const [args] = mockActivityFindMany.mock.calls[0];
expect(args.orderBy).toEqual({ createdAt: "asc" });
});
it("selects only metadata, score, and createdAt", async () => {
mockActivityFindMany.mockResolvedValue([]);
await getKnowledgeProfile(1);
const [args] = mockActivityFindMany.mock.calls[0];
expect(args.select).toEqual({
metadata: true,
score: true,
createdAt: true,
});
});
// ── Empty activity list ───────────────────────────────────────────────────
it("returns userId in profile", async () => {
mockActivityFindMany.mockResolvedValue([]);
const profile = await getKnowledgeProfile(7);
expect(profile.userId).toBe(7);
});
it("returns 0 totalAttempts for empty activity list", async () => {
mockActivityFindMany.mockResolvedValue([]);
const profile = await getKnowledgeProfile(1);
expect(profile.totalAttempts).toBe(0);
});
it("returns empty domains map for empty activity list", async () => {
mockActivityFindMany.mockResolvedValue([]);
const profile = await getKnowledgeProfile(1);
expect(profile.domains.size).toBe(0);
});
it("returns empty recentTopicIds for empty activity list", async () => {
mockActivityFindMany.mockResolvedValue([]);
const profile = await getKnowledgeProfile(1);
expect(profile.recentTopicIds).toEqual([]);
});
it("recommends beginner for new users with no activities", async () => {
mockActivityFindMany.mockResolvedValue([]);
const profile = await getKnowledgeProfile(1);
expect(profile.recommendedDifficulty).toBe("beginner");
});
// ── Parseable vs unparseable activities ───────────────────────────────────
it("counts only parseable activities in totalAttempts", async () => {
mockActivityFindMany.mockResolvedValue([
makeActivity(TOPIC_CS_01, 0.8),
makeActivity(TOPIC_CS_02, 0.7),
{ metadata: null, score: 0.5, createdAt: new Date() }, // null β†’ skipped
{ metadata: "not-json{{{", score: 0.5, createdAt: new Date() }, // malformed β†’ skipped
{ metadata: JSON.stringify({ noTopicField: true }), score: 0.5, createdAt: new Date() }, // missing topic β†’ skipped
]);
const profile = await getKnowledgeProfile(1);
expect(profile.totalAttempts).toBe(2);
});
it("skips null metadata without throwing", async () => {
mockActivityFindMany.mockResolvedValue([
{ metadata: null, score: 0.8, createdAt: new Date() },
]);
const profile = await getKnowledgeProfile(1);
expect(profile.totalAttempts).toBe(0);
expect(profile.recentTopicIds).toEqual([]);
});
it("skips malformed JSON metadata without throwing", async () => {
mockActivityFindMany.mockResolvedValue([
{ metadata: "{{bad json", score: 0.8, createdAt: new Date() },
]);
const profile = await getKnowledgeProfile(1);
expect(profile.totalAttempts).toBe(0);
});
it("parses activities with unknown topic strings (fallback topicId)", async () => {
// A topic not in FEYNMAN_TOPICS still parses as a TopicAttempt with a generated ID
mockActivityFindMany.mockResolvedValue([
{ metadata: JSON.stringify({ topic: "Some obscure topic not in library" }), score: 0.7, createdAt: new Date() },
]);
const profile = await getKnowledgeProfile(1);
// Unknown topics still count as attempts
expect(profile.totalAttempts).toBe(1);
});
// ── totalAttempts ─────────────────────────────────────────────────────────
it("totalAttempts equals number of parseable activities", async () => {
mockActivityFindMany.mockResolvedValue([
makeActivity(TOPIC_CS_01, 0.8),
makeActivity(TOPIC_CS_02, 0.7),
makeActivity(TOPIC_PH_01, 0.9),
]);
const profile = await getKnowledgeProfile(1);
expect(profile.totalAttempts).toBe(3);
});
// ── recentTopicIds ────────────────────────────────────────────────────────
it("recentTopicIds reflects most-recent-first ordering", async () => {
// Activities arrive ordered asc from DB; recentTopicIds should be newest-first
mockActivityFindMany.mockResolvedValue([
makeActivity(TOPIC_CS_01, 0.8, new Date("2026-01-01T00:00:00Z")),
makeActivity(TOPIC_CS_02, 0.7, new Date("2026-01-02T00:00:00Z")),
makeActivity(TOPIC_PH_01, 0.9, new Date("2026-01-03T00:00:00Z")),
]);
const profile = await getKnowledgeProfile(1);
// Most recent first: ph-01, cs-02, cs-01
expect(profile.recentTopicIds[0]).toBe("ph-01");
expect(profile.recentTopicIds[1]).toBe("cs-02");
expect(profile.recentTopicIds[2]).toBe("cs-01");
expect(profile.recentTopicIds.length).toBe(3);
});
it("caps recentTopicIds at 10 entries (RECENCY_WINDOW)", async () => {
// 12 activities using 12 distinct known topics β€” only the last 10 should appear
const topicStrings = [
TOPIC_CS_01,
TOPIC_CS_02,
TOPIC_CS_03,
TOPIC_PH_01,
TOPIC_MA_01,
TOPIC_BI_01,
"Newton's three laws of motion", // ph-01 reuse (same string = same ID)
"Big O notation and time complexity", // cs-02 reuse
"How recursion works", // cs-03 reuse
"Why imaginary numbers are real and useful", // ma-01 reuse
"How a compiler turns source code into machine code", // cs-10 β€” 11th
"How the MapReduce pattern works", // cs-11 β€” 12th
];
const activities = topicStrings.map((topic, i) => ({
metadata: JSON.stringify({ topic }),
score: 0.7,
createdAt: new Date(Date.UTC(2026, 0, i + 1)),
}));
mockActivityFindMany.mockResolvedValue(activities);
const profile = await getKnowledgeProfile(1);
expect(profile.recentTopicIds.length).toBe(10);
// The last (12th) activity topic should be first in recentTopicIds
expect(profile.recentTopicIds[0]).toBe("cs-11");
// The first (1st) activity topic (cs-01) should not be in the window
expect(profile.recentTopicIds).not.toContain("cs-01");
});
it("recentTopicIds includes all topics when fewer than 10 activities", async () => {
mockActivityFindMany.mockResolvedValue([
makeActivity(TOPIC_CS_01, 0.7, new Date("2026-01-01T00:00:00Z")),
makeActivity(TOPIC_MA_01, 0.8, new Date("2026-01-02T00:00:00Z")),
]);
const profile = await getKnowledgeProfile(1);
expect(profile.recentTopicIds.length).toBe(2);
// Most recent first: ma-01, cs-01
expect(profile.recentTopicIds[0]).toBe("ma-01");
expect(profile.recentTopicIds[1]).toBe("cs-01");
});
// ── recommendedDifficulty ─────────────────────────────────────────────────
it("recommends beginner when fewer than 3 parseable activities", async () => {
mockActivityFindMany.mockResolvedValue([
makeActivity(TOPIC_CS_01, 0.9),
makeActivity(TOPIC_CS_02, 0.95),
]);
const profile = await getKnowledgeProfile(1);
expect(profile.recommendedDifficulty).toBe("beginner");
});
it("recommends intermediate for moderate experience with low-average scores", async () => {
// 5 attempts with avg score 0.5 β†’ intermediate (β‰₯3 attempts, avg < 0.65)
const activities = [
makeActivity(TOPIC_CS_01, 0.5),
makeActivity(TOPIC_CS_02, 0.5),
makeActivity(TOPIC_CS_03, 0.5),
makeActivity(TOPIC_PH_01, 0.5),
makeActivity(TOPIC_MA_01, 0.5),
];
mockActivityFindMany.mockResolvedValue(activities);
const profile = await getKnowledgeProfile(1);
expect(profile.recommendedDifficulty).toBe("intermediate");
});
it("recommends expert for experienced users with high average scores", async () => {
// 8+ attempts with avg score >= 0.65 β†’ expert
const activities = [
makeActivity(TOPIC_CS_01, 0.8),
makeActivity(TOPIC_CS_02, 0.8),
makeActivity(TOPIC_CS_03, 0.8),
makeActivity(TOPIC_PH_01, 0.8),
makeActivity(TOPIC_MA_01, 0.8),
makeActivity(TOPIC_BI_01, 0.8),
makeActivity("Newton's three laws of motion", 0.8),
makeActivity("Big O notation and time complexity", 0.8),
];
mockActivityFindMany.mockResolvedValue(activities);
const profile = await getKnowledgeProfile(1);
expect(profile.recommendedDifficulty).toBe("expert");
});
it("stays intermediate when attempt count is high but avg score is below expert threshold", async () => {
// 10 attempts but avg score 0.4 β€” not enough for expert
const activities = Array.from({ length: 10 }, () =>
makeActivity(TOPIC_CS_01, 0.4),
);
mockActivityFindMany.mockResolvedValue(activities);
const profile = await getKnowledgeProfile(1);
expect(profile.recommendedDifficulty).toBe("intermediate");
});
// ── domain profiles ───────────────────────────────────────────────────────
it("populates domains from activities", async () => {
mockActivityFindMany.mockResolvedValue([
makeActivity(TOPIC_CS_01, 0.8),
makeActivity(TOPIC_CS_02, 0.9),
makeActivity(TOPIC_PH_01, 0.7),
]);
const profile = await getKnowledgeProfile(1);
expect(profile.domains.has("CS")).toBe(true);
expect(profile.domains.has("Physics")).toBe(true);
expect(profile.domains.size).toBe(2);
});
it("domain attempt count matches parseable activities in that domain", async () => {
mockActivityFindMany.mockResolvedValue([
makeActivity(TOPIC_CS_01, 0.8),
makeActivity(TOPIC_CS_02, 0.9),
makeActivity(TOPIC_PH_01, 0.7),
]);
const profile = await getKnowledgeProfile(1);
expect(profile.domains.get("CS")?.attempts).toBe(2);
expect(profile.domains.get("Physics")?.attempts).toBe(1);
});
it("domain avgScore is the mean score for that domain", async () => {
mockActivityFindMany.mockResolvedValue([
makeActivity(TOPIC_CS_01, 0.6),
makeActivity(TOPIC_CS_02, 0.8),
]);
const profile = await getKnowledgeProfile(1);
// avg of 0.6 and 0.8 = 0.7
expect(profile.domains.get("CS")?.avgScore).toBeCloseTo(0.7, 5);
});
it("marks topic as mastered when avg score across its attempts >= 0.7", async () => {
mockActivityFindMany.mockResolvedValue([
makeActivity(TOPIC_CS_01, 0.8),
makeActivity(TOPIC_CS_01, 0.9), // same topic, two high-score attempts β†’ mastered
]);
const profile = await getKnowledgeProfile(1);
expect(profile.domains.get("CS")?.masteredTopics).toContain("cs-01");
});
it("does not mark topic as mastered when avg score < 0.7", async () => {
mockActivityFindMany.mockResolvedValue([
makeActivity(TOPIC_CS_01, 0.5),
makeActivity(TOPIC_CS_01, 0.6), // avg 0.55 β†’ not mastered
]);
const profile = await getKnowledgeProfile(1);
expect(profile.domains.get("CS")?.masteredTopics).not.toContain("cs-01");
});
it("tracks attempted topic IDs in the domain profile", async () => {
mockActivityFindMany.mockResolvedValue([
makeActivity(TOPIC_CS_01, 0.5), // cs-01
makeActivity(TOPIC_CS_03, 0.7), // cs-03
]);
const profile = await getKnowledgeProfile(1);
const cs = profile.domains.get("CS");
expect(cs?.attemptedTopicIds.has("cs-01")).toBe(true);
expect(cs?.attemptedTopicIds.has("cs-03")).toBe(true);
expect(cs?.attemptedTopicIds.has("cs-02")).toBe(false);
});
it("tracks taughtCount for wasTaught activities", async () => {
mockActivityFindMany.mockResolvedValue([
makeActivity(TOPIC_CS_01, 0.7, new Date(), { wasTaught: true }),
makeActivity(TOPIC_CS_02, 0.8, new Date(), { wasTaught: false }),
makeActivity(TOPIC_CS_03, 0.6, new Date()), // no wasTaught field
]);
const profile = await getKnowledgeProfile(1);
expect(profile.domains.get("CS")?.taughtCount).toBe(1);
});
it("separates activities into correct domains when multiple domains present", async () => {
mockActivityFindMany.mockResolvedValue([
makeActivity(TOPIC_CS_01, 0.7), // CS
makeActivity(TOPIC_PH_01, 0.8), // Physics
makeActivity(TOPIC_MA_01, 0.9), // Mathematics
makeActivity(TOPIC_BI_01, 0.6), // Biology
]);
const profile = await getKnowledgeProfile(1);
expect(profile.domains.size).toBe(4);
expect(profile.domains.get("CS")?.attempts).toBe(1);
expect(profile.domains.get("Physics")?.attempts).toBe(1);
expect(profile.domains.get("Mathematics")?.attempts).toBe(1);
expect(profile.domains.get("Biology")?.attempts).toBe(1);
});
// ── Error propagation ─────────────────────────────────────────────────────
it("propagates DB errors", async () => {
mockActivityFindMany.mockRejectedValue(new Error("DB connection lost"));
await expect(getKnowledgeProfile(1)).rejects.toThrow("DB connection lost");
});
});