generated from nhcarrigan/template
0d36b255ee
Add six new goddess-mode API routes (boss fight, consecration, enlightenment, upgrade purchase, crafting, exploration) alongside matching service modules and full test suites at 100% coverage.
296 lines
12 KiB
TypeScript
296 lines
12 KiB
TypeScript
/* eslint-disable max-lines-per-function -- Test suites naturally have many cases */
|
|
/* eslint-disable max-lines -- Test suites naturally have many cases */
|
|
/* eslint-disable @typescript-eslint/consistent-type-assertions -- Tests build minimal state objects */
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { Hono } from "hono";
|
|
import type { GameState } from "@elysium/types";
|
|
|
|
vi.mock("../../src/db/client.js", () => ({
|
|
prisma: {
|
|
gameState: { findUnique: vi.fn(), update: vi.fn() },
|
|
},
|
|
}));
|
|
|
|
vi.mock("../../src/middleware/auth.js", () => ({
|
|
authMiddleware: vi.fn(async (c: { set: (key: string, value: string) => void }, next: () => Promise<void>) => {
|
|
c.set("discordId", "test_discord_id");
|
|
await next();
|
|
}),
|
|
}));
|
|
|
|
vi.mock("../../src/services/logger.js", () => ({
|
|
logger: {
|
|
error: vi.fn().mockResolvedValue(undefined),
|
|
metric: vi.fn().mockResolvedValue(undefined),
|
|
},
|
|
}));
|
|
|
|
const DISCORD_ID = "test_discord_id";
|
|
|
|
const makeConsecration = (overrides: Record<string, unknown> = {}) => ({
|
|
count: 0,
|
|
divinity: 0,
|
|
productionMultiplier: 1,
|
|
purchasedUpgradeIds: [] as string[],
|
|
...overrides,
|
|
});
|
|
|
|
const makeEnlightenment = (overrides: Record<string, unknown> = {}) => ({
|
|
count: 0,
|
|
stardust: 0,
|
|
purchasedUpgradeIds: [] as string[],
|
|
stardustPrayersMultiplier: 1,
|
|
stardustCombatMultiplier: 1,
|
|
stardustConsecrationThresholdMultiplier: 1,
|
|
stardustConsecrationDivinityMultiplier: 1,
|
|
stardustMetaMultiplier: 1,
|
|
...overrides,
|
|
});
|
|
|
|
const makeGoddessExploration = (overrides: Record<string, unknown> = {}) => ({
|
|
areas: [] as Array<{ id: string; status: string }>,
|
|
materials: [] as Array<{ materialId: string; quantity: number }>,
|
|
craftedRecipeIds: [] as string[],
|
|
craftedPrayersMultiplier: 1,
|
|
craftedDivinityMultiplier: 1,
|
|
craftedCombatMultiplier: 1,
|
|
...overrides,
|
|
});
|
|
|
|
/**
|
|
* Creates a minimal GoddessState that has met the first consecration threshold (50 000 prayers).
|
|
*/
|
|
const makeGoddessStateEligible = (overrides: Record<string, unknown> = {}) => ({
|
|
zones: [] as Array<{ id: string; status: string }>,
|
|
bosses: [] as Array<{ id: string; status: string }>,
|
|
quests: [] as Array<{ id: string; status: string }>,
|
|
disciples: [] as Array<{ id: string; count: number }>,
|
|
equipment: [] as Array<{ id: string; type: string; owned: boolean; equipped: boolean; bonus: Record<string, unknown> }>,
|
|
upgrades: [] as Array<{ id: string; purchased: boolean; target: string; multiplier: number }>,
|
|
achievements: [] as Array<{ id: string; completed: boolean }>,
|
|
consecration: makeConsecration(),
|
|
enlightenment: makeEnlightenment(),
|
|
exploration: makeGoddessExploration(),
|
|
totalPrayersEarned: 50_000, // Meets base threshold for count=0
|
|
lifetimePrayersEarned: 50_000,
|
|
lifetimeBossesDefeated: 0,
|
|
lifetimeQuestsCompleted: 0,
|
|
baseClickPower: 1,
|
|
lastTickAt: 0,
|
|
...overrides,
|
|
});
|
|
|
|
/**
|
|
* Creates a minimal GoddessState that has NOT met the consecration threshold.
|
|
*/
|
|
const makeGoddessStateIneligible = (overrides: Record<string, unknown> = {}) => ({
|
|
...makeGoddessStateEligible(),
|
|
totalPrayersEarned: 0,
|
|
...overrides,
|
|
});
|
|
|
|
const makeState = (overrides: Partial<GameState> = {}): GameState => ({
|
|
player: { discordId: DISCORD_ID, username: "u", discriminator: "0", avatar: null, totalGoldEarned: 0, totalClicks: 0, characterName: "T" },
|
|
resources: { gold: 0, essence: 0, crystals: 0, runestones: 0, prayers: 0 },
|
|
adventurers: [],
|
|
upgrades: [],
|
|
quests: [],
|
|
bosses: [],
|
|
equipment: [],
|
|
achievements: [],
|
|
zones: [],
|
|
exploration: { areas: [], materials: [], craftedRecipeIds: [], craftedGoldMultiplier: 1, craftedEssenceMultiplier: 1, craftedClickMultiplier: 1, craftedCombatMultiplier: 1 },
|
|
companions: { unlockedCompanionIds: [], activeCompanionId: null },
|
|
prestige: { count: 0, runestones: 0, productionMultiplier: 1, purchasedUpgradeIds: [] },
|
|
baseClickPower: 1,
|
|
lastTickAt: 0,
|
|
schemaVersion: 1,
|
|
goddess: makeGoddessStateEligible() as GameState["goddess"],
|
|
...overrides,
|
|
} as GameState);
|
|
|
|
describe("consecration route", () => {
|
|
let app: Hono;
|
|
let prisma: { gameState: { findUnique: ReturnType<typeof vi.fn>; update: ReturnType<typeof vi.fn> } };
|
|
|
|
beforeEach(async () => {
|
|
vi.clearAllMocks();
|
|
const { consecrationRouter } = await import("../../src/routes/consecration.js");
|
|
const { prisma: p } = await import("../../src/db/client.js");
|
|
prisma = p as typeof prisma;
|
|
app = new Hono();
|
|
app.route("/consecration", consecrationRouter);
|
|
});
|
|
|
|
const post = (path: string, body?: Record<string, unknown>) =>
|
|
app.fetch(new Request(`http://localhost/consecration${path}`, {
|
|
method: "POST",
|
|
headers: body !== undefined ? { "Content-Type": "application/json" } : undefined,
|
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
}));
|
|
|
|
describe("POST /", () => {
|
|
it("returns 404 when no save is found", async () => {
|
|
vi.mocked(prisma.gameState.findUnique).mockResolvedValueOnce(null);
|
|
const res = await post("");
|
|
expect(res.status).toBe(404);
|
|
});
|
|
|
|
it("returns 400 when goddess realm is not unlocked", async () => {
|
|
const state = makeState({ goddess: undefined });
|
|
vi.mocked(prisma.gameState.findUnique).mockResolvedValueOnce({ state } as never);
|
|
const res = await post("");
|
|
expect(res.status).toBe(400);
|
|
const body = await res.json() as { error: string };
|
|
expect(body.error).toBe("Goddess realm not unlocked");
|
|
});
|
|
|
|
it("returns 400 with threshold message when not eligible", async () => {
|
|
const state = makeState({
|
|
goddess: makeGoddessStateIneligible() as GameState["goddess"],
|
|
});
|
|
vi.mocked(prisma.gameState.findUnique).mockResolvedValueOnce({ state } as never);
|
|
const res = await post("");
|
|
expect(res.status).toBe(400);
|
|
const body = await res.json() as { error: string };
|
|
expect(body.error).toMatch(/Not eligible for consecration/u);
|
|
expect(body.error).toMatch(/50,000/u);
|
|
});
|
|
|
|
it("returns 200 with divinityEarned and newConsecrationCount on success", async () => {
|
|
const state = makeState();
|
|
vi.mocked(prisma.gameState.findUnique).mockResolvedValueOnce({ state } as never);
|
|
vi.mocked(prisma.gameState.update).mockResolvedValueOnce({} as never);
|
|
const res = await post("");
|
|
expect(res.status).toBe(200);
|
|
const body = await res.json() as { divinityEarned: number; newConsecrationCount: number };
|
|
expect(body.newConsecrationCount).toBe(1);
|
|
expect(body.divinityEarned).toBeGreaterThanOrEqual(1);
|
|
});
|
|
|
|
it("applies the threshold multiplier when checking eligibility", async () => {
|
|
// threshold multiplier of 2 means we need 100 000 prayers for count=0 but only have 50 000
|
|
const state = makeState({
|
|
goddess: makeGoddessStateIneligible({
|
|
totalPrayersEarned: 50_000,
|
|
enlightenment: makeEnlightenment({ stardustConsecrationThresholdMultiplier: 2 }),
|
|
}) as GameState["goddess"],
|
|
});
|
|
vi.mocked(prisma.gameState.findUnique).mockResolvedValueOnce({ state } as never);
|
|
const res = await post("");
|
|
expect(res.status).toBe(400);
|
|
const body = await res.json() as { error: string };
|
|
// threshold should be 100 000 with multiplier 2
|
|
expect(body.error).toMatch(/100,000/u);
|
|
});
|
|
|
|
it("returns 500 when database throws an Error", async () => {
|
|
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce(new Error("DB error"));
|
|
const res = await post("");
|
|
expect(res.status).toBe(500);
|
|
});
|
|
|
|
it("returns 500 when database throws a non-Error value", async () => {
|
|
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce("raw string error");
|
|
const res = await post("");
|
|
expect(res.status).toBe(500);
|
|
});
|
|
});
|
|
|
|
describe("POST /buy-upgrade", () => {
|
|
it("returns 400 when upgradeId is missing", async () => {
|
|
const res = await post("/buy-upgrade", {});
|
|
expect(res.status).toBe(400);
|
|
const body = await res.json() as { error: string };
|
|
expect(body.error).toBe("upgradeId is required");
|
|
});
|
|
|
|
it("returns 404 for an unknown upgrade", async () => {
|
|
const res = await post("/buy-upgrade", { upgradeId: "nonexistent_upgrade_id" });
|
|
expect(res.status).toBe(404);
|
|
const body = await res.json() as { error: string };
|
|
expect(body.error).toBe("Unknown consecration upgrade");
|
|
});
|
|
|
|
it("returns 404 when no save is found", async () => {
|
|
vi.mocked(prisma.gameState.findUnique).mockResolvedValueOnce(null);
|
|
const res = await post("/buy-upgrade", { upgradeId: "divine_prayers_1" });
|
|
expect(res.status).toBe(404);
|
|
});
|
|
|
|
it("returns 400 when goddess realm is not unlocked", async () => {
|
|
const state = makeState({ goddess: undefined });
|
|
vi.mocked(prisma.gameState.findUnique).mockResolvedValueOnce({ state } as never);
|
|
const res = await post("/buy-upgrade", { upgradeId: "divine_prayers_1" });
|
|
expect(res.status).toBe(400);
|
|
const body = await res.json() as { error: string };
|
|
expect(body.error).toBe("Goddess realm not unlocked");
|
|
});
|
|
|
|
it("returns 400 when upgrade is already purchased", async () => {
|
|
const state = makeState({
|
|
goddess: makeGoddessStateEligible({
|
|
consecration: makeConsecration({
|
|
divinity: 100,
|
|
purchasedUpgradeIds: [ "divine_prayers_1" ],
|
|
}),
|
|
}) as GameState["goddess"],
|
|
});
|
|
vi.mocked(prisma.gameState.findUnique).mockResolvedValueOnce({ state } as never);
|
|
const res = await post("/buy-upgrade", { upgradeId: "divine_prayers_1" });
|
|
expect(res.status).toBe(400);
|
|
const body = await res.json() as { error: string };
|
|
expect(body.error).toBe("Upgrade already purchased");
|
|
});
|
|
|
|
it("returns 400 when not enough divinity", async () => {
|
|
// divine_prayers_1 costs 5 divinity — give the player 0
|
|
const state = makeState({
|
|
goddess: makeGoddessStateEligible({
|
|
consecration: makeConsecration({ divinity: 0 }),
|
|
}) as GameState["goddess"],
|
|
});
|
|
vi.mocked(prisma.gameState.findUnique).mockResolvedValueOnce({ state } as never);
|
|
const res = await post("/buy-upgrade", { upgradeId: "divine_prayers_1" });
|
|
expect(res.status).toBe(400);
|
|
const body = await res.json() as { error: string };
|
|
expect(body.error).toBe("Not enough divinity");
|
|
});
|
|
|
|
it("returns 200 with updated multipliers on successful purchase", async () => {
|
|
// divine_prayers_1 costs 5 divinity and is in the "prayers" category
|
|
const state = makeState({
|
|
goddess: makeGoddessStateEligible({
|
|
consecration: makeConsecration({ divinity: 100 }),
|
|
}) as GameState["goddess"],
|
|
});
|
|
vi.mocked(prisma.gameState.findUnique).mockResolvedValueOnce({ state } as never);
|
|
vi.mocked(prisma.gameState.update).mockResolvedValueOnce({} as never);
|
|
const res = await post("/buy-upgrade", { upgradeId: "divine_prayers_1" });
|
|
expect(res.status).toBe(200);
|
|
const body = await res.json() as {
|
|
divinityRemaining: number;
|
|
purchasedUpgradeIds: string[];
|
|
divinityPrayersMultiplier: number;
|
|
divinityDisciplesMultiplier: number;
|
|
divinityCombatMultiplier: number;
|
|
};
|
|
expect(body.divinityRemaining).toBe(95); // 100 - 5
|
|
expect(body.purchasedUpgradeIds).toContain("divine_prayers_1");
|
|
expect(body.divinityPrayersMultiplier).toBeGreaterThan(1);
|
|
});
|
|
|
|
it("returns 500 when database throws an Error during buy-upgrade", async () => {
|
|
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce(new Error("DB error"));
|
|
const res = await post("/buy-upgrade", { upgradeId: "divine_prayers_1" });
|
|
expect(res.status).toBe(500);
|
|
});
|
|
|
|
it("returns 500 when database throws a non-Error value during buy-upgrade", async () => {
|
|
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce("raw string error");
|
|
const res = await post("/buy-upgrade", { upgradeId: "divine_prayers_1" });
|
|
expect(res.status).toBe(500);
|
|
});
|
|
});
|
|
});
|