Files
co-lite/solvway-customer-portal/app/checkin/page.test.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
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
2026-11-26 15:55:45 +08:00

518 lines
21 KiB
TypeScript

import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach } from "vitest";
// ── Module mocks (hoisted before any imports) ─────────────────────────────────
vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), push: vi.fn() }) }));
// Mutable member state so individual tests can supply a real member.
const memberMockState: {
member: { memberCode: string; name: string; initials: string; phone: string } | null;
} = { member: null };
vi.mock("@/app/lib/MemberContext", () => ({
useMember: () => ({ member: memberMockState.member, loading: false, refresh: vi.fn() }),
}));
vi.mock("@/app/lib/ThemeContext", () => ({
useTheme: () => ({ isDark: false, toggle: vi.fn() }),
}));
vi.mock("@/app/lib/clientApi", () => ({
apiGet: vi.fn(),
apiPost: vi.fn(),
apiPut: vi.fn(),
ApiError: class ApiError extends Error {
status: number;
constructor(message: string, status: number) {
super(message);
this.name = "ApiError";
this.status = status;
}
},
}));
// ── html5-qrcode mock ─────────────────────────────────────────────────────────
// The factory reads from a mutable state object at call time so tests can
// swap the `startImpl` function between test cases via beforeEach.
//
// Most tests only ever construct a single Html5Qrcode instance and are happy
// sharing the top-level `startImpl`/`stopImpl`. Tests that need to control two
// (or more) *distinct* instances independently — e.g. to simulate a stale,
// superseded scan attempt racing a newer one — can push per-instance
// overrides onto `instanceQueue`; each `new Html5Qrcode(...)` call shifts one
// off the queue and uses it instead of the shared defaults.
type StartFn = (
config: unknown,
opts: unknown,
onSuccess: (text: string) => void
) => Promise<void>;
type StopFn = () => Promise<void>;
const qrMockState: {
lastOnSuccess: ((text: string) => void) | null;
startImpl: StartFn;
stopImpl: StopFn;
instanceQueue: Array<{ startImpl?: StartFn; stopImpl?: StopFn }>;
} = {
lastOnSuccess: null,
startImpl: (_config, _opts, onSuccess) => {
qrMockState.lastOnSuccess = onSuccess;
return Promise.resolve();
},
stopImpl: () => Promise.resolve(),
instanceQueue: [],
};
vi.mock("html5-qrcode", () => {
class Html5Qrcode {
private readonly override = qrMockState.instanceQueue.shift();
start(
config: unknown,
opts: unknown,
onSuccess: (text: string) => void
): Promise<void> {
const impl = this.override?.startImpl ?? qrMockState.startImpl;
return impl(config, opts, onSuccess);
}
stop(): Promise<void> {
const impl = this.override?.stopImpl ?? qrMockState.stopImpl;
return impl();
}
}
return { Html5Qrcode };
});
// ── Import page AFTER mocks are set up ───────────────────────────────────────
import CheckInPage from "./page";
import { apiGet, apiPost } from "@/app/lib/clientApi";
// ─────────────────────────────────────────────────────────────────────────────
beforeEach(() => {
qrMockState.lastOnSuccess = null;
// Reset to default (success) start implementation
qrMockState.startImpl = (_config, _opts, onSuccess) => {
qrMockState.lastOnSuccess = onSuccess;
return Promise.resolve();
};
qrMockState.stopImpl = () => Promise.resolve();
qrMockState.instanceQueue = [];
vi.mocked(apiPost).mockReset();
memberMockState.member = null;
vi.mocked(apiGet).mockReset();
// Default: both points endpoints resolve empty so the Badge mount fetch never throws.
vi.mocked(apiGet).mockResolvedValue({} as never);
// jsdom: ensure window.isSecureContext is truthy so camera path runs
Object.defineProperty(window, "isSecureContext", { value: true, configurable: true });
});
// ─────────────────────────────────────────────────────────────────────────────
/** The Scan tab auto-starts capture on mount; wait until the scanner is live
* (its onSuccess callback has been captured). */
async function waitForAutoScan() {
await waitFor(() => expect(qrMockState.lastOnSuccess).not.toBeNull(), { timeout: 3000 });
}
/** Switch to the "My Badge" tab. */
function goToBadge() {
fireEvent.click(screen.getByRole("button", { name: /my badge/i }));
}
// ─────────────────────────────────────────────────────────────────────────────
describe("CheckInPage — Scan QR tab", () => {
it("0. auto-starts the camera on the Scan tab without a Tap-to-Scan button", async () => {
render(<CheckInPage />);
// Capture begins automatically — the scanner goes live on its own.
await waitForAutoScan();
// The old explicit-start CTA is gone.
expect(screen.queryByRole("button", { name: /tap to scan/i })).not.toBeInTheDocument();
});
it("0b. does not auto-start in an insecure context; shows the secure-connection message", async () => {
Object.defineProperty(window, "isSecureContext", { value: false, configurable: true });
const startSpy = vi.fn((_c: unknown, _o: unknown, onSuccess: (t: string) => void) => {
qrMockState.lastOnSuccess = onSuccess;
return Promise.resolve();
});
qrMockState.startImpl = startSpy;
render(<CheckInPage />);
await waitFor(() =>
expect(screen.getByText(/secure \(https\) connection/i)).toBeInTheDocument(),
);
// Camera capture was never attempted.
expect(startSpy).not.toHaveBeenCalled();
expect(qrMockState.lastOnSuccess).toBeNull();
});
it("1. decode → verifying → CHECKED_IN shows success UI and calls apiPost correctly", async () => {
vi.mocked(apiPost).mockResolvedValueOnce({ status: "CHECKED_IN", eventName: "Food Fest X" });
render(<CheckInPage />);
// Scan QR tab is active by default and auto-starts.
await waitForAutoScan();
// Simulate a QR code decode
qrMockState.lastOnSuccess!("FAKE_QR_TEXT");
await waitFor(() =>
expect(screen.getByText(/checked in!/i)).toBeInTheDocument(),
{ timeout: 3000 }
);
expect(apiPost).toHaveBeenCalledWith("/api/event/check-in", { qrText: "FAKE_QR_TEXT" });
// Check-In Confirmed button should also appear
expect(screen.getByRole("button", { name: /check-in confirmed/i })).toBeInTheDocument();
});
it("1c. decode → ALREADY_CHECKED_IN shows a distinct, non-error already-checked-in state", async () => {
vi.mocked(apiPost).mockResolvedValueOnce({ status: "ALREADY_CHECKED_IN", eventName: "Food Fest X" });
render(<CheckInPage />);
await waitForAutoScan();
qrMockState.lastOnSuccess!("FAKE_QR_TEXT");
// A distinct "already checked in" message is shown...
const already = await screen.findAllByText(/already checked in/i);
expect(already.length).toBeGreaterThanOrEqual(1);
// ...and it is NOT presented as an error to retry.
expect(screen.queryByText(/couldn't be completed/i)).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: /scan again/i })).not.toBeInTheDocument();
});
it("2. decode → WRONG_QR_TYPE shows 'not a check-in code' and a Scan again affordance", async () => {
vi.mocked(apiPost).mockResolvedValueOnce({ status: "WRONG_QR_TYPE" });
render(<CheckInPage />);
await waitForAutoScan();
qrMockState.lastOnSuccess!("WRONG_QR_TEXT");
await waitFor(() =>
expect(screen.getByText(/that's not a check-in code/i)).toBeInTheDocument(),
{ timeout: 3000 }
);
expect(screen.getByRole("button", { name: /scan again/i })).toBeInTheDocument();
});
it("2b. a merchant payment (PT) QR goes to check-in and is rejected as the wrong QR type", async () => {
// Scan-to-pay was removed: a PT code is no longer dispatched to a payment screen.
vi.mocked(apiPost).mockResolvedValueOnce({ status: "WRONG_QR_TYPE" });
render(<CheckInPage />);
await waitForAutoScan();
qrMockState.lastOnSuccess!("PT:merchant-wallet-qr");
await waitFor(() =>
expect(screen.getByText(/that's not a check-in code/i)).toBeInTheDocument(),
{ timeout: 3000 }
);
expect(apiPost).toHaveBeenCalledWith("/api/event/check-in", { qrText: "PT:merchant-wallet-qr" });
expect(apiPost).toHaveBeenCalledTimes(1);
expect(screen.getByRole("button", { name: /scan again/i })).toBeInTheDocument();
});
it("3. permission denied → shows camera-unavailable message, My Badge hint, and a retry", async () => {
// Override startImpl to reject (simulates permission-denied)
qrMockState.startImpl = () => Promise.reject(new Error("Permission denied"));
render(<CheckInPage />);
// Auto-start attempts capture, which fails.
await waitFor(
() =>
expect(
screen.getByText(/camera unavailable/i)
).toBeInTheDocument(),
{ timeout: 3000 }
);
// Should render the inline fallback hint specific to camera_error state.
// This text only appears in the camera_error/insecure overlay, not in the tab label.
expect(screen.getByText(/use your/i, { exact: false })).toBeInTheDocument();
expect(screen.getByText(/my badge/i, { selector: "strong" })).toBeInTheDocument();
// A manual retry remains available after a camera failure.
expect(screen.getByRole("button", { name: /scan again/i })).toBeInTheDocument();
});
it("4. switching to My Badge while verifying resets the scan tab and auto-restarts on return (no frozen spinner)", async () => {
// Never-resolving apiPost keeps the component in `verifying` state
vi.mocked(apiPost).mockReturnValue(new Promise(() => { /* never resolves */ }));
render(<CheckInPage />);
await waitForAutoScan();
// Trigger a QR decode — this moves state to verifying (apiPost is pending)
qrMockState.lastOnSuccess!("SOME_QR_TEXT");
// Wait until the verifying spinner appears
await waitFor(
() => expect(screen.getByText(/verifying/i)).toBeInTheDocument(),
{ timeout: 3000 }
);
// Switch to My Badge tab while still verifying
fireEvent.click(screen.getByRole("button", { name: /my badge/i }));
await waitFor(() => expect(screen.getByRole("button", { name: /copy/i })).toBeInTheDocument());
// Watch for a fresh auto-start when we return.
qrMockState.lastOnSuccess = null;
// Switch back to Scan QR tab — an idle scan tab auto-restarts capture.
fireEvent.click(screen.getByRole("button", { name: /scan qr/i }));
// Recovery: the camera restarts on its own (no frozen verifying spinner).
await waitFor(() => expect(qrMockState.lastOnSuccess).not.toBeNull(), { timeout: 3000 });
});
it("5. leaving the Scan tab while the camera is still starting stops the stream and never reaches 'scanning' (regression)", async () => {
// Control exactly when scanner.start() resolves so we can leave mid-flight.
let resolveStart: () => void = () => {};
const startPromise = new Promise<void>((resolve) => {
resolveStart = resolve;
});
const stopSpy = vi.fn(() => Promise.resolve());
qrMockState.startImpl = (_config, _opts, onSuccess) => {
qrMockState.lastOnSuccess = onSuccess;
return startPromise;
};
qrMockState.stopImpl = stopSpy;
render(<CheckInPage />);
// Auto-start puts us in the "starting" state (start() has not resolved yet).
await waitFor(() => expect(screen.getByText(/starting camera/i)).toBeInTheDocument());
// Leave the Scan tab while the start() call is still in flight.
const badgeTab = screen.getByRole("button", { name: /my badge/i });
fireEvent.click(badgeTab);
// Now let the pending scanner.start() resolve — the camera "opens" only after
// the user has already left.
resolveStart();
// The just-opened stream must be stopped...
await waitFor(() => expect(stopSpy).toHaveBeenCalled());
// ...and the UI must never have advanced to (or remained stuck in) a live
// scanning state: no live camera mount point, and no "Scanning…" button label.
await waitFor(() => {
expect(document.getElementById("checkin-reader")).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: /scanning…/i })).not.toBeInTheDocument();
});
// We should be on the Badge tab now (navigation was not blocked/reverted).
expect(screen.getByRole("button", { name: /copy/i })).toBeInTheDocument();
});
it("6. a stale start() resolving after the user left mid-'starting' stops its own stream and lets a clean auto-restart proceed on return (regression)", async () => {
// Attempt #1 (auto-start on mount): resolves late, after we've left.
let resolveStart: () => void = () => {};
const startPromise = new Promise<void>((resolve) => {
resolveStart = resolve;
});
const stopSpy = vi.fn(() => Promise.resolve());
qrMockState.instanceQueue.push({ startImpl: () => startPromise, stopImpl: stopSpy });
// Attempt #2 (auto-restart on return) uses the default (resolving) startImpl.
render(<CheckInPage />);
await waitFor(() => expect(screen.getByText(/starting camera/i)).toBeInTheDocument());
// Leave the Scan tab while attempt #1's start() is still pending.
fireEvent.click(screen.getByRole("button", { name: /my badge/i }));
await waitFor(() => expect(screen.getByRole("button", { name: /copy/i })).toBeInTheDocument());
// The stale attempt #1 now resolves while we're away — it must stop itself.
resolveStart();
await waitFor(() => expect(stopSpy).toHaveBeenCalled());
// Watch for the fresh auto-restart.
qrMockState.lastOnSuccess = null;
// Come back to the Scan tab — a clean attempt #2 auto-starts and goes live,
// unaffected by the stale attempt #1.
fireEvent.click(screen.getByRole("button", { name: /scan qr/i }));
await waitFor(() => expect(qrMockState.lastOnSuccess).not.toBeNull(), { timeout: 3000 });
});
it("7. a stale, superseded scan attempt's start() cannot clobber a newer attempt into 'scanning' (generation-counter regression)", async () => {
// Attempt #1 (auto-start on mount): its start() resolves late, after attempt
// #2 has begun.
let resolveStart1: () => void = () => {};
const start1Promise = new Promise<void>((resolve) => {
resolveStart1 = resolve;
});
const stop1Spy = vi.fn(() => Promise.resolve());
qrMockState.instanceQueue.push({ startImpl: () => start1Promise, stopImpl: stop1Spy });
// Attempt #2 (auto-restart on returning to Scan): its start() stays pending
// throughout this test.
const start2Promise = new Promise<void>(() => { /* never resolves in this test */ });
const stop2Spy = vi.fn(() => Promise.resolve());
qrMockState.instanceQueue.push({ startImpl: () => start2Promise, stopImpl: stop2Spy });
render(<CheckInPage />);
// Attempt #1 begins on mount; its start() is in flight.
await waitFor(() => expect(screen.getByText(/starting camera/i)).toBeInTheDocument());
// Leave Scan while attempt #1 is still starting. handleTabSwitch is async
// (it awaits stopCamera() before flipping `view`), so wait for the Badge
// tab to actually render before switching back.
fireEvent.click(screen.getByRole("button", { name: /my badge/i }));
await waitFor(() => expect(screen.getByRole("button", { name: /copy/i })).toBeInTheDocument());
// Return to Scan — an idle scan tab auto-starts a fresh attempt (#2).
fireEvent.click(screen.getByRole("button", { name: /scan qr/i }));
await waitFor(() => expect(screen.getByText(/starting camera/i)).toBeInTheDocument());
// Now the STALE attempt #1's start() resolves.
resolveStart1();
// Attempt #1's own scanner must be stopped...
await waitFor(() => expect(stop1Spy).toHaveBeenCalled());
// ...but it must NOT drive the UI into "scanning" on behalf of attempt #2,
// which is still awaiting its own start(). The machine should still
// reflect attempt #2's in-flight "starting" state, and attempt #2's
// scanner must be untouched.
expect(screen.getByText(/starting camera/i)).toBeInTheDocument();
expect(stop2Spy).not.toHaveBeenCalled();
});
it("8. releases the camera stream when start() opens it then fails (no leaked track)", async () => {
// Reproduce the html5-qrcode leak: start() opens the camera via getUserMedia,
// then its render step fails (as when the reader element unmounts mid-start).
// The library rejects without stopping the track, so the page must stop it.
const track = { stop: vi.fn() };
const stream = { getTracks: () => [track] } as unknown as MediaStream;
const gum = vi.fn().mockResolvedValue(stream);
const originalMediaDevices = Object.getOwnPropertyDescriptor(navigator, "mediaDevices");
Object.defineProperty(navigator, "mediaDevices", {
value: { getUserMedia: gum },
configurable: true,
});
qrMockState.startImpl = async () => {
await navigator.mediaDevices.getUserMedia({ video: true });
const err = new Error("Could not start video source");
err.name = "NotReadableError";
throw err;
};
try {
render(<CheckInPage />);
// The opened camera track MUST be stopped even though html5-qrcode did not.
await waitFor(() => expect(track.stop).toHaveBeenCalled(), { timeout: 3000 });
} finally {
if (originalMediaDevices) {
Object.defineProperty(navigator, "mediaDevices", originalMediaDevices);
} else {
Reflect.deleteProperty(navigator, "mediaDevices");
}
}
});
});
// ─────────────────────────────────────────────────────────────────────────────
describe("CheckInPage — My Badge tab", () => {
it("1. shows the real member name from useMember(), not a mock", async () => {
memberMockState.member = { memberCode: "MC-90210", name: "Jordan Tan", initials: "JT", phone: "+60 12-000 0000" };
render(<CheckInPage />);
goToBadge();
expect(await screen.findByText("Jordan Tan")).toBeInTheDocument();
// The old hardcoded mock name must not appear.
expect(screen.queryByText("Alex Lim")).not.toBeInTheDocument();
});
it("2. shows the fetched loyalty balance and earned-today", async () => {
memberMockState.member = { memberCode: "MC-1", name: "A B", initials: "AB", phone: "" };
vi.mocked(apiGet).mockImplementation((url: string) =>
url.includes("balance")
? Promise.resolve({ balance: 3450 } as never)
: Promise.resolve({ earnedToday: 275 } as never)
);
render(<CheckInPage />);
goToBadge();
expect(await screen.findByText(/3,450/)).toBeInTheDocument();
expect(await screen.findByText(/275/)).toBeInTheDocument();
});
it("3. points value comes from the API, not the MEMBER mock (1,200)", async () => {
memberMockState.member = { memberCode: "MC-1", name: "A B", initials: "AB", phone: "" };
vi.mocked(apiGet).mockImplementation((url: string) =>
url.includes("balance")
? Promise.resolve({ balance: 3450 } as never)
: Promise.resolve({ earnedToday: 275 } as never)
);
render(<CheckInPage />);
goToBadge();
await screen.findByText(/3,450/);
expect(screen.queryByText(/1,200/)).not.toBeInTheDocument();
});
it("3b. renders the member name uppercased on the badge (display only)", async () => {
memberMockState.member = { memberCode: "MC-1", name: "Jordan Tan", initials: "JT", phone: "" };
render(<CheckInPage />);
goToBadge();
const name = await screen.findByText("Jordan Tan");
expect(name).toHaveClass("uppercase");
expect(name.textContent).toBe("Jordan Tan");
});
it("4. renders no member-tier UI and no @handle", async () => {
memberMockState.member = { memberCode: "MC-1", name: "A B", initials: "AB", phone: "" };
render(<CheckInPage />);
goToBadge();
await screen.findByText("A B"); // badge tab is rendered
expect(screen.queryAllByText(/member tier/i)).toHaveLength(0);
expect(screen.queryAllByText(/gold/i)).toHaveLength(0);
expect(screen.queryAllByText(/to platinum/i)).toHaveLength(0);
expect(screen.queryAllByText(/@[a-z]/i)).toHaveLength(0);
});
it("5. renders without crashing when there is no member session yet", async () => {
memberMockState.member = null;
render(<CheckInPage />);
goToBadge();
// Copy affordance in the footer is a stable marker that the card rendered.
expect(await screen.findByRole("button", { name: /copy/i })).toBeInTheDocument();
});
it("6. points default to 0 when the endpoints fail", async () => {
memberMockState.member = { memberCode: "MC-1", name: "A B", initials: "AB", phone: "" };
vi.mocked(apiGet).mockRejectedValue(new Error("network"));
render(<CheckInPage />);
goToBadge();
await screen.findByText("A B");
await waitFor(() => expect(screen.getAllByText(/^0$/).length).toBeGreaterThan(0));
});
});