Files
co-lite/solvway-admin-portal/app/email-templates/EmailTemplateEditor.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

186 lines
7.6 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { fireEvent } from "@testing-library/react";
import { EmailTemplateEditor } from "./EmailTemplateEditor";
import type { EmailTemplate } from "@/app/lib/types";
const svc = vi.hoisted(() => ({
createEmailTemplate: vi.fn(),
updateEmailTemplate: vi.fn(),
previewEmailTemplate: vi.fn(),
uploadEmailAttachment: vi.fn(),
}));
vi.mock("@/app/lib/services/emailTemplates", async () => {
const actual = await vi.importActual<typeof import("@/app/lib/services/emailTemplates")>(
"@/app/lib/services/emailTemplates",
);
return { ...actual, ...svc };
});
const row: EmailTemplate = {
id: 1,
name: "Reset Password",
lang: "EN",
subject: "Reset your password",
body: "<p>Hello</p>",
status: "Y",
attachmentId: [],
};
beforeEach(() => {
svc.createEmailTemplate.mockReset();
svc.updateEmailTemplate.mockReset();
svc.previewEmailTemplate.mockReset();
svc.uploadEmailAttachment.mockReset();
svc.previewEmailTemplate.mockResolvedValue({ renderedHtml: "<p>Hello Amir</p>" });
});
describe("EmailTemplateEditor — edit mode", () => {
it("renders the name field read-only and prefilled on edit", () => {
render(<EmailTemplateEditor mode="edit" initialName="Reset Password" initialRows={[row]} />);
const nameInput = screen.getByLabelText("Name");
expect(nameInput).toHaveAttribute("readonly");
expect(nameInput).toHaveValue("Reset Password");
});
it("parses {{tokens}} from the body, collects sample values and calls the preview route", async () => {
const user = userEvent.setup();
render(<EmailTemplateEditor mode="edit" initialName="Reset Password" initialRows={[row]} />);
// Type a {{token}} into the body (fireEvent so the literal braces survive — userEvent
// escapes braces and would produce {firstName}).
const body = screen.getByLabelText("Body (HTML)");
fireEvent.change(body, { target: { value: "Hello {{firstName}}!" } });
// A sample-value input labelled with the token appears.
const sampleInput = await screen.findByLabelText("firstName");
await user.type(sampleInput, "Amir");
await waitFor(() => {
expect(svc.previewEmailTemplate).toHaveBeenCalledWith(
"Hello {{firstName}}!",
expect.objectContaining({ firstName: "Amir" }),
);
});
// The rendered preview is shown in the pane, inside the sandboxed frame (F09).
await waitFor(() => {
expect(screen.getByTitle("Preview").getAttribute("srcdoc")).toBe("<p>Hello Amir</p>");
});
});
it("updates the active language row through updateEmailTemplate with the immutable name", async () => {
const user = userEvent.setup();
svc.updateEmailTemplate.mockResolvedValue({ ...row, subject: "Reset your password now" });
render(<EmailTemplateEditor mode="edit" initialName="Reset Password" initialRows={[row]} />);
const subject = screen.getByLabelText("Subject");
await user.clear(subject);
await user.type(subject, "Reset your password now");
await user.click(screen.getByRole("button", { name: "Save template" }));
await waitFor(() => expect(svc.updateEmailTemplate).toHaveBeenCalledTimes(1));
const [id, payload] = svc.updateEmailTemplate.mock.calls[0];
expect(id).toBe(1);
expect(payload).toEqual(
expect.objectContaining({
name: "Reset Password",
subject: "Reset your password now",
lang: "EN",
attachmentId: [],
}),
);
});
});
describe("EmailTemplateEditor — create mode", () => {
it("shows the code-reference caveat and keeps the name editable", () => {
render(<EmailTemplateEditor mode="create" />);
const nameInput = screen.getByLabelText("Name");
expect(nameInput).not.toHaveAttribute("readonly");
expect(
screen.getByText(/must match a template key referenced in backend code/i),
).toBeInTheDocument();
});
});
describe("EmailTemplateEditor — form polish", () => {
it("mutes the read-only name on edit and keeps a monospace HTML body", () => {
render(<EmailTemplateEditor mode="edit" initialName="Reset Password" initialRows={[row]} />);
expect(screen.getByLabelText("Name")).toHaveClass("bg-muted");
expect(screen.getByLabelText("Body (HTML)")).toHaveClass("font-mono");
});
it("offers Add language as a visible button outside the tab list", () => {
render(<EmailTemplateEditor mode="edit" initialName="Reset Password" initialRows={[row]} />);
const add = screen.getByRole("combobox", { name: "Add language" });
expect(add).toBeVisible();
expect(add).toHaveTextContent("Add language");
expect(screen.getByRole("tablist")).not.toContainElement(add);
});
it("spaces each sample-value label from its input", async () => {
render(<EmailTemplateEditor mode="edit" initialName="Reset Password" initialRows={[{ ...row, body: "Hi {{firstName}}" }]} />);
const input = await screen.findByLabelText("firstName");
expect(input.parentElement).toHaveClass("space-y-1.5");
});
});
describe("EmailTemplateEditor — attachment management (Task 13)", () => {
it("uploads a picked file as base64, links the returned attachment, and removing drops its id from the save body", async () => {
const user = userEvent.setup();
svc.uploadEmailAttachment.mockResolvedValue({
id: 77,
fileName: "logo.png",
fileType: "image/png",
});
svc.updateEmailTemplate.mockResolvedValue({ ...row, attachmentId: [77] });
render(<EmailTemplateEditor mode="edit" initialName="Reset Password" initialRows={[row]} />);
const fileInput = screen.getByLabelText("Add attachment file");
const file = new File(["data"], "logo.png", { type: "image/png" });
await user.upload(fileInput, file);
// Uploaded through the BFF attachment route with the file read as base64.
await waitFor(() => expect(svc.uploadEmailAttachment).toHaveBeenCalledTimes(1));
const [payload] = svc.uploadEmailAttachment.mock.calls[0];
expect(payload.fileName).toBe("logo.png");
expect(payload.fileType).toBe("image/png");
expect(payload.base).toBeTruthy();
// The returned attachment appears in the list.
expect(await screen.findByText("logo.png")).toBeInTheDocument();
// Saving links the uploaded attachment id.
await user.click(screen.getByRole("button", { name: "Save template" }));
await waitFor(() => expect(svc.updateEmailTemplate).toHaveBeenCalledTimes(1));
expect(svc.updateEmailTemplate.mock.calls[0][1]).toEqual(
expect.objectContaining({ attachmentId: [77] }),
);
// Removing the attachment drops its id from the next save body.
svc.updateEmailTemplate.mockClear();
await user.click(screen.getByRole("button", { name: "Remove" }));
await user.click(screen.getByRole("button", { name: "Save template" }));
await waitFor(() => expect(svc.updateEmailTemplate).toHaveBeenCalledTimes(1));
expect(svc.updateEmailTemplate.mock.calls[0][1]).toEqual(
expect.objectContaining({ attachmentId: [] }),
);
});
it("saving a template with no attachments still sends attachmentId: []", async () => {
const user = userEvent.setup();
svc.updateEmailTemplate.mockResolvedValue({ ...row, attachmentId: [] });
render(<EmailTemplateEditor mode="edit" initialName="Reset Password" initialRows={[row]} />);
await user.click(screen.getByRole("button", { name: "Save template" }));
await waitFor(() => expect(svc.updateEmailTemplate).toHaveBeenCalledTimes(1));
expect(svc.updateEmailTemplate.mock.calls[0][1]).toEqual(
expect.objectContaining({ attachmentId: [] }),
);
});
});