Files
co-lite/solvway-admin-portal/app/components/messages/MessageThreadDrawer.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

139 lines
7.3 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { act, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MessageThreadDrawer, mergeMessages } from "./MessageThreadDrawer";
import {
getAdminConversation, listAdminMessages, markAdminRead, sendAdminMessage,
type ConversationView, type MessageView,
} from "@/app/lib/services/adminMessages";
vi.mock("@/app/lib/services/adminMessages", async (orig) => ({
...(await orig<typeof import("@/app/lib/services/adminMessages")>()),
getAdminConversation: vi.fn(),
listAdminMessages: vi.fn(),
sendAdminMessage: vi.fn(),
markAdminRead: vi.fn(),
uploadAdminMessageImage: vi.fn(),
}));
const head: ConversationView = {
uuid: "c1", type: "S", counterpartCode: "MY3", counterpartName: "Aisyah", relationship: "SUPPORT",
level: null, subject: null, lastMessageAt: "2026-09-30T10:01:00", lastMessagePreview: "hello", unread: true, canSend: true,
};
const msg = (uuid: string, body: string, at: string, senderType: "M" | "A" = "M", senderCode = "MY3", imageCount = 0): MessageView =>
({ uuid, senderType, senderCode, mine: false, body, imageCount, createdAt: at, seq: Date.parse(at) / 1000 });
const m1 = msg("m1", "hello", "2026-09-30T10:00:00");
const m2 = msg("m2", "new one", "2026-09-30T10:01:00");
beforeEach(() => {
vi.mocked(getAdminConversation).mockReset().mockResolvedValue(head);
vi.mocked(listAdminMessages).mockReset().mockResolvedValue({ items: [m1], hasMore: false });
vi.mocked(markAdminRead).mockReset().mockResolvedValue({ updated: true });
vi.mocked(sendAdminMessage).mockReset();
});
afterEach(() => {
vi.useRealTimers();
Object.defineProperty(document, "visibilityState", { value: "visible", configurable: true });
});
describe("mergeMessages", () => {
it("merges by uuid, keeps oldest first and never duplicates", () => {
expect(mergeMessages([m1], [m2, m1]).map((m) => m.uuid)).toEqual(["m1", "m2"]);
});
});
describe("MessageThreadDrawer", () => {
it("shows the thread, the admin username on admin messages, and marks it read on open", async () => {
const onChanged = vi.fn();
vi.mocked(listAdminMessages).mockResolvedValue({ items: [msg("m2", "we shipped it", "2026-09-30T10:05:00", "A", "alice"), m1], hasMore: false });
render(<MessageThreadDrawer uuid="c1" onClose={vi.fn()} onChanged={onChanged} />);
expect(await screen.findByText("hello")).toBeInTheDocument();
expect(screen.getByText(/alice/)).toBeInTheDocument();
await waitFor(() => expect(markAdminRead).toHaveBeenCalledWith("c1"));
await waitFor(() => expect(onChanged).toHaveBeenCalled());
});
it("renders bodies as plain text", async () => {
vi.mocked(listAdminMessages).mockResolvedValue({ items: [msg("m1", "<b>bold</b>", "2026-09-30T10:00:00")], hasMore: false });
render(<MessageThreadDrawer uuid="c1" onClose={vi.fn()} onChanged={vi.fn()} />);
expect(await screen.findByText("<b>bold</b>")).toBeInTheDocument();
expect(document.querySelector("b")).toBeNull();
});
it("polls every 15s while visible, merges a new message once, and stops while hidden", async () => {
vi.useFakeTimers();
render(<MessageThreadDrawer uuid="c1" onClose={vi.fn()} onChanged={vi.fn()} />);
await act(async () => {});
expect(screen.getByText("hello")).toBeInTheDocument();
expect(markAdminRead).toHaveBeenCalledTimes(1);
vi.mocked(listAdminMessages).mockResolvedValue({ items: [m2, m1], hasMore: false });
await act(async () => { await vi.advanceTimersByTimeAsync(15_000); });
expect(screen.getByText("new one")).toBeInTheDocument();
expect(screen.getAllByText("hello")).toHaveLength(1);
expect(markAdminRead).toHaveBeenCalledTimes(2); // a member message arrived while open
await act(async () => { await vi.advanceTimersByTimeAsync(15_000); }); // same page again: no duplicate
expect(screen.getAllByText("new one")).toHaveLength(1);
Object.defineProperty(document, "visibilityState", { value: "hidden", configurable: true });
const calls = vi.mocked(listAdminMessages).mock.calls.length;
await act(async () => { await vi.advanceTimersByTimeAsync(45_000); });
expect(vi.mocked(listAdminMessages).mock.calls.length).toBe(calls);
});
it("sends a reply, appends it once and clears the composer", async () => {
vi.mocked(sendAdminMessage).mockResolvedValue(msg("m3", "on it", "2026-09-30T10:09:00", "A", "alice"));
const onChanged = vi.fn();
render(<MessageThreadDrawer uuid="c1" onClose={vi.fn()} onChanged={onChanged} />);
await screen.findByText("hello");
const send = screen.getByRole("button", { name: "Send" });
expect(send).toBeDisabled();
await userEvent.type(screen.getByRole("textbox", { name: "Reply" }), "on it");
expect(screen.getByText("5/2000")).toBeInTheDocument();
await userEvent.click(send);
await waitFor(() => expect(sendAdminMessage).toHaveBeenCalledWith("c1", "on it", []));
expect(await screen.findByText("on it", { selector: "p" })).toBeInTheDocument();
expect(screen.getByRole("textbox", { name: "Reply" })).toHaveValue("");
});
it("shows a send failure inline and keeps the draft", async () => {
vi.mocked(sendAdminMessage).mockRejectedValue(new Error("Upstream down"));
render(<MessageThreadDrawer uuid="c1" onClose={vi.fn()} onChanged={vi.fn()} />);
await screen.findByText("hello");
await userEvent.type(screen.getByRole("textbox", { name: "Reply" }), "x");
await userEvent.click(screen.getByRole("button", { name: "Send" }));
expect(await screen.findByText("Upstream down")).toBeInTheDocument();
expect(screen.getByRole("textbox", { name: "Reply" })).toHaveValue("x");
});
it("shows friendly copy, not the raw reason, for a known send failure", async () => {
vi.mocked(sendAdminMessage).mockRejectedValue(new Error("MESSAGE_COMMIT_FAILED"));
render(<MessageThreadDrawer uuid="c1" onClose={vi.fn()} onChanged={vi.fn()} />);
await screen.findByText("hello");
await userEvent.type(screen.getByRole("textbox", { name: "Reply" }), "x");
await userEvent.click(screen.getByRole("button", { name: "Send" }));
expect(await screen.findByText("The message couldn't be saved. Please try again.")).toBeInTheDocument();
expect(screen.queryByText("MESSAGE_COMMIT_FAILED")).toBeNull();
});
it("loads older messages with the oldest uuid as cursor", async () => {
vi.mocked(listAdminMessages)
.mockResolvedValueOnce({ items: [m2], hasMore: true })
.mockResolvedValueOnce({ items: [m1], hasMore: false });
render(<MessageThreadDrawer uuid="c1" onClose={vi.fn()} onChanged={vi.fn()} />);
await userEvent.click(await screen.findByRole("button", { name: "Load older messages" }));
expect(await screen.findByText("hello")).toBeInTheDocument();
expect(listAdminMessages).toHaveBeenLastCalledWith("c1", "m2");
});
});
// babyboo-56-warranty-claims: the composer can open holding a draft (prop initialDraft).
describe("MessageThreadDrawer initialDraft", () => {
it("puts the draft in the composer and sends nothing", async () => {
render(<MessageThreadDrawer uuid="c1" initialDraft="Warranty claim WC1: " onClose={vi.fn()} onChanged={vi.fn()} />);
expect(await screen.findByRole("textbox", { name: "Reply" })).toHaveValue("Warranty claim WC1: ");
expect(sendAdminMessage).not.toHaveBeenCalled();
});
});