Files
co-lite/solvway-customer-portal/app/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

451 lines
18 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { StrictMode } from "react";
import { act, render, screen, waitFor } from "@testing-library/react";
import type { AppBanner, AppPromo, CurrentEventConfig } from "@/app/lib/types";
vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) }));
vi.mock("@/app/lib/ThemeContext", () => ({ useTheme: () => ({ isDark: false }) }));
vi.mock("@/app/lib/MemberContext", () => ({
useMember: () => ({ member: { name: "Jordan Tan", memberCode: "MC-1", phone: "0123" } }),
}));
vi.mock("@/app/lib/clientApi", () => ({ apiGet: vi.fn() }));
// HomeProfileReminder pulls in i18n + a profile fetch; irrelevant to these tests.
vi.mock("@/app/components/HomeProfileReminder", () => ({ default: () => null }));
import HomePage from "./page";
import { apiGet } from "@/app/lib/clientApi";
const mockApiGet = apiGet as unknown as ReturnType<typeof vi.fn>;
describe("HomePage — member name display", () => {
beforeEach(() => {
mockApiGet.mockReset();
mockApiGet.mockResolvedValue({} as never);
});
it("renders the member name uppercased (display only, data unchanged)", () => {
render(<HomePage />);
const name = screen.getByText("Jordan Tan");
// CSS transform: the DOM text stays original case (proving data isn't mutated),
// and the uppercase presentation is applied via the class.
expect(name).toHaveClass("uppercase");
expect(name.textContent).toBe("Jordan Tan");
});
});
function mockApis(banner: AppBanner[] | Error, promos: AppPromo[] | Error = []) {
mockApiGet.mockImplementation((path: string) => {
if (path === "/api/banner") {
return banner instanceof Error ? Promise.reject(banner) : Promise.resolve(banner);
}
if (path === "/api/promos") {
return promos instanceof Error ? Promise.reject(promos) : Promise.resolve(promos);
}
if (path === "/api/points/balance") return Promise.resolve({ balance: 0 });
if (path === "/api/points/today") return Promise.resolve({ earnedToday: 0 });
return Promise.resolve({});
});
}
describe("HomePage announcement banner", () => {
beforeEach(() => mockApiGet.mockReset());
it("renders the marquee above the Profile Card when banners are active", async () => {
mockApis([{ id: 1, message: "Grand sale this weekend", style: "PROMO", sortIndex: 0 }]);
render(<HomePage />);
const region = await screen.findByRole("region", { name: /announcement/i });
expect(region).toBeInTheDocument();
// Positioned above the Profile Card (member name node comes after the region).
const name = screen.getByText("Jordan Tan");
expect(region.compareDocumentPosition(name) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
it("renders no banner region when there are no active banners", async () => {
mockApis([]);
render(<HomePage />);
// Profile card renders...
expect(await screen.findByText("Jordan Tan")).toBeInTheDocument();
// ...but no marquee.
await waitFor(() => expect(screen.queryByRole("region", { name: /announcement/i })).toBeNull());
});
it("renders normally with no banner when the banner fetch fails", async () => {
mockApis(new Error("network"));
render(<HomePage />);
expect(await screen.findByText("Jordan Tan")).toBeInTheDocument();
await waitFor(() => expect(screen.queryByRole("region", { name: /announcement/i })).toBeNull());
});
});
describe("HomePage promo carousel", () => {
beforeEach(() => mockApiGet.mockReset());
it("renders the promo carousel below Quick Links when there are active promos", async () => {
mockApis([], [
{
id: 1,
mediaType: "IMAGE",
mediaUrl: "https://cdn.example.com/one.jpg",
altText: "Grand sale",
sortIndex: 0,
},
]);
render(<HomePage />);
const region = await screen.findByRole("region", { name: /promotions/i });
expect(region).toBeInTheDocument();
// Positioned below the Quick Links section (this quick-link label precedes the region).
const lastQuickLink = screen.getByText("Taste Rewards +");
expect(lastQuickLink.compareDocumentPosition(region) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
it("renders no promo carousel when there are no active promos", async () => {
mockApis([], []);
render(<HomePage />);
expect(await screen.findByText("Jordan Tan")).toBeInTheDocument();
await waitFor(() => expect(screen.queryByRole("region", { name: /promotions/i })).toBeNull());
});
it("renders no promo carousel when the promo fetch fails", async () => {
mockApis([], new Error("network"));
render(<HomePage />);
expect(await screen.findByText("Jordan Tan")).toBeInTheDocument();
await waitFor(() => expect(screen.queryByRole("region", { name: /promotions/i })).toBeNull());
});
});
describe("HomePage quick links (dark-mode legibility)", () => {
beforeEach(() => mockApiGet.mockReset());
it("renders the Stage Activities and Floor Plan icons in the orange accent, not the old indigo", async () => {
mockApis([]);
render(<HomePage />);
for (const label of ["Stage Activities", "Floor Plan"]) {
// The tile is a link or an inert block depending on the event; colour applies to both.
const tile = (await screen.findByText(label)).closest(".rounded-2xl");
expect(tile).not.toBeNull();
const icon = tile!.querySelector("svg");
expect(icon).not.toBeNull();
expect(icon!.style.stroke).toBe("rgb(255, 107, 0)"); // #FF6B00
expect(icon!.style.stroke).not.toBe("rgb(41, 10, 129)"); // old #290a81
}
});
});
describe("HomePage quick links", () => {
beforeEach(() => mockApiGet.mockReset());
const TILES: [RegExp, string][] = [
[/welcome gift/i, "/attendance"],
[/stage activities/i, "/stage"],
[/lucky draw/i, "/draw"],
[/floor plan/i, "/floorplan"],
[/taste rewards/i, "/store"],
];
function mockConfig(config: CurrentEventConfig | Error) {
mockApis([], []);
const base = mockApiGet.getMockImplementation() as (path: string) => Promise<unknown>;
mockApiGet.mockImplementation((path: string) => {
if (path === "/api/event/current-config") {
return config instanceof Error ? Promise.reject(config) : Promise.resolve(config);
}
return base(path);
});
}
async function expectInert(name: RegExp) {
expect(await screen.findByText(name)).toBeInTheDocument();
expect(screen.queryByRole("link", { name })).toBeNull();
}
const EVENT = { uuid: "1", name: "Expo", location: "KL" };
const PRODUCT = { uuid: "9", displayName: "Magnet", costAmount: 800 };
it("renders every tile as inert when no event is live", async () => {
mockConfig({});
render(<HomePage />);
await waitFor(() => expect(mockApiGet).toHaveBeenCalledWith("/api/event/current-config"));
await act(async () => {}); // let the config promise settle before checking
for (const [name] of TILES) await expectInert(name);
});
it("links only the tiles whose event content exists", async () => {
mockConfig({ currentEvent: EVENT, currentEventLuckyDraw: "https://img/ld.png" });
render(<HomePage />);
expect(await screen.findByRole("link", { name: /welcome gift/i })).toHaveAttribute("href", "/attendance");
expect(await screen.findByRole("link", { name: /lucky draw/i })).toHaveAttribute("href", "/draw");
await expectInert(/stage activities/i);
await expectInert(/floor plan/i);
await expectInert(/taste rewards/i);
});
it("links every tile when the event has every upload", async () => {
mockConfig({
currentEvent: EVENT,
currentEventStageActivities: "s",
currentEventLuckyDraw: "l",
currentEventFloorPlan: "f",
currentEventTasteRewards: "t",
currentEventTasteRewardsProductList: [PRODUCT],
});
render(<HomePage />);
for (const [name, href] of TILES) {
expect(await screen.findByRole("link", { name })).toHaveAttribute("href", href);
}
});
it("links Taste Rewards+ when the event has reward products but no Taste Rewards document", async () => {
mockConfig({ currentEvent: EVENT, currentEventTasteRewardsProductList: [PRODUCT] });
render(<HomePage />);
expect(await screen.findByRole("link", { name: /taste rewards/i })).toHaveAttribute("href", "/store");
});
it("keeps Taste Rewards+ inert when the event has a Taste Rewards document but no reward products", async () => {
mockConfig({ currentEvent: EVENT, currentEventTasteRewards: "t", currentEventTasteRewardsProductList: [] });
render(<HomePage />);
expect(await screen.findByRole("link", { name: /welcome gift/i })).toBeInTheDocument();
await expectInert(/taste rewards/i);
});
it("renders every tile as inert when the config request fails", async () => {
mockConfig(new Error("network"));
render(<HomePage />);
await waitFor(() => expect(mockApiGet).toHaveBeenCalledWith("/api/event/current-config"));
await act(async () => {}); // let the config promise settle before checking
for (const [name] of TILES) await expectInert(name);
});
});
describe("HomePage Highlights header", () => {
beforeEach(() => mockApiGet.mockReset());
it("shows a 'Highlights' header directly above the promo carousel when promos exist", async () => {
mockApis([], [
{ id: 1, mediaType: "IMAGE", mediaUrl: "https://cdn.example.com/one.jpg", altText: "Grand sale", sortIndex: 0 },
]);
render(<HomePage />);
const heading = await screen.findByText("Highlights");
const region = screen.getByRole("region", { name: /promotions/i });
// The header precedes the carousel in the DOM.
expect(heading.compareDocumentPosition(region) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
it("does not show the 'Highlights' header when there are no promos", async () => {
mockApis([], []);
render(<HomePage />);
expect(await screen.findByText("Jordan Tan")).toBeInTheDocument();
await waitFor(() => expect(screen.queryByText("Highlights")).toBeNull());
});
});
const { showToast } = vi.hoisted(() => ({ showToast: vi.fn() }));
vi.mock("@/app/lib/ToastContext", () => ({ useToast: () => ({ showToast }) }));
describe("HomePage profile reward pickup", () => {
let balances: number[];
let today: number;
const balanceReads = () => mockApiGet.mock.calls.filter(([p]) => p === "/api/points/balance").length;
const todayReads = () => mockApiGet.mock.calls.filter(([p]) => p === "/api/points/today").length;
// Each balance read consumes the next scripted value; the last value repeats.
const note = (balance: unknown = 100, at: unknown = Date.now()) => JSON.stringify({ balance, at });
const advance = (ms: number) => act(async () => { await vi.advanceTimersByTimeAsync(ms); });
beforeEach(() => {
vi.useFakeTimers();
sessionStorage.clear();
showToast.mockReset();
mockApiGet.mockReset();
balances = [100];
today = 0;
mockApiGet.mockImplementation((path: string) => {
if (path === "/api/points/balance") {
const b = balances.length > 1 ? balances.shift()! : balances[0];
return Promise.resolve({ balance: b });
}
if (path === "/api/points/today") return Promise.resolve({ earnedToday: today });
if (path === "/api/banner" || path === "/api/promos") return Promise.resolve([]);
return Promise.resolve({});
});
});
afterEach(() => {
vi.useRealTimers();
sessionStorage.clear();
});
it("reads the balance once and shows no toast without a baseline", async () => {
render(<HomePage />);
await advance(15000);
expect(balanceReads()).toBe(1);
expect(showToast).not.toHaveBeenCalled();
});
it("polls after a baseline, then shows the new balance, earned today and a delta toast, and stops", async () => {
sessionStorage.setItem("profileRewardBaseline", note());
balances = [100, 100, 600];
render(<HomePage />);
await advance(0);
expect(sessionStorage.getItem("profileRewardBaseline")).not.toBeNull(); // kept while polling
expect(balanceReads()).toBe(1);
await advance(1600);
expect(balanceReads()).toBe(2);
expect(showToast).not.toHaveBeenCalled();
expect(sessionStorage.getItem("profileRewardBaseline")).not.toBeNull();
today = 500;
await advance(1600);
expect(screen.getByText("600")).toBeInTheDocument();
expect(screen.getByText("+500 pts")).toBeInTheDocument();
expect(todayReads()).toBeGreaterThanOrEqual(2);
expect(showToast).toHaveBeenCalledTimes(1);
expect(showToast).toHaveBeenCalledWith("Profile updated · +500 points earned");
expect(sessionStorage.getItem("profileRewardBaseline")).toBeNull(); // removed once the reward is found
const reads = balanceReads();
await advance(15000);
expect(balanceReads()).toBe(reads);
expect(showToast).toHaveBeenCalledTimes(1);
});
it("toasts the actual delta, not a constant", async () => {
sessionStorage.setItem("profileRewardBaseline", note());
balances = [100, 350];
render(<HomePage />);
await advance(3200);
expect(showToast).toHaveBeenCalledWith("Profile updated · +250 points earned");
});
it("polls until the note's deadline (at + 12s), then gives up with no toast", async () => {
sessionStorage.setItem("profileRewardBaseline", note());
render(<HomePage />);
await advance(0);
await advance(1600);
expect(balanceReads()).toBe(2); // polling is active at all
await advance(10000); // 11.6s since the note was written
expect(sessionStorage.getItem("profileRewardBaseline")).not.toBeNull(); // still before at + 12s
await advance(1000); // 12.6s
expect(sessionStorage.getItem("profileRewardBaseline")).toBeNull(); // removed on give-up
const reads = balanceReads();
await advance(12000);
expect(balanceReads()).toBe(reads);
expect(showToast).not.toHaveBeenCalled();
});
it("ignores an expired note (at = now - 20s): key removed at once, one read, no toast", async () => {
sessionStorage.setItem("profileRewardBaseline", note(100, Date.now() - 20000));
balances = [100];
render(<HomePage />);
await advance(0);
expect(sessionStorage.getItem("profileRewardBaseline")).toBeNull();
await advance(15000);
expect(balanceReads()).toBe(1);
expect(showToast).not.toHaveBeenCalled();
});
it("retries after a rejected balance read while the note is valid, then toasts", async () => {
sessionStorage.setItem("profileRewardBaseline", note());
let n = 0;
mockApiGet.mockImplementation((path: string) => {
if (path === "/api/points/balance") return ++n === 1 ? Promise.reject(new Error("down")) : Promise.resolve({ balance: 600 });
if (path === "/api/points/today") return Promise.resolve({ earnedToday: 500 });
if (path === "/api/banner" || path === "/api/promos") return Promise.resolve([]);
return Promise.resolve({});
});
render(<HomePage />);
await advance(0);
expect(balanceReads()).toBe(1);
expect(showToast).not.toHaveBeenCalled();
await advance(1600);
expect(balanceReads()).toBe(2);
expect(showToast).toHaveBeenCalledTimes(1);
expect(showToast).toHaveBeenCalledWith("Profile updated · +500 points earned");
expect(sessionStorage.getItem("profileRewardBaseline")).toBeNull();
await advance(15000);
expect(balanceReads()).toBe(2);
});
it("toasts at once and does not poll when the first read is already above the baseline", async () => {
sessionStorage.setItem("profileRewardBaseline", note());
balances = [600];
render(<HomePage />);
await advance(0);
expect(showToast).toHaveBeenCalledWith("Profile updated · +500 points earned");
expect(sessionStorage.getItem("profileRewardBaseline")).toBeNull();
const reads = balanceReads();
await advance(15000);
expect(balanceReads()).toBe(reads);
expect(showToast).toHaveBeenCalledTimes(1);
});
it.each([
["plain number", "100"],
["not JSON", "abc"],
["string balance", '{"balance":"x","at":1}'],
["non-finite at", '{"balance":100,"at":null}'],
])("ignores a malformed note (%s): key removed, one read, no toast", async (_n, bad) => {
sessionStorage.setItem("profileRewardBaseline", bad);
balances = [600];
render(<HomePage />);
await advance(0);
expect(sessionStorage.getItem("profileRewardBaseline")).toBeNull();
await advance(15000);
expect(balanceReads()).toBe(1);
expect(showToast).not.toHaveBeenCalled();
});
it("still shows the reward under StrictMode's double mount, once, and clears the key", async () => {
sessionStorage.setItem("profileRewardBaseline", note());
balances = [100, 100, 600];
render(<StrictMode><HomePage /></StrictMode>);
await advance(6000);
expect(showToast).toHaveBeenCalledTimes(1);
expect(showToast).toHaveBeenCalledWith("Profile updated · +500 points earned");
expect(sessionStorage.getItem("profileRewardBaseline")).toBeNull();
});
it("stops polling on unmount", async () => {
sessionStorage.setItem("profileRewardBaseline", note());
const { unmount } = render(<HomePage />);
await advance(1600);
expect(balanceReads()).toBe(2); // polling is active before unmount
unmount();
const reads = balanceReads();
await advance(15000);
expect(balanceReads()).toBe(reads);
});
it("shows the unchanged balance during the check instead of 0", async () => {
sessionStorage.setItem("profileRewardBaseline", note());
balances = [100];
render(<HomePage />);
await advance(0);
expect(screen.getByText("100")).toBeInTheDocument();
expect(screen.queryByText("0")).toBeNull();
});
it("keeps showing the unchanged balance after the deadline gives up, with no toast", async () => {
sessionStorage.setItem("profileRewardBaseline", note());
balances = [100];
render(<HomePage />);
await advance(13000);
expect(sessionStorage.getItem("profileRewardBaseline")).toBeNull();
expect(screen.getByText("100")).toBeInTheDocument();
expect(screen.queryByText("0")).toBeNull();
expect(showToast).not.toHaveBeenCalled();
});
});