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

1010 lines
41 KiB
TypeScript

import { render, screen, fireEvent, waitFor, within } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach } from "vitest";
// ── Module mocks (hoisted before any imports) ─────────────────────────────────
const nav = vi.hoisted(() => ({ push: vi.fn() }));
const toast = vi.hoisted(() => ({ showToast: vi.fn() }));
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: nav.push, replace: vi.fn(), back: vi.fn() }),
}));
vi.mock("@/app/lib/ToastContext", () => ({
useToast: () => ({ showToast: toast.showToast }),
}));
vi.mock("@/app/lib/ThemeContext", () => ({
useTheme: () => ({ isDark: false, toggle: vi.fn() }),
}));
vi.mock("@/app/lib/MemberContext", () => ({
useMember: () => ({ member: { name: "Alice", memberCode: "M1", phone: "0123" } }),
}));
vi.mock("@/app/lib/clientApi", () => ({
apiGet: 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;
}
},
}));
// ── Import page AFTER mocks are set up ───────────────────────────────────────
import ProfilePage from "./page";
import { apiGet, apiPut, ApiError } from "@/app/lib/clientApi";
beforeEach(() => {
nav.push.mockReset();
toast.showToast.mockReset();
vi.mocked(apiPut).mockReset();
vi.mocked(apiPut).mockResolvedValue(undefined);
vi.mocked(apiGet).mockReset();
vi.mocked(apiGet).mockImplementation((url: string) => {
if (url.includes("/api/member/profile-init")) return Promise.resolve({});
if (url.includes("/api/geo/first-level")) return Promise.resolve([]);
// /api/member/profile — includes addressLocation so a valid save can proceed
// without selecting a geo level (the first-level list is empty above).
return Promise.resolve({
name: "Alice",
surname: "Tan",
email: "alice@example.com",
dob: "1990-05-10",
gender: "F",
postCode: "12345",
addressLocation: "loc-1",
memberCode: "M1",
});
});
});
describe("ProfilePage — input focus stability", () => {
it("keeps the First Name field focused across successive keystrokes", async () => {
render(<ProfilePage />);
// Wait for the profile to load and the form to render.
const first = (await screen.findByPlaceholderText(
"Your first name",
)) as HTMLInputElement;
// Simulate the field being focused (as it is after the user taps/clicks it).
first.focus();
expect(document.activeElement).toBe(first);
// Type a character — this triggers setForm -> ProfilePage re-render.
fireEvent.change(first, { target: { value: "Alicee" } });
// Re-query: if Row/Label are re-created during render, the input is
// remounted and focus is lost. The same node must remain focused.
const firstAfter = screen.getByPlaceholderText("Your first name");
expect(firstAfter).toBe(first);
expect(document.activeElement).toBe(firstAfter);
expect((firstAfter as HTMLInputElement).value).toBe("Alicee");
});
it("keeps focus after typing in the Email field too", async () => {
render(<ProfilePage />);
const email = (await screen.findByPlaceholderText(
"you@email.com",
)) as HTMLInputElement;
email.focus();
expect(document.activeElement).toBe(email);
fireEvent.change(email, { target: { value: "alice@new.com" } });
await waitFor(() => {
const emailAfter = screen.getByPlaceholderText("you@email.com");
expect(document.activeElement).toBe(emailAfter);
});
});
});
describe("ProfilePage — member name display", () => {
it("uppercases the read-only header name but not the editable inputs or their values", async () => {
render(<ProfilePage />);
const first = (await screen.findByPlaceholderText("Your first name")) as HTMLInputElement;
// Header shows the combined name; it is uppercased for display only.
const header = screen.getByText("Alice Tan");
expect(header).toHaveClass("uppercase");
expect(header.textContent).toBe("Alice Tan");
// The editable inputs keep their original casing and are NOT uppercased.
expect(first.value).toBe("Alice");
expect(first).not.toHaveClass("uppercase");
const surname = screen.getByPlaceholderText("Your surname") as HTMLInputElement;
expect(surname.value).toBe("Tan");
expect(surname).not.toHaveClass("uppercase");
});
});
describe("ProfilePage — redirect and toast on save", () => {
it("redirects home and shows a toast after a successful save", async () => {
render(<ProfilePage />);
await screen.findByPlaceholderText("Your first name");
fireEvent.click(screen.getByText("Save Changes"));
await waitFor(() => expect(apiPut).toHaveBeenCalled());
await waitFor(() => expect(nav.push).toHaveBeenCalledWith("/"));
expect(toast.showToast).toHaveBeenCalledTimes(1);
expect(toast.showToast).toHaveBeenCalledWith(expect.stringMatching(/profile/i));
});
it("does not redirect or toast when client-side validation fails", async () => {
render(<ProfilePage />);
const first = await screen.findByPlaceholderText("Your first name");
// Clear a required field so handleSave bails before calling the API.
fireEvent.change(first, { target: { value: "" } });
fireEvent.click(screen.getByText("Save Changes"));
await screen.findByText("First name is required.");
expect(apiPut).not.toHaveBeenCalled();
expect(nav.push).not.toHaveBeenCalled();
expect(toast.showToast).not.toHaveBeenCalled();
});
it("does not redirect or toast when the save request fails", async () => {
vi.mocked(apiPut).mockRejectedValueOnce(new ApiError("Server error", 500));
render(<ProfilePage />);
await screen.findByPlaceholderText("Your first name");
fireEvent.click(screen.getByText("Save Changes"));
await screen.findByText("Server error");
expect(nav.push).not.toHaveBeenCalled();
expect(toast.showToast).not.toHaveBeenCalled();
});
});
// ── Per-field required messages ───────────────────────────────────────────────
describe("ProfilePage — per-field required messages", () => {
const OLD_MSG = "Name, surname and email are required.";
const FIRST = "First name is required.";
const SURNAME = "Surname is required.";
const EMAIL = "Email is required.";
async function loaded() {
render(<ProfilePage />);
const first = (await screen.findByPlaceholderText("Your first name")) as HTMLInputElement;
const surname = screen.getByPlaceholderText("Your surname") as HTMLInputElement;
const email = screen.getByPlaceholderText("you@email.com") as HTMLInputElement;
return { first, surname, email };
}
// Message must sit in the same row as its input, after it in DOM order.
function expectUnder(input: HTMLElement, text: string) {
const msg = screen.getByText(text);
expect(input.parentElement).toContainElement(msg);
expect(input.compareDocumentPosition(msg) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
}
it("shows only the Email message under Email when only Email is empty", async () => {
const { email } = await loaded();
fireEvent.change(email, { target: { value: "" } });
fireEvent.click(screen.getByText("Save Changes"));
await screen.findByText(EMAIL);
expectUnder(email, EMAIL);
expect(screen.queryByText(FIRST)).toBeNull();
expect(screen.queryByText(SURNAME)).toBeNull();
expect(screen.queryByText(OLD_MSG)).toBeNull();
expect(apiPut).not.toHaveBeenCalled();
});
it("treats whitespace-only values as empty", async () => {
const { email } = await loaded();
fireEvent.change(email, { target: { value: " " } });
fireEvent.click(screen.getByText("Save Changes"));
await screen.findByText(EMAIL);
expect(apiPut).not.toHaveBeenCalled();
});
it("shows Surname and Email messages, each under its own field", async () => {
const { surname, email } = await loaded();
fireEvent.change(surname, { target: { value: "" } });
fireEvent.change(email, { target: { value: "" } });
fireEvent.click(screen.getByText("Save Changes"));
await screen.findByText(SURNAME);
expectUnder(surname, SURNAME);
expectUnder(email, EMAIL);
expect(screen.queryByText(FIRST)).toBeNull();
expect(screen.queryByText(OLD_MSG)).toBeNull();
expect(apiPut).not.toHaveBeenCalled();
});
it("shows the First name message under the First Name input", async () => {
const { first } = await loaded();
fireEvent.change(first, { target: { value: "" } });
fireEvent.click(screen.getByText("Save Changes"));
await screen.findByText(FIRST);
expectUnder(first, FIRST);
expect(screen.queryByText(OLD_MSG)).toBeNull();
expect(apiPut).not.toHaveBeenCalled();
});
it("clears a field's message when that field is edited, leaving the others", async () => {
const { surname, email } = await loaded();
fireEvent.change(surname, { target: { value: "" } });
fireEvent.change(email, { target: { value: "" } });
fireEvent.click(screen.getByText("Save Changes"));
await screen.findByText(EMAIL);
fireEvent.change(email, { target: { value: "a" } });
await waitFor(() => expect(screen.queryByText(EMAIL)).toBeNull());
expect(screen.getByText(SURNAME)).toBeInTheDocument();
});
it("focuses the Email input and marks it aria-invalid when only Email is empty", async () => {
const { first, email } = await loaded();
fireEvent.change(email, { target: { value: "" } });
fireEvent.click(screen.getByText("Save Changes"));
await screen.findByText(EMAIL);
await waitFor(() => expect(document.activeElement).toBe(email));
expect(email).toHaveAttribute("aria-invalid", "true");
expect(first).not.toHaveAttribute("aria-invalid", "true");
});
it("focuses the first empty field (Surname) and marks both empty fields aria-invalid", async () => {
const { surname, email } = await loaded();
fireEvent.change(surname, { target: { value: "" } });
fireEvent.change(email, { target: { value: "" } });
fireEvent.click(screen.getByText("Save Changes"));
await screen.findByText(SURNAME);
await waitFor(() => expect(document.activeElement).toBe(surname));
expect(surname).toHaveAttribute("aria-invalid", "true");
expect(email).toHaveAttribute("aria-invalid", "true");
});
});
// ── Address search (replaces the country/state/town cascade) ──────────────────
const COUNTRIES = [
{ id: 1, name: '{"en_US":"Malaysia"}' },
{ id: 2, name: '{"en_US":"Singapore"}' },
];
const MY_PLACES = [
{ id: 111, label: "Puchong, Selangor, Malaysia", postCode: "47100" },
{ id: 113, label: "Petaling Jaya, Selangor, Malaysia", postCode: "46000" },
{ id: 121, label: "Yong Peng, Johor, Malaysia", postCode: "83700" },
{ id: 131, label: "Atlantis, Johor, Malaysia", postCode: null },
];
const SG_PLACES = [{ id: 201, label: "Ang Mo Kio, Singapore", postCode: null }];
const BASE_PROFILE = {
name: "Alice",
surname: "Tan",
email: "alice@example.com",
dob: "1990-05-10",
gender: "F",
postCode: "",
addressLocation: "",
addressDetails: "",
fullAddress: "",
memberCode: "M1",
};
function mockGeo(
opts: {
profile?: Record<string, unknown>;
init?: Record<string, unknown>;
my?: Array<{ id: number; label: string; postCode: string | null }>;
} = {},
) {
vi.mocked(apiGet).mockImplementation((url: string) => {
if (url.includes("/api/member/profile-init")) return Promise.resolve(opts.init ?? {});
if (url.includes("/api/geo/first-level")) return Promise.resolve(COUNTRIES);
if (url.includes("/api/geo/search-index?country=1")) return Promise.resolve(opts.my ?? MY_PLACES);
if (url.includes("/api/geo/search-index?country=2")) return Promise.resolve(SG_PLACES);
return Promise.resolve({ ...BASE_PROFILE, ...opts.profile });
});
}
const SAVED = {
addressLocation: "loc-1",
fullAddress: ", 47300, Petaling Jaya, Selangor, Malaysia",
addressDetails: "12 Jalan Mawar",
postCode: "47300",
};
const SEARCH = "Search town or postcode";
const areaPicker = () => screen.getByTestId("area-picker");
const areaText = () => areaPicker().textContent;
// The Area field is a button; tapping it opens a panel holding the search box and list.
async function openPanel() {
fireEvent.click(await screen.findByTestId("area-picker"));
return (await screen.findByPlaceholderText(SEARCH)) as HTMLInputElement;
}
async function renderEditor(opts: Parameters<typeof mockGeo>[0] = {}) {
mockGeo(opts);
render(<ProfilePage />);
const search = await openPanel();
const country = (opts.init?.geoLocationLevel1 as number | string | undefined) ?? 1;
await waitFor(() =>
expect(apiGet).toHaveBeenCalledWith(`/api/geo/search-index?country=${country}`),
);
return search;
}
function type(input: HTMLInputElement, value: string) {
fireEvent.change(input, { target: { value } });
}
// Re-opens the panel when a previous pick closed it, so the passed search box may be stale.
async function pick(_search: HTMLInputElement, query: string, label: string) {
const search = (screen.queryByPlaceholderText(SEARCH) as HTMLInputElement | null) ?? (await openPanel());
type(search, query);
const opt = await screen.findByRole("option", { name: label });
fireEvent.mouseDown(opt);
fireEvent.click(opt);
}
const postcodeInput = () => screen.getByPlaceholderText("Enter Postcode") as HTMLInputElement;
describe("ProfilePage — address display mode", () => {
it("shows the saved address on one line with a Change button and no place selects", async () => {
mockGeo({ profile: SAVED });
render(<ProfilePage />);
const line = await screen.findByTestId("profile-address-line");
expect(line.textContent).toBe("47300, Petaling Jaya, Selangor, Malaysia");
expect(screen.getByRole("button", { name: "Change" })).toBeInTheDocument();
expect(screen.queryByTestId("area-picker")).toBeNull();
// other selects (gender, DOB) remain, but nothing offers a country/place
const selects = screen.getAllByRole("combobox");
expect(selects.length).toBeGreaterThan(0);
expect(selects.some((s) => within(s).queryByText("Malaysia"))).toBe(false);
expect(screen.queryByLabelText("Country")).toBeNull();
});
it("has no leading separator when there is no street line", async () => {
mockGeo({ profile: { ...SAVED, addressDetails: "", fullAddress: ", 47300, Petaling Jaya, Selangor, Malaysia" } });
render(<ProfilePage />);
const line = await screen.findByTestId("profile-address-line");
expect(line.textContent).not.toMatch(/^[\s,]/);
expect(line.textContent).not.toMatch(/[\s,]$/);
});
it("opens the editor when Change is clicked", async () => {
mockGeo({ profile: SAVED });
render(<ProfilePage />);
fireEvent.click(await screen.findByRole("button", { name: "Change" }));
expect(await screen.findByTestId("area-picker")).toBeInTheDocument();
expect(screen.getByPlaceholderText("Unit, building, street")).toBeInTheDocument();
});
it("shows the editor directly when nothing is saved", async () => {
mockGeo();
render(<ProfilePage />);
expect(await screen.findByTestId("area-picker")).toBeInTheDocument();
expect(screen.queryByTestId("profile-address-line")).toBeNull();
});
});
describe("ProfilePage — area search", () => {
it("lists a matching place when typing 'puch'", async () => {
const search = await renderEditor();
type(search, "puch");
expect(await screen.findByRole("option", { name: "Puchong, Selangor, Malaysia" })).toBeInTheDocument();
expect(screen.queryByRole("option", { name: "Yong Peng, Johor, Malaysia" })).toBeNull();
});
it("matches case-insensitively", async () => {
const search = await renderEditor();
type(search, "PUCHONG");
expect(await screen.findByRole("option", { name: "Puchong, Selangor, Malaysia" })).toBeInTheDocument();
});
it("filters from the first character", async () => {
const search = await renderEditor();
type(search, "u");
expect(await screen.findByRole("option", { name: "Puchong, Selangor, Malaysia" })).toBeInTheDocument();
expect(screen.queryByRole("option", { name: /Petaling/ })).toBeNull();
});
it("shows at most 20 suggestions", async () => {
const many = Array.from({ length: 25 }, (_, i) => ({
id: 500 + i,
label: `Taman Bunga ${i}, Selangor, Malaysia`,
postCode: "40000",
}));
const search = await renderEditor({ my: many });
type(search, "taman");
expect(await screen.findAllByRole("option", { name: /Taman Bunga/ })).toHaveLength(20);
});
it("selecting a suggestion closes the list and shows its label in the input", async () => {
const search = await renderEditor();
await pick(search, "puch", "Puchong, Selangor, Malaysia");
await waitFor(() => expect(screen.queryByRole("option", { name: /Puchong/ })).toBeNull());
expect(areaText()).toBe("Puchong, Selangor, Malaysia");
});
it("sends the picked place id as addressLocation", async () => {
const search = await renderEditor();
await pick(search, "puch", "Puchong, Selangor, Malaysia");
await waitFor(() => expect(postcodeInput().value).toBe("47100"));
fireEvent.click(screen.getByText("Save Changes"));
await waitFor(() => expect(apiPut).toHaveBeenCalledTimes(1));
expect(apiPut).toHaveBeenCalledWith(
"/api/member/profile",
expect.objectContaining({ addressLocation: "111", postCode: "47100" }),
);
});
it("sends the saved addressLocation when nothing was picked", async () => {
mockGeo({ profile: SAVED });
render(<ProfilePage />);
await screen.findByTestId("profile-address-line");
fireEvent.click(screen.getByText("Save Changes"));
await waitFor(() => expect(apiPut).toHaveBeenCalledTimes(1));
expect(apiPut).toHaveBeenCalledWith(
"/api/member/profile",
expect.objectContaining({ addressLocation: "loc-1" }),
);
});
it("blocks save with a message when no place is picked or saved", async () => {
await renderEditor();
fireEvent.click(screen.getByText("Save Changes"));
await screen.findByText("Please select your address location.");
expect(apiPut).not.toHaveBeenCalled();
});
});
describe("ProfilePage — country selection", () => {
it("defaults to Malaysia when nothing is saved", async () => {
await renderEditor();
expect(apiGet).not.toHaveBeenCalledWith("/api/geo/search-index?country=2");
});
it("searches the saved country (Singapore)", async () => {
const search = await renderEditor({ init: { geoLocationLevel1: 2 } });
expect(apiGet).not.toHaveBeenCalledWith("/api/geo/search-index?country=1");
type(search, "ang mo");
expect(await screen.findByRole("option", { name: "Ang Mo Kio, Singapore" })).toBeInTheDocument();
});
it("accepts the saved country id as a string", async () => {
await renderEditor({ init: { geoLocationLevel1: "2" } });
expect(apiGet).not.toHaveBeenCalledWith("/api/geo/search-index?country=1");
});
it("switching the Country select loads that index and clears the pick", async () => {
const search = await renderEditor();
await pick(search, "puch", "Puchong, Selangor, Malaysia");
expect(areaText()).toBe("Puchong, Selangor, Malaysia");
const country = (await screen.findByLabelText("Country")) as HTMLSelectElement;
expect(within(country).getByText("Malaysia")).toBeInTheDocument();
expect(within(country).getByText("Singapore")).toBeInTheDocument();
fireEvent.change(country, { target: { value: "2" } });
await waitFor(() => expect(apiGet).toHaveBeenCalledWith("/api/geo/search-index?country=2"));
await waitFor(() => expect(areaText()).toBe("Select your area"));
fireEvent.click(screen.getByText("Save Changes"));
await screen.findByText("Please select your address location.");
expect(apiPut).not.toHaveBeenCalled();
});
});
describe("ProfilePage — street address line", () => {
it("is prefilled, has maxLength 250, and is sent trimmed after editing", async () => {
mockGeo({ profile: SAVED });
render(<ProfilePage />);
fireEvent.click(await screen.findByRole("button", { name: "Change" }));
const street = (await screen.findByPlaceholderText("Unit, building, street")) as HTMLInputElement;
expect(street.value).toBe("12 Jalan Mawar");
expect(street.maxLength).toBe(250);
type(street, " 8 Jalan Melati ");
fireEvent.click(screen.getByText("Save Changes"));
await waitFor(() => expect(apiPut).toHaveBeenCalledTimes(1));
expect(apiPut).toHaveBeenCalledWith(
"/api/member/profile",
expect.objectContaining({ addressDetails: "8 Jalan Melati" }),
);
});
it("does not block save when empty", async () => {
mockGeo({ profile: SAVED });
render(<ProfilePage />);
fireEvent.click(await screen.findByRole("button", { name: "Change" }));
const street = (await screen.findByPlaceholderText("Unit, building, street")) as HTMLInputElement;
type(street, "");
fireEvent.click(screen.getByText("Save Changes"));
await waitFor(() => expect(apiPut).toHaveBeenCalledTimes(1));
expect(apiPut).toHaveBeenCalledWith(
"/api/member/profile",
expect.objectContaining({ addressDetails: "" }),
);
});
});
describe("ProfilePage — postcode autofill from the picked place", () => {
it("fills an empty postcode from the picked place", async () => {
const search = await renderEditor();
expect(postcodeInput().value).toBe("");
await pick(search, "puch", "Puchong, Selangor, Malaysia");
await waitFor(() => expect(postcodeInput().value).toBe("47100"));
});
it("replaces a postcode that was already there with the picked place's", async () => {
const search = await renderEditor({ profile: { postCode: "99999" } });
expect(postcodeInput().value).toBe("99999");
await pick(search, "puch", "Puchong, Selangor, Malaysia");
await waitFor(() => expect(postcodeInput().value).toBe("47100"));
});
it("replaces a user-typed postcode with the picked place's", async () => {
const search = await renderEditor();
type(postcodeInput(), "11111");
await pick(search, "puch", "Puchong, Selangor, Malaysia");
await waitFor(() => expect(postcodeInput().value).toBe("47100"));
});
it("does not fill when the place has a null postcode", async () => {
const search = await renderEditor();
await pick(search, "atlan", "Atlantis, Johor, Malaysia");
await waitFor(() => expect(areaText()).toBe("Atlantis, Johor, Malaysia"));
expect(postcodeInput().value).toBe("");
});
it("replaces an automatically filled postcode when a different place is picked", async () => {
const search = await renderEditor();
await pick(search, "puch", "Puchong, Selangor, Malaysia");
await waitFor(() => expect(postcodeInput().value).toBe("47100"));
await pick(search, "petaling", "Petaling Jaya, Selangor, Malaysia");
await waitFor(() => expect(postcodeInput().value).toBe("46000"));
});
it("keeps a postcode edited after picking until another place is picked", async () => {
const search = await renderEditor();
await pick(search, "puch", "Puchong, Selangor, Malaysia");
await waitFor(() => expect(postcodeInput().value).toBe("47100"));
type(postcodeInput(), "47120");
expect(postcodeInput().value).toBe("47120");
await pick(search, "petaling", "Petaling Jaya, Selangor, Malaysia");
await waitFor(() => expect(postcodeInput().value).toBe("46000"));
});
});
describe("ProfilePage — postcode required & validated for Malaysia", () => {
it("marks the Postcode label required while Malaysia is selected", async () => {
await renderEditor();
const label = screen.getByText("Postcode").closest("p") as HTMLElement;
expect(label.textContent).toContain("*");
});
it("blocks save when a Malaysian address has no postcode", async () => {
const search = await renderEditor();
await pick(search, "atlan", "Atlantis, Johor, Malaysia");
await waitFor(() => expect(areaText()).toBe("Atlantis, Johor, Malaysia"));
fireEvent.click(screen.getByText("Save Changes"));
await screen.findByText("Please enter a valid 5-digit postcode.");
expect(apiPut).not.toHaveBeenCalled();
});
it("blocks save when the Malaysian postcode is not 5 digits", async () => {
const search = await renderEditor();
await pick(search, "puch", "Puchong, Selangor, Malaysia");
await waitFor(() => expect(postcodeInput().value).toBe("47100"));
type(postcodeInput(), "123");
fireEvent.click(screen.getByText("Save Changes"));
await screen.findByText("Please enter a valid 5-digit postcode.");
expect(apiPut).not.toHaveBeenCalled();
});
it("saves a Singapore address with an empty postcode", async () => {
const search = await renderEditor({ init: { geoLocationLevel1: 2 } });
await pick(search, "ang mo", "Ang Mo Kio, Singapore");
await waitFor(() => expect(areaText()).toBe("Ang Mo Kio, Singapore"));
expect(postcodeInput().value).toBe("");
fireEvent.click(screen.getByText("Save Changes"));
await waitFor(() => expect(apiPut).toHaveBeenCalledTimes(1));
expect(apiPut).toHaveBeenCalledWith(
"/api/member/profile",
expect.objectContaining({ addressLocation: "201", postCode: "" }),
);
});
});
// ── Follow-up: typed-not-picked, loading, fallback, ranking, combobox a11y ────
const PICK_MSG = "Please pick your area from the list.";
async function openEditor(opts: Parameters<typeof mockGeo>[0] = {}) {
mockGeo({ profile: SAVED, ...opts });
render(<ProfilePage />);
fireEvent.click(await screen.findByRole("button", { name: "Change" }));
const search = await openPanel();
const country = (opts.init?.geoLocationLevel1 as number | string | undefined) ?? 1;
await waitFor(() =>
expect(apiGet).toHaveBeenCalledWith(`/api/geo/search-index?country=${country}`),
);
return search;
}
function overrideIndex(handler: (url: string) => Promise<unknown>) {
const base = vi.mocked(apiGet).getMockImplementation()!;
vi.mocked(apiGet).mockImplementation(((url: string) =>
url.includes("/api/geo/search-index") ? handler(url) : base(url)) as typeof apiGet);
}
describe("ProfilePage — typed but not picked", () => {
it("keeps the saved area when search text was typed but nothing picked", async () => {
const search = await openEditor();
type(search, "zzz");
fireEvent.click(screen.getByText("Save Changes"));
await waitFor(() => expect(apiPut).toHaveBeenCalledTimes(1));
expect(apiPut).toHaveBeenCalledWith("/api/member/profile", expect.objectContaining({ addressLocation: "loc-1" }));
expect(screen.queryByText(PICK_MSG)).toBeNull();
});
it("does not apply when the search box is empty", async () => {
await openEditor();
fireEvent.click(screen.getByText("Save Changes"));
await waitFor(() => expect(apiPut).toHaveBeenCalledTimes(1));
expect(screen.queryByText(PICK_MSG)).toBeNull();
});
it("does not apply when the search box still shows the picked label", async () => {
const search = await openEditor();
await pick(search, "puch", "Puchong, Selangor, Malaysia");
await waitFor(() => expect(areaText()).toBe("Puchong, Selangor, Malaysia"));
fireEvent.click(screen.getByText("Save Changes"));
await waitFor(() => expect(apiPut).toHaveBeenCalledTimes(1));
expect(screen.queryByText(PICK_MSG)).toBeNull();
});
it("blocks save after switching country without picking", async () => {
await openEditor({ init: { geoLocationLevel1: 1 } });
const country = (await screen.findByLabelText("Country")) as HTMLSelectElement;
fireEvent.change(country, { target: { value: "2" } });
await waitFor(() => expect(apiGet).toHaveBeenCalledWith("/api/geo/search-index?country=2"));
fireEvent.click(screen.getByText("Save Changes"));
await screen.findByText(PICK_MSG);
expect(apiPut).not.toHaveBeenCalled();
});
});
describe("ProfilePage — places loading state", () => {
it("shows 'Loading places…' while the index request is pending", async () => {
let resolve!: (v: unknown) => void;
const deferred = new Promise((r) => { resolve = r; });
mockGeo();
overrideIndex(() => deferred);
render(<ProfilePage />);
await screen.findByTestId("area-picker");
expect(await screen.findByText("Loading places…")).toBeInTheDocument();
resolve(MY_PLACES);
await waitFor(() => expect(screen.queryByText("Loading places…")).toBeNull());
});
it("shows an error when the index request rejects", async () => {
mockGeo();
overrideIndex(() => Promise.reject(new Error("boom")));
render(<ProfilePage />);
await screen.findByTestId("area-picker");
expect(await screen.findByText("Couldn't load places.")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Try again" })).toBeInTheDocument();
expect(screen.queryByText("Loading places…")).toBeNull();
});
it("retries the place list from 'Try again' and then offers suggestions", async () => {
mockGeo();
let calls = 0;
let resolveRetry!: (v: unknown) => void;
overrideIndex(() => {
calls += 1;
if (calls === 1) return Promise.reject(new Error("boom"));
return new Promise((r) => { resolveRetry = r; });
});
render(<ProfilePage />);
const search = await openPanel();
fireEvent.click(await screen.findByRole("button", { name: "Try again" }));
expect(await screen.findByText("Loading places…")).toBeInTheDocument();
expect(screen.queryByText("Couldn't load places.")).toBeNull();
expect(calls).toBe(2);
resolveRetry(MY_PLACES);
await waitFor(() => expect(screen.queryByText("Loading places…")).toBeNull());
type(search, "puch");
expect(await screen.findByRole("option", { name: "Puchong, Selangor, Malaysia" })).toBeInTheDocument();
});
it("never shows 'Loading places…' when no country is available", async () => {
mockGeo();
const base = vi.mocked(apiGet).getMockImplementation()!;
vi.mocked(apiGet).mockImplementation(((url: string) =>
url.includes("/api/geo/first-level") ? Promise.resolve([]) : base(url)) as typeof apiGet);
render(<ProfilePage />);
await screen.findByTestId("area-picker");
expect(screen.queryByText("Loading places…")).toBeNull();
expect(apiGet).not.toHaveBeenCalledWith(expect.stringContaining("/api/geo/search-index"));
});
});
describe("ProfilePage — saved country id not in first-level", () => {
it("falls back to Malaysia and applies its postcode rule", async () => {
mockGeo({ init: { geoLocationLevel1: 999 } });
render(<ProfilePage />);
const search = await openPanel();
await waitFor(() => expect(apiGet).toHaveBeenCalledWith("/api/geo/search-index?country=1"));
expect(apiGet).not.toHaveBeenCalledWith("/api/geo/search-index?country=999");
await pick(search, "atlan", "Atlantis, Johor, Malaysia");
await waitFor(() => expect(areaText()).toBe("Atlantis, Johor, Malaysia"));
fireEvent.click(screen.getByText("Save Changes"));
await screen.findByText("Please enter a valid 5-digit postcode.");
expect(apiPut).not.toHaveBeenCalled();
});
});
describe("ProfilePage — suggestion ranking", () => {
const optionLabels = async () =>
within(await screen.findByRole("listbox"))
.getAllByRole("option")
.map((o) => o.textContent);
it("lists a deeper place before a shallower one when both match by own name", async () => {
const my = [
{ id: 11, label: "Selangor, Malaysia", postCode: null },
{ id: 114, label: "Selayang, Selangor, Malaysia", postCode: "68100" },
];
const search = await renderEditor({ my });
type(search, "sel");
expect(await optionLabels()).toEqual(["Selayang, Selangor, Malaysia", "Selangor, Malaysia"]);
});
it("ranks an own-name match above a deeper parent-only match", async () => {
const my = [
{ id: 115, label: "Bukit Jaya, Puchong, Selangor, Malaysia", postCode: "47100" },
{ id: 111, label: "Puchong, Selangor, Malaysia", postCode: "47100" },
{ id: 11, label: "Selangor, Malaysia", postCode: null },
];
const search = await renderEditor({ my });
type(search, "sel");
expect(await optionLabels()).toEqual([
"Selangor, Malaysia",
"Bukit Jaya, Puchong, Selangor, Malaysia",
"Puchong, Selangor, Malaysia",
]);
});
});
describe("ProfilePage — search combobox accessibility", () => {
it("the area button exposes aria-expanded and aria-controls tied to the listbox", async () => {
mockGeo();
render(<ProfilePage />);
const btn = await screen.findByTestId("area-picker");
expect(btn.getAttribute("aria-expanded")).toBe("false");
const box = await openPanel();
expect(box).toHaveAttribute("aria-label", SEARCH);
type(box, "puch");
const listbox = await screen.findByRole("listbox");
expect(btn.getAttribute("aria-expanded")).toBe("true");
expect(listbox.id).toBeTruthy();
expect(btn.getAttribute("aria-controls")).toBe(listbox.id);
fireEvent.mouseDown(await screen.findByRole("option", { name: "Puchong, Selangor, Malaysia" }));
await waitFor(() => expect(screen.queryByRole("listbox")).toBeNull());
expect(btn.getAttribute("aria-expanded")).toBe("false");
});
});
// ── Date of birth uses the calendar picker ────────────────────────────────────
describe("ProfilePage — date of birth calendar picker", () => {
it("replaces the Year/Month/Day selects with one field showing the saved date", async () => {
mockGeo({ profile: SAVED });
render(<ProfilePage />);
const field = await screen.findByRole("button", { name: "10 May 1990" });
expect(field).toHaveAttribute("aria-haspopup", "dialog");
for (const name of ["Year", "Month", "Day"]) {
expect(screen.queryByRole("option", { name })).toBeNull();
}
});
it("sends the picked year, month and day as a YYYY-MM-DD dob", async () => {
mockGeo({ profile: SAVED });
render(<ProfilePage />);
fireEvent.click(await screen.findByRole("button", { name: "10 May 1990" }));
await screen.findByRole("dialog", { name: "Choose your birth year" });
fireEvent.click(screen.getByRole("button", { name: "1985" }));
await screen.findByRole("dialog", { name: "Choose your birth month" });
fireEvent.click(screen.getByRole("button", { name: "March" }));
await screen.findByRole("dialog", { name: "Choose your birth day" });
fireEvent.click(screen.getByRole("button", { name: "7" }));
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
expect(screen.getByRole("button", { name: "7 March 1985" })).toBeInTheDocument();
fireEvent.click(screen.getByText("Save Changes"));
await waitFor(() => expect(apiPut).toHaveBeenCalledTimes(1));
expect(apiPut).toHaveBeenCalledWith(
"/api/member/profile",
expect.objectContaining({ dob: "1985-03-07" }),
);
});
it("blocks save with a message when the date of birth is empty", async () => {
mockGeo({ profile: { ...SAVED, dob: "" } });
render(<ProfilePage />);
await screen.findByRole("button", { name: "Select your date of birth" });
fireEvent.click(screen.getByText("Save Changes"));
await screen.findByText("Please complete your date of birth.");
expect(apiPut).not.toHaveBeenCalled();
});
});
describe("ProfilePage — profile reward baseline", () => {
const baseProfile = {
name: "Alice",
surname: "Tan",
email: "alice@example.com",
dob: "1990-05-10",
gender: "F",
postCode: "12345",
addressLocation: "loc-1",
memberCode: "M1",
};
const mockApis = (emrmProfileUpdate: string | undefined, balance: () => Promise<unknown>) => {
vi.mocked(apiGet).mockImplementation((url: string) => {
if (url.includes("/api/points/balance")) return balance() as Promise<never>;
if (url.includes("/api/member/profile-init")) return Promise.resolve({});
if (url.includes("/api/geo/first-level")) return Promise.resolve([]);
return Promise.resolve({ ...baseProfile, emrmProfileUpdate });
});
};
const save = async () => {
render(<ProfilePage />);
await screen.findByPlaceholderText("Your first name");
fireEvent.click(screen.getByText("Save Changes"));
};
beforeEach(() => {
sessionStorage.clear();
});
it("reads the balance before the save and stores it as the baseline when the profile is not yet complete", async () => {
vi.spyOn(Date, "now").mockReturnValue(1_700_000_000_000);
mockApis("N", () => Promise.resolve({ balance: 120 }));
await save();
await waitFor(() => expect(nav.push).toHaveBeenCalledWith("/"));
expect(apiGet).toHaveBeenCalledWith("/api/points/balance");
const balanceOrder = vi
.mocked(apiGet)
.mock.invocationCallOrder[
vi.mocked(apiGet).mock.calls.findIndex((c) => c[0] === "/api/points/balance")
];
expect(balanceOrder).toBeLessThan(vi.mocked(apiPut).mock.invocationCallOrder[0]);
const note = JSON.parse(sessionStorage.getItem("profileRewardBaseline") ?? "null");
expect(note.balance).toBe(120);
expect(note.at).toBe(1_700_000_000_000);
vi.mocked(Date.now).mockRestore();
});
it("does not read the balance or write a baseline when the profile is already complete", async () => {
mockApis("Y", () => Promise.resolve({ balance: 120 }));
await save();
await waitFor(() => expect(nav.push).toHaveBeenCalledWith("/"));
expect(apiGet).not.toHaveBeenCalledWith("/api/points/balance");
expect(sessionStorage.getItem("profileRewardBaseline")).toBeNull();
});
it("writes no baseline when the save fails", async () => {
mockApis("N", () => Promise.resolve({ balance: 120 }));
vi.mocked(apiPut).mockRejectedValue(new ApiError("boom", 500));
await save();
await waitFor(() => expect(apiPut).toHaveBeenCalled());
await waitFor(() => expect(screen.queryByText("Save Changes")).toBeInTheDocument());
expect(nav.push).not.toHaveBeenCalled();
expect(sessionStorage.getItem("profileRewardBaseline")).toBeNull();
});
it("still saves and writes no baseline when the balance read fails", async () => {
mockApis("N", () => Promise.reject(new Error("balance down")));
await save();
await waitFor(() => expect(apiPut).toHaveBeenCalled());
await waitFor(() => expect(nav.push).toHaveBeenCalledWith("/"));
expect(sessionStorage.getItem("profileRewardBaseline")).toBeNull();
});
});
describe("ProfilePage — area search by postcode", () => {
it("suggests the area whose postcode matches the typed 5 digits", async () => {
const search = await openEditor();
await pick(search, "47100", "Puchong, Selangor, Malaysia");
await waitFor(() => expect(areaText()).toBe("Puchong, Selangor, Malaysia"));
fireEvent.click(screen.getByText("Save Changes"));
await waitFor(() => expect(apiPut).toHaveBeenCalledTimes(1));
expect(apiPut).toHaveBeenCalledWith(
"/api/member/profile",
expect.objectContaining({ addressLocation: "111" }),
);
});
});
describe("ProfilePage — country first, area dropdown", () => {
it("shows the Country select first in the address editor, defaulted to Malaysia", async () => {
await renderEditor({ init: {} });
const country = screen.getByLabelText("Country") as HTMLSelectElement;
expect(country.selectedOptions[0].textContent).toBe("Malaysia");
expect(screen.queryByRole("button", { name: "Other country" })).toBeNull();
const street = screen.getByPlaceholderText("Unit, building, street");
expect(country.compareDocumentPosition(street) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
it("lists every area A-Z when the area panel opens", async () => {
await renderEditor();
const options = within(await screen.findByRole("listbox")).getAllByRole("option");
expect(options.map((o) => o.textContent)).toEqual([
"Atlantis, Johor, Malaysia",
"Petaling Jaya, Selangor, Malaysia",
"Puchong, Selangor, Malaysia",
"Yong Peng, Johor, Malaysia",
]);
});
it("the Area field is a button, not a text box, and shows a prompt until a place is picked", async () => {
mockGeo();
render(<ProfilePage />);
const btn = await screen.findByTestId("area-picker");
expect(btn.tagName).toBe("BUTTON");
expect(btn).toHaveAttribute("type", "button");
expect(areaText()).toBe("Select your area");
expect(screen.queryByPlaceholderText(SEARCH)).toBeNull();
});
it("closes the panel and shows the picked place on the Area button", async () => {
const search = await renderEditor();
await pick(search, "puch", "Puchong, Selangor, Malaysia");
await waitFor(() => expect(screen.queryByPlaceholderText(SEARCH)).toBeNull());
expect(areaText()).toBe("Puchong, Selangor, Malaysia");
});
it("tells members to pick the nearest town when their taman is not listed", async () => {
await renderEditor();
expect(
screen.getByText("Can't find your taman? Pick the nearest town and add your taman in the street line."),
).toBeInTheDocument();
});
it("caps the untyped list at 300 with a hint to type", async () => {
const many = Array.from({ length: 350 }, (_, i) => ({
id: 1000 + i,
label: `Town ${String(i).padStart(3, "0")}, Malaysia`,
postCode: null,
}));
await renderEditor({ my: many });
const listbox = await screen.findByRole("listbox");
expect(within(listbox).getAllByRole("option")).toHaveLength(300);
expect(screen.getByText("Type to narrow the list.")).toBeInTheDocument();
});
});