Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
135 lines
5.9 KiB
TypeScript
135 lines
5.9 KiB
TypeScript
// @vitest-environment jsdom
|
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
|
import { apiGet, apiPost, apiPut, apiDelete, ApiError } from "./clientApi";
|
|
|
|
function jsonResponse(body: unknown, status: number): Response {
|
|
return new Response(JSON.stringify(body), {
|
|
status,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
}
|
|
|
|
describe("clientApi", () => {
|
|
const originalFetch = global.fetch;
|
|
const originalAssign = window.location.assign;
|
|
|
|
beforeEach(() => {
|
|
global.fetch = vi.fn();
|
|
// jsdom's window.location.assign is unimplemented navigation; stub it so the
|
|
// 401 redirect path is observable instead of throwing "Not implemented".
|
|
Object.defineProperty(window, "location", {
|
|
value: { ...window.location, assign: vi.fn() },
|
|
writable: true,
|
|
});
|
|
});
|
|
|
|
afterEach(() => {
|
|
global.fetch = originalFetch;
|
|
Object.defineProperty(window, "location", { value: { ...window.location, assign: originalAssign }, writable: true });
|
|
});
|
|
|
|
it("apiGet resolves the parsed JSON body on success", async () => {
|
|
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue(jsonResponse({ name: "Admin" }, 200));
|
|
await expect(apiGet<{ name: string }>("/api/auth/session")).resolves.toEqual({ name: "Admin" });
|
|
});
|
|
|
|
it("apiPost sends a JSON body and Content-Type header", async () => {
|
|
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue(jsonResponse({ ok: true }, 200));
|
|
await apiPost("/api/auth/login", { username: "a", password: "b" });
|
|
expect(global.fetch).toHaveBeenCalledWith(
|
|
"/api/auth/login",
|
|
expect.objectContaining({
|
|
method: "POST",
|
|
body: JSON.stringify({ username: "a", password: "b" }),
|
|
headers: expect.objectContaining({ "Content-Type": "application/json" }),
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("apiPut passes caller-provided headers alongside Content-Type", async () => {
|
|
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue(jsonResponse({ ok: true }, 200));
|
|
await apiPut("/api/roles/4/modules", { moduleIds: [40800000] }, { "X-Trace-Id": "abc" });
|
|
expect(global.fetch).toHaveBeenCalledWith(
|
|
"/api/roles/4/modules",
|
|
expect.objectContaining({
|
|
method: "PUT",
|
|
body: JSON.stringify({ moduleIds: [40800000] }),
|
|
headers: expect.objectContaining({ "Content-Type": "application/json", "X-Trace-Id": "abc" }),
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("apiDelete sends a DELETE with no body (module-tree delete)", async () => {
|
|
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue(new Response(null, { status: 204 }));
|
|
await apiDelete("/api/modules/41800000");
|
|
expect(global.fetch).toHaveBeenCalledWith(
|
|
"/api/modules/41800000",
|
|
expect.objectContaining({
|
|
method: "DELETE",
|
|
headers: expect.not.objectContaining({ "Content-Type": "application/json" }),
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("throws ApiError with the server's message on failure", async () => {
|
|
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue(
|
|
jsonResponse({ error: "Invalid username or password" }, 400),
|
|
);
|
|
await expect(apiGet("/api/members")).rejects.toMatchObject({
|
|
message: "Invalid username or password",
|
|
status: 400,
|
|
});
|
|
});
|
|
|
|
// Ruling R3: an authenticated client call that gets a 401 (expired/absent
|
|
// session, e.g. a cookie that decodes but whose token the mobile-api has
|
|
// since rejected) must bounce the browser to /login, not just reject.
|
|
it("redirects to /login on a 401 response", async () => {
|
|
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue(jsonResponse({ error: "Not authenticated" }, 401));
|
|
await expect(apiGet("/api/members")).rejects.toBeInstanceOf(ApiError);
|
|
expect(window.location.assign).toHaveBeenCalledWith("/login");
|
|
});
|
|
|
|
it("redirects to /reset-password on 403 PASSWORD_RESET_REQUIRED", async () => {
|
|
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue(
|
|
jsonResponse({ error: "PASSWORD_RESET_REQUIRED", code: "PASSWORD_RESET_REQUIRED" }, 403),
|
|
);
|
|
await expect(apiGet("/api/members")).rejects.toBeInstanceOf(ApiError);
|
|
expect(window.location.assign).toHaveBeenCalledWith("/reset-password");
|
|
});
|
|
|
|
it("does not redirect on other 403s", async () => {
|
|
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue(jsonResponse({ error: "Forbidden" }, 403));
|
|
await expect(apiGet("/api/members")).rejects.toBeInstanceOf(ApiError);
|
|
expect(window.location.assign).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("a 401 from the login call shows its message instead of redirecting", async () => {
|
|
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue(
|
|
jsonResponse({ error: "This account is disabled. Contact your administrator." }, 401),
|
|
);
|
|
await expect(apiPost("/api/auth/login", { username: "u", password: "p" })).rejects.toMatchObject({
|
|
message: "This account is disabled. Contact your administrator.",
|
|
status: 401,
|
|
});
|
|
expect(window.location.assign).not.toHaveBeenCalled();
|
|
});
|
|
|
|
// unify-admin-listing-toolbar: a request that never reaches the server (offline, connection reset)
|
|
// used to surface the browser's raw "Failed to fetch".
|
|
it("throws a readable ApiError with status 0 when the request cannot reach the server", async () => {
|
|
(global.fetch as ReturnType<typeof vi.fn>).mockRejectedValue(new TypeError("Failed to fetch"));
|
|
const err = await apiGet("/api/admin/event-summary/7").catch((e: unknown) => e);
|
|
expect(err).toBeInstanceOf(ApiError);
|
|
expect((err as ApiError).message).toBe("Couldn't reach the server. Check your connection and retry.");
|
|
expect((err as ApiError).status).toBe(0);
|
|
expect(window.location.assign).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not swallow an abort", async () => {
|
|
const abort = new DOMException("The operation was aborted.", "AbortError");
|
|
(global.fetch as ReturnType<typeof vi.fn>).mockRejectedValue(abort);
|
|
await expect(apiGet("/api/x")).rejects.toBe(abort);
|
|
});
|
|
});
|