240 lines
9.3 KiB
TypeScript
240 lines
9.3 KiB
TypeScript
import "@testing-library/jest-dom";
|
|
import { fireEvent, render, screen } from "@testing-library/react";
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { MemoryRouter } from "react-router";
|
|
import TransactionalEmailsRoute, { action, loader } from "./transactional-emails";
|
|
import { getMailjetProviderStatus, updateMailjetSettings } from "~/modules/emails/services/TransactionalEmailSettings.server";
|
|
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
|
import { sendEmail } from "~/modules/emails/services/EmailService";
|
|
|
|
vi.mock("react-router", async () => {
|
|
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
|
return {
|
|
...actual,
|
|
useLoaderData: () => routeLoaderData,
|
|
useActionData: () => undefined,
|
|
useFetcher: () => ({
|
|
data: undefined,
|
|
state: "idle",
|
|
formData: undefined,
|
|
submit: vi.fn(),
|
|
Form: ({ children, ...props }: React.ComponentProps<"form">) => <form {...props}>{children}</form>,
|
|
}),
|
|
};
|
|
});
|
|
|
|
vi.mock("react-i18next", () => ({
|
|
useTranslation: () => ({
|
|
t: (key: string, args?: Record<string, string>) => {
|
|
if (key === "settings.admin.transactionalEmails.providerStatus") {
|
|
return `${args?.provider} ${args?.status}`;
|
|
}
|
|
if (key === "settings.admin.transactionalEmails.sources.summary") {
|
|
return `API key source: ${args?.apiKeySource}; From email source: ${args?.fromEmailSource}`;
|
|
}
|
|
if (key === "settings.admin.transactionalEmails.workerEnvNotice") {
|
|
return `This page can only verify web-visible environment keys. The worker must use ${args?.providerEnvName}, MAILJET_SECRET_KEY, MAILJET_FROM_EMAIL, and MAILJET_FROM_NAME to deliver queued mail.`;
|
|
}
|
|
const labels: Record<string, string> = {
|
|
"settings.admin.transactionalEmails.providers.mailjet": "Mailjet",
|
|
"settings.admin.transactionalEmails.status.configured": "Configured",
|
|
"settings.admin.transactionalEmails.status.missingConfiguration": "Missing configuration",
|
|
};
|
|
return labels[key] ?? key;
|
|
},
|
|
}),
|
|
}));
|
|
|
|
vi.mock("~/locale/i18next.server", () => ({
|
|
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
|
|
}));
|
|
|
|
vi.mock("~/locale/mail-translator.server", () => ({
|
|
getMailTranslator: vi.fn(async () => ({ t: (key: string) => key, locale: "en" })),
|
|
getMailTranslatorFromRequest: vi.fn(async () => ({ t: (key: string) => (key === "registry.welcomeDescription" ? "Localized welcome email" : key), locale: "en" })),
|
|
}));
|
|
|
|
vi.mock("~/utils/loaders.middleware", () => ({
|
|
requireAuth: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
|
verifyUserHasPermission: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/session.server", () => ({
|
|
requireUser: vi.fn(async () => ({ firstName: "Ada", email: "ada@example.com" })),
|
|
validateCSRFToken: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/data/useAdminData", () => ({
|
|
useAdminData: () => ({ user: { email: "admin@example.com" } }),
|
|
}));
|
|
|
|
vi.mock("~/utils/db/appConfiguration.db.server", () => ({
|
|
getAppConfiguration: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/modules/emails/services/TransactionalEmailSettings.server", () => ({
|
|
getMailjetProviderStatus: vi.fn(),
|
|
updateMailjetSettings: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/modules/emails/services/EmailService", () => ({
|
|
sendEmail: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/modules/emails/utils/EmailTemplates", () => ({
|
|
default: {
|
|
allTemplates: [
|
|
{
|
|
name: "welcome",
|
|
description: "Welcome email",
|
|
describe: (t?: (key: string) => string) => t?.("registry.welcomeDescription") ?? "Welcome email",
|
|
parse: vi.fn(() => ({ subject: "Welcome", body: "Hello" })),
|
|
},
|
|
],
|
|
},
|
|
}));
|
|
|
|
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({
|
|
default: ({ title, buttons, children }: { title: React.ReactNode; buttons?: React.ReactNode; children: React.ReactNode }) => (
|
|
<main>
|
|
<header>{title}</header>
|
|
<div>{buttons}</div>
|
|
{children}
|
|
</main>
|
|
),
|
|
}));
|
|
|
|
vi.mock("~/components/ui/tables/TableSimple", () => ({
|
|
default: ({ items }: { items: { name: string; description: string }[] }) => (
|
|
<table>
|
|
<tbody>
|
|
{items.map((item) => (
|
|
<tr key={item.name}>
|
|
<td>{item.name}</td>
|
|
<td>{item.description}</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
),
|
|
}));
|
|
|
|
vi.mock("~/components/ui/modals/ModalOrSlide", () => ({
|
|
default: ({ open, children }: { open: boolean; children: React.ReactNode }) => (open ? <section aria-label="Email Settings">{children}</section> : null),
|
|
}));
|
|
|
|
const appConfiguration = {
|
|
email: {
|
|
provider: "mailjet",
|
|
fromEmail: "sender@example.com",
|
|
fromName: "Support",
|
|
supportEmail: "support@example.com",
|
|
},
|
|
};
|
|
|
|
const mailjetStatus = {
|
|
id: "mailjet" as const,
|
|
name: "Mailjet" as const,
|
|
configured: true,
|
|
source: { apiKey: "environment" as const, secretKey: "environment" as const, fromEmail: "environment" as const },
|
|
missing: [],
|
|
};
|
|
|
|
let routeLoaderData = {
|
|
title: "Transactional Emails",
|
|
items: [{ name: "welcome", description: "Welcome email" }],
|
|
appConfiguration,
|
|
provider: mailjetStatus,
|
|
providers: [mailjetStatus],
|
|
};
|
|
|
|
const getAppConfigurationMock = vi.mocked(getAppConfiguration);
|
|
const getMailjetProviderStatusMock = vi.mocked(getMailjetProviderStatus);
|
|
const updateMailjetSettingsMock = vi.mocked(updateMailjetSettings);
|
|
const sendEmailMock = vi.mocked(sendEmail);
|
|
|
|
describe("admin transactional email route", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
routeLoaderData = {
|
|
title: "Transactional Emails",
|
|
items: [{ name: "welcome", description: "Welcome email" }],
|
|
appConfiguration,
|
|
provider: mailjetStatus,
|
|
providers: [mailjetStatus],
|
|
};
|
|
getAppConfigurationMock.mockResolvedValue(appConfiguration as Awaited<ReturnType<typeof getAppConfiguration>>);
|
|
getMailjetProviderStatusMock.mockResolvedValue(mailjetStatus);
|
|
updateMailjetSettingsMock.mockResolvedValue({ success: true });
|
|
});
|
|
|
|
it("loader exposes Mailjet as the only provider status without secrets", async () => {
|
|
const result = await loader({ request: new Request("https://admin.example.com/settings/transactional-emails"), params: {}, context: {}, unstable_pattern: "admin/settings/transactional-emails" });
|
|
|
|
expect(result.providers).toEqual([mailjetStatus]);
|
|
expect(result.provider).toEqual(mailjetStatus);
|
|
expect(result.items).toEqual([{ name: "welcome", description: "Localized welcome email" }]);
|
|
// The provider status must only carry redaction markers, never raw key material.
|
|
expect(Object.values(result.provider.source).every((value) => value === "environment" || value === "missing")).toBe(true);
|
|
});
|
|
|
|
it("action rejects provider tampering through the Mailjet update helper", async () => {
|
|
updateMailjetSettingsMock.mockResolvedValue({
|
|
success: false,
|
|
errorKey: "settings.admin.transactionalEmails.errors.unsupportedProvider",
|
|
});
|
|
const form = new FormData();
|
|
form.set("action", "update-app-configuration");
|
|
form.set("emailProvider", "sendgrid");
|
|
|
|
const result = await action({ request: new Request("https://admin.example.com/settings/transactional-emails", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(form as unknown as Record<string, string>) }), params: {}, context: {}, unstable_pattern: "admin/settings/transactional-emails" });
|
|
|
|
expect(result).toEqual({ error: "settings.admin.transactionalEmails.errors.unsupportedProvider" });
|
|
const submittedForm = updateMailjetSettingsMock.mock.calls[0]?.[0];
|
|
expect(submittedForm?.get("emailProvider")).toBe("sendgrid");
|
|
});
|
|
|
|
it("returns a localized error instead of exposing mail provider failures", async () => {
|
|
sendEmailMock.mockRejectedValueOnce(new Error("provider secret: upstream refused request"));
|
|
const form = new FormData();
|
|
form.set("action", "send-test");
|
|
form.set("template", "welcome");
|
|
form.set("email", "admin@example.com");
|
|
|
|
const result = await action({
|
|
request: new Request("https://admin.example.com/settings/transactional-emails", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
body: new URLSearchParams(form as unknown as Record<string, string>),
|
|
}),
|
|
params: {},
|
|
context: {},
|
|
unstable_pattern: "admin/settings/transactional-emails",
|
|
});
|
|
|
|
expect(result).toEqual({ error: "settings.admin.transactionalEmails.errors.testSendFailed" });
|
|
expect(JSON.stringify(result)).not.toContain("provider secret");
|
|
});
|
|
|
|
it("renders Mailjet-only settings without a generic provider selector", () => {
|
|
render(
|
|
<MemoryRouter>
|
|
<TransactionalEmailsRoute />
|
|
</MemoryRouter>
|
|
);
|
|
|
|
fireEvent.click(screen.getByRole("button"));
|
|
|
|
expect(screen.getByText("Mailjet")).toBeInTheDocument();
|
|
expect(screen.getByText("API key source: environment; From email source: environment")).toBeInTheDocument();
|
|
expect(screen.getByText(/This page can only verify web-visible environment keys/)).toBeInTheDocument();
|
|
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
|
|
expect(document.querySelector('input[name="emailFromEmail"]')).toBeNull();
|
|
expect(document.querySelector('input[name="emailFromName"]')).toBeNull();
|
|
expect(document.querySelector('input[name="emailProvider"]')).toHaveValue("mailjet");
|
|
});
|
|
});
|