RotNot / src /app /api /chess /__tests__ /challenge.test.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
7.91 kB
/**
* Tests for /api/chess/challenge route.
*
* Covers:
* - clampStockfishLevel β€” pure level-clamping function
* - POST handler β€” token guard (503), Lichess failure (502), success (200)
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { NextRequest, NextResponse } from "next/server";
// ---------------------------------------------------------------------------
// Mock challengeStockfish (avoid real network calls)
// ---------------------------------------------------------------------------
const mockChallengeStockfish = vi.fn();
vi.mock("@/lib/lichess", () => ({
challengeStockfish: (...args: unknown[]) => mockChallengeStockfish(...args),
}));
// ---------------------------------------------------------------------------
// Imports (after mocks)
// ---------------------------------------------------------------------------
import { POST, clampStockfishLevel } from "../challenge/route";
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const originalEnv = { ...process.env };
function makeRequest(body?: Record<string, unknown>): NextRequest {
return new NextRequest("http://localhost/api/chess/challenge", {
method: "POST",
body: body !== undefined ? JSON.stringify(body) : undefined,
headers: { "Content-Type": "application/json" },
});
}
async function parseJson(res: NextResponse): Promise<unknown> {
return res.json();
}
beforeEach(() => {
mockChallengeStockfish.mockReset();
process.env = { ...originalEnv, LICHESS_API_TOKEN: "test-token" };
});
afterEach(() => {
process.env = originalEnv;
});
// ─── clampStockfishLevel ─────────────────────────────────────────────────────
describe("clampStockfishLevel", () => {
it("returns the level unchanged when in range [1, 8]", () => {
expect(clampStockfishLevel(1)).toBe(1);
expect(clampStockfishLevel(4)).toBe(4);
expect(clampStockfishLevel(8)).toBe(8);
});
it("clamps values below 1 to 1", () => {
expect(clampStockfishLevel(0)).toBe(1);
expect(clampStockfishLevel(-5)).toBe(1);
expect(clampStockfishLevel(-Infinity)).toBe(1);
});
it("clamps values above 8 to 8", () => {
expect(clampStockfishLevel(9)).toBe(8);
expect(clampStockfishLevel(100)).toBe(8);
expect(clampStockfishLevel(Infinity)).toBe(8);
});
it("rounds fractional levels to the nearest integer", () => {
expect(clampStockfishLevel(3.5)).toBe(4);
expect(clampStockfishLevel(3.4)).toBe(3);
expect(clampStockfishLevel(7.9)).toBe(8);
});
it("defaults to 4 when level is undefined", () => {
expect(clampStockfishLevel(undefined)).toBe(4);
});
it("defaults to 4 when level is null", () => {
expect(clampStockfishLevel(null)).toBe(4);
});
it("defaults to 4 when level is a string", () => {
expect(clampStockfishLevel("5")).toBe(4);
});
it("defaults to 4 when level is a boolean", () => {
expect(clampStockfishLevel(true)).toBe(4);
});
it("defaults to 4 when level is an object", () => {
expect(clampStockfishLevel({})).toBe(4);
});
});
// ─── POST /api/chess/challenge β€” token guard ─────────────────────────────────
describe("POST /api/chess/challenge β€” LICHESS_API_TOKEN guard", () => {
it("returns 503 when LICHESS_API_TOKEN is not set", async () => {
delete process.env.LICHESS_API_TOKEN;
const res = await POST(makeRequest({ level: 4 }));
expect(res.status).toBe(503);
const body = await parseJson(res) as { error: string };
expect(body.error).toContain("LICHESS_API_TOKEN");
});
it("returns 503 when LICHESS_API_TOKEN is an empty string", async () => {
process.env.LICHESS_API_TOKEN = "";
const res = await POST(makeRequest({ level: 4 }));
expect(res.status).toBe(503);
});
it("does not call challengeStockfish when token is missing", async () => {
delete process.env.LICHESS_API_TOKEN;
await POST(makeRequest({ level: 4 }));
expect(mockChallengeStockfish).not.toHaveBeenCalled();
});
});
// ─── POST /api/chess/challenge β€” Lichess failure ─────────────────────────────
describe("POST /api/chess/challenge β€” Lichess failure (502)", () => {
it("returns 502 when challengeStockfish returns null", async () => {
mockChallengeStockfish.mockResolvedValueOnce(null);
const res = await POST(makeRequest({ level: 3 }));
expect(res.status).toBe(502);
const body = await parseJson(res) as { error: string };
expect(body.error).toMatch(/Failed to create Stockfish challenge/i);
});
it("still calls challengeStockfish with the correct level when token is present", async () => {
mockChallengeStockfish.mockResolvedValueOnce(null);
await POST(makeRequest({ level: 6 }));
expect(mockChallengeStockfish).toHaveBeenCalledWith(6);
});
});
// ─── POST /api/chess/challenge β€” success ─────────────────────────────────────
describe("POST /api/chess/challenge β€” success", () => {
const MOCK_CHALLENGE = {
id: "abc123xyz",
url: "https://lichess.org/abc123xyz",
};
it("returns 200 with gameId, gameUrl, and level on success", async () => {
mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE);
const res = await POST(makeRequest({ level: 5 }));
expect(res.status).toBe(200);
const body = await parseJson(res) as { gameId: string; gameUrl: string; level: number };
expect(body.gameId).toBe("abc123xyz");
expect(body.gameUrl).toBe("https://lichess.org/abc123xyz");
expect(body.level).toBe(5);
});
it("defaults level to 4 when no body is provided", async () => {
mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE);
const res = await POST(
new NextRequest("http://localhost/api/chess/challenge", { method: "POST" })
);
expect(res.status).toBe(200);
const body = await parseJson(res) as { level: number };
expect(body.level).toBe(4);
expect(mockChallengeStockfish).toHaveBeenCalledWith(4);
});
it("defaults level to 4 when level is omitted from body", async () => {
mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE);
const res = await POST(makeRequest({}));
const body = await parseJson(res) as { level: number };
expect(body.level).toBe(4);
});
it("clamps level 9 β†’ 8 and passes 8 to challengeStockfish", async () => {
mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE);
const res = await POST(makeRequest({ level: 9 }));
expect(res.status).toBe(200);
const body = await parseJson(res) as { level: number };
expect(body.level).toBe(8);
expect(mockChallengeStockfish).toHaveBeenCalledWith(8);
});
it("clamps level 0 β†’ 1 and passes 1 to challengeStockfish", async () => {
mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE);
const res = await POST(makeRequest({ level: 0 }));
expect(res.status).toBe(200);
const body = await parseJson(res) as { level: number };
expect(body.level).toBe(1);
expect(mockChallengeStockfish).toHaveBeenCalledWith(1);
});
it("passes level 1 through unchanged", async () => {
mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE);
await POST(makeRequest({ level: 1 }));
expect(mockChallengeStockfish).toHaveBeenCalledWith(1);
});
it("passes level 8 through unchanged", async () => {
mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE);
await POST(makeRequest({ level: 8 }));
expect(mockChallengeStockfish).toHaveBeenCalledWith(8);
});
});