RotNot / src /lib /__tests__ /api-error.test.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
8.44 kB
import { describe, it, expect, vi } from "vitest";
import { NextRequest, NextResponse } from "next/server";
import { ApiError, withApiError } from "../api-error";
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function makeRequest(path = "/api/test"): NextRequest {
return new NextRequest(`http://localhost${path}`);
}
async function parseJson(response: NextResponse): Promise<unknown> {
return response.json();
}
// ---------------------------------------------------------------------------
// ApiError class
// ---------------------------------------------------------------------------
describe("ApiError", () => {
it("is an instance of Error", () => {
const err = new ApiError(400, "Bad request");
expect(err).toBeInstanceOf(Error);
});
it("stores statusCode and message", () => {
const err = new ApiError(404, "Not found");
expect(err.statusCode).toBe(404);
expect(err.message).toBe("Not found");
});
it("sets name to 'ApiError'", () => {
const err = new ApiError(500, "Server error");
expect(err.name).toBe("ApiError");
});
it("has a stack trace", () => {
const err = new ApiError(422, "Validation failed");
expect(err.stack).toBeDefined();
expect(err.stack).toContain("ApiError");
});
it("statusCode is readonly", () => {
const err = new ApiError(403, "Forbidden");
// TypeScript enforces readonly at compile time; at runtime we verify the value persists
expect(err.statusCode).toBe(403);
});
});
// ---------------------------------------------------------------------------
// withApiError β€” successful handler passthrough
// ---------------------------------------------------------------------------
describe("withApiError β€” success", () => {
it("returns the handler's response when no error is thrown", async () => {
const handler = vi.fn(async () =>
NextResponse.json({ ok: true }, { status: 200 })
);
const wrapped = withApiError(handler);
const req = makeRequest();
const res = await wrapped(req);
expect(handler).toHaveBeenCalledOnce();
expect(res.status).toBe(200);
expect(await parseJson(res)).toEqual({ ok: true });
});
it("passes request and context through to the handler", async () => {
const handler = vi.fn(async () => NextResponse.json({}));
const ctx = { params: { id: "42" } };
const wrapped = withApiError(handler);
await wrapped(makeRequest(), ctx);
expect(handler).toHaveBeenCalledWith(expect.any(NextRequest), ctx);
});
it("works with synchronous handlers (returning NextResponse, not Promise)", async () => {
const handler = vi.fn(() => NextResponse.json({ sync: true }));
const wrapped = withApiError(handler);
const res = await wrapped(makeRequest());
expect(res.status).toBe(200);
expect(await parseJson(res)).toEqual({ sync: true });
});
});
// ---------------------------------------------------------------------------
// withApiError β€” ApiError handling
// ---------------------------------------------------------------------------
describe("withApiError β€” ApiError", () => {
it("returns the correct status code for a 400 ApiError", async () => {
const handler = async () => {
throw new ApiError(400, "Missing field");
};
const wrapped = withApiError(handler);
const res = await wrapped(makeRequest("/api/foo"));
expect(res.status).toBe(400);
const body = (await parseJson(res)) as { error: string; status: number };
expect(body.error).toBe("Missing field");
expect(body.status).toBe(400);
});
it("returns the correct status code for a 404 ApiError", async () => {
const handler = async () => {
throw new ApiError(404, "Not found");
};
const wrapped = withApiError(handler);
const res = await wrapped(makeRequest());
expect(res.status).toBe(404);
const body = (await parseJson(res)) as { error: string; status: number };
expect(body.error).toBe("Not found");
expect(body.status).toBe(404);
});
it("returns the correct status code for a 422 ApiError", async () => {
const handler = async () => {
throw new ApiError(422, "Validation failed");
};
const wrapped = withApiError(handler);
const res = await wrapped(makeRequest());
expect(res.status).toBe(422);
});
it("logs to console.error with status code and path", async () => {
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
const handler = async () => {
throw new ApiError(403, "Forbidden");
};
const wrapped = withApiError(handler);
await wrapped(makeRequest("/api/secret"));
expect(spy).toHaveBeenCalledOnce();
expect(spy.mock.calls[0][0]).toContain("[API 403]");
expect(spy.mock.calls[0][0]).toContain("/api/secret");
expect(spy.mock.calls[0][0]).toContain("Forbidden");
spy.mockRestore();
});
});
// ---------------------------------------------------------------------------
// withApiError β€” generic Error handling
// ---------------------------------------------------------------------------
describe("withApiError β€” generic Error", () => {
it("returns 500 for a generic Error", async () => {
const handler = async () => {
throw new Error("Something broke");
};
const wrapped = withApiError(handler);
const res = await wrapped(makeRequest());
expect(res.status).toBe(500);
const body = (await parseJson(res)) as { error: string; status: number };
expect(body.error).toBe("Internal server error");
expect(body.status).toBe(500);
});
it("does not leak the actual error message in the response body", async () => {
const handler = async () => {
throw new Error("Database password is hunter2");
};
const wrapped = withApiError(handler);
const res = await wrapped(makeRequest());
const body = (await parseJson(res)) as { error: string };
expect(body.error).toBe("Internal server error");
expect(body.error).not.toContain("hunter2");
});
it("logs the error message and stack to console.error", async () => {
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
const handler = async () => {
throw new Error("Detailed failure reason");
};
const wrapped = withApiError(handler);
await wrapped(makeRequest("/api/broken"));
expect(spy).toHaveBeenCalledOnce();
expect(spy.mock.calls[0][0]).toContain("[API 500]");
expect(spy.mock.calls[0][0]).toContain("/api/broken");
expect(spy.mock.calls[0][0]).toContain("Detailed failure reason");
// Second argument is the stack trace
expect(spy.mock.calls[0][1]).toContain("Error");
spy.mockRestore();
});
});
// ---------------------------------------------------------------------------
// withApiError β€” non-Error throws
// ---------------------------------------------------------------------------
describe("withApiError β€” non-Error throws", () => {
it("handles a thrown string", async () => {
const handler = async () => {
throw "string error";
};
const wrapped = withApiError(handler);
const res = await wrapped(makeRequest());
expect(res.status).toBe(500);
const body = (await parseJson(res)) as { error: string };
expect(body.error).toBe("Internal server error");
});
it("handles a thrown number", async () => {
const handler = async () => {
throw 42;
};
const wrapped = withApiError(handler);
const res = await wrapped(makeRequest());
expect(res.status).toBe(500);
});
it("handles a thrown null", async () => {
const handler = async () => {
throw null;
};
const wrapped = withApiError(handler);
const res = await wrapped(makeRequest());
expect(res.status).toBe(500);
});
it("logs the stringified value for non-Error throws", async () => {
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
const handler = async () => {
throw "oops";
};
const wrapped = withApiError(handler);
await wrapped(makeRequest("/api/thing"));
expect(spy).toHaveBeenCalledOnce();
expect(spy.mock.calls[0][0]).toContain("oops");
// No stack for non-Error β€” second arg should be empty string
expect(spy.mock.calls[0][1]).toBe("");
spy.mockRestore();
});
});