238 lines
8.8 KiB
TypeScript
238 lines
8.8 KiB
TypeScript
import "@testing-library/jest-dom";
|
|
import { render, screen } from "@testing-library/react";
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { MemoryRouter } from "react-router";
|
|
import AdminSettingsCookies, { action } from "./cookies";
|
|
import { getOrCreateAppConfiguration, updateAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
|
import { createAdminLog } from "~/utils/db/logs.db.server";
|
|
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
|
|
|
let routeLoaderData = {
|
|
title: "Cookie Settings",
|
|
appConfiguration: {
|
|
cookies: {
|
|
enabled: true,
|
|
},
|
|
},
|
|
};
|
|
let fetcherData: { success?: string; error?: string; fieldErrors?: Record<string, string[]> } | undefined;
|
|
let fetcherSubmit = vi.fn();
|
|
let canUpdate = true;
|
|
|
|
vi.mock("react-router", async () => {
|
|
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
|
return {
|
|
...actual,
|
|
useLoaderData: () => routeLoaderData,
|
|
useFetcher: () => ({
|
|
data: fetcherData,
|
|
state: "idle",
|
|
submit: fetcherSubmit,
|
|
}),
|
|
};
|
|
});
|
|
|
|
vi.mock("react-i18next", () => ({
|
|
useTranslation: () => ({ t: (key: string) => key }),
|
|
}));
|
|
|
|
vi.mock("~/locale/i18next.server", () => ({
|
|
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
|
|
}));
|
|
|
|
vi.mock("~/utils/data/useAdminData", () => ({
|
|
useAdminData: () => ({ permissions: canUpdate ? ["admin.settings.cookies.update"] : [] }),
|
|
}));
|
|
|
|
vi.mock("~/utils/helpers/PermissionsHelper", () => ({
|
|
getUserHasPermission: vi.fn(() => canUpdate),
|
|
}));
|
|
|
|
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
|
verifyUserHasPermission: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/session.server", () => ({
|
|
validateCSRFToken: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/data/useRootData", () => ({
|
|
useRootData: () => ({ csrf: "csrf-test-token" }),
|
|
}));
|
|
|
|
vi.mock("~/utils/db/appConfiguration.db.server", () => ({
|
|
getAppConfiguration: vi.fn(),
|
|
getOrCreateAppConfiguration: vi.fn(),
|
|
updateAppConfiguration: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/db/logs.db.server", () => ({
|
|
createAdminLog: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("sonner", () => ({
|
|
toast: { success: vi.fn(), error: vi.fn() },
|
|
}));
|
|
|
|
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/buttons/BackButtonWithTitle", () => ({
|
|
default: ({ children }: { children: React.ReactNode }) => <h1>{children}</h1>,
|
|
}));
|
|
|
|
vi.mock("~/components/ui/buttons/ButtonSecondary", () => ({
|
|
default: ({ children, ...props }: React.ComponentProps<"button">) => <button {...props}>{children}</button>,
|
|
}));
|
|
|
|
vi.mock("~/components/ui/icons/PreviewIcon", () => ({
|
|
default: () => <span aria-hidden="true" />,
|
|
}));
|
|
|
|
vi.mock("~/components/ui/input/InputCheckboxWithDescription", () => ({
|
|
default: ({ name, title, value, disabled }: { name: string; title: string; value?: boolean; disabled?: boolean }) => (
|
|
<label>
|
|
{title}
|
|
<input name={name} type="checkbox" defaultChecked={value} disabled={disabled} />
|
|
</label>
|
|
),
|
|
}));
|
|
|
|
vi.mock("~/components/ui/modals/Modal", () => ({
|
|
default: ({ open, children }: { open: boolean; children: React.ReactNode }) => (open ? <section aria-label="Cookie preview">{children}</section> : null),
|
|
}));
|
|
|
|
vi.mock("~/components/cookies/CookieConsentSettings", () => ({
|
|
default: () => <div>Cookie consent preview</div>,
|
|
}));
|
|
|
|
vi.mock("~/components/cookies/CookiesList", () => ({
|
|
default: () => <div>Cookies list</div>,
|
|
}));
|
|
|
|
const verifyUserHasPermissionMock = vi.mocked(verifyUserHasPermission);
|
|
const getOrCreateAppConfigurationMock = vi.mocked(getOrCreateAppConfiguration);
|
|
const updateAppConfigurationMock = vi.mocked(updateAppConfiguration);
|
|
const createAdminLogMock = vi.mocked(createAdminLog);
|
|
|
|
function postRequest(form: FormData) {
|
|
return new Request("https://admin.example.com/settings/cookies?token=secret", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
body: new URLSearchParams(form as unknown as Record<string, string>),
|
|
});
|
|
}
|
|
|
|
function validForm() {
|
|
const form = new FormData();
|
|
form.set("action", "update");
|
|
form.set("enabled", "true");
|
|
return form;
|
|
}
|
|
|
|
describe("admin cookie settings route", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
fetcherData = undefined;
|
|
fetcherSubmit = vi.fn();
|
|
canUpdate = true;
|
|
routeLoaderData = { title: "Cookie Settings", appConfiguration: { cookies: { enabled: true } } };
|
|
verifyUserHasPermissionMock.mockResolvedValue(undefined as never);
|
|
getOrCreateAppConfigurationMock.mockResolvedValue(undefined as never);
|
|
updateAppConfigurationMock.mockResolvedValue(undefined as never);
|
|
createAdminLogMock.mockResolvedValue(undefined as never);
|
|
});
|
|
|
|
it("rejects invalid actions before permission, database, or audit side effects", async () => {
|
|
const form = validForm();
|
|
form.set("action", "delete");
|
|
|
|
const response = await action({ request: postRequest(form), params: {}, context: {}, unstable_pattern: "admin/settings/cookies" });
|
|
const body = await (response as Response).json();
|
|
|
|
expect((response as Response).status).toBe(400);
|
|
expect(body.fieldErrors.action).toEqual(["Invalid action."]);
|
|
expect(verifyUserHasPermissionMock).not.toHaveBeenCalled();
|
|
expect(getOrCreateAppConfigurationMock).not.toHaveBeenCalled();
|
|
expect(updateAppConfigurationMock).not.toHaveBeenCalled();
|
|
expect(createAdminLogMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects tampered enabled values before permission, database, or audit side effects", async () => {
|
|
const form = validForm();
|
|
form.set("enabled", "maybe");
|
|
|
|
const response = await action({ request: postRequest(form), params: {}, context: {}, unstable_pattern: "admin/settings/cookies" });
|
|
const body = await (response as Response).json();
|
|
|
|
expect((response as Response).status).toBe(400);
|
|
expect(body.fieldErrors.enabled).toEqual(["Boolean value is invalid."]);
|
|
expect(verifyUserHasPermissionMock).not.toHaveBeenCalled();
|
|
expect(getOrCreateAppConfigurationMock).not.toHaveBeenCalled();
|
|
expect(updateAppConfigurationMock).not.toHaveBeenCalled();
|
|
expect(createAdminLogMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("propagates permission rejection for valid mutations without database or audit side effects", async () => {
|
|
const rejection = new Response("Forbidden", { status: 403 });
|
|
verifyUserHasPermissionMock.mockRejectedValue(rejection);
|
|
|
|
await expect(action({ request: postRequest(validForm()), params: {}, context: {}, unstable_pattern: "admin/settings/cookies" })).rejects.toBe(rejection);
|
|
|
|
expect(verifyUserHasPermissionMock).toHaveBeenCalledWith(expect.any(Request), "admin.settings.cookies.update");
|
|
expect(getOrCreateAppConfigurationMock).not.toHaveBeenCalled();
|
|
expect(updateAppConfigurationMock).not.toHaveBeenCalled();
|
|
expect(createAdminLogMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("updates valid cookie settings and writes a redacted audit payload without URL query secrets", async () => {
|
|
const response = await action({ request: postRequest(validForm()), params: {}, context: {}, unstable_pattern: "admin/settings/cookies" });
|
|
const body = await (response as Response).json();
|
|
|
|
expect((response as Response).status).toBe(200);
|
|
expect(body.success).toBe("shared.updated");
|
|
expect(updateAppConfigurationMock).toHaveBeenCalledWith({ cookiesEnabled: true });
|
|
expect(createAdminLogMock).toHaveBeenCalledWith(expect.any(Request), "admin.settings.updated", expect.any(String));
|
|
const auditPayload = createAdminLogMock.mock.calls[0][2];
|
|
expect(auditPayload).toContain("cookies");
|
|
expect(auditPayload).toContain("cookiesEnabled");
|
|
expect(auditPayload).toContain('"cookiesEnabled":true');
|
|
expect(auditPayload).not.toContain("token=secret");
|
|
});
|
|
|
|
it("renders accessible fetcher action and field errors", () => {
|
|
fetcherData = { error: "shared.invalidForm", fieldErrors: { enabled: ["Boolean value is invalid."], action: ["Invalid action."] } };
|
|
|
|
render(
|
|
<MemoryRouter>
|
|
<AdminSettingsCookies />
|
|
</MemoryRouter>
|
|
);
|
|
|
|
const alert = screen.getByRole("alert");
|
|
expect(alert).toHaveTextContent("shared.invalidForm");
|
|
expect(alert).toHaveTextContent("enabled: Boolean value is invalid.");
|
|
expect(alert).toHaveTextContent("action: Invalid action.");
|
|
});
|
|
|
|
it("preserves the preview modal path and disables updates without permission", () => {
|
|
canUpdate = false;
|
|
|
|
render(
|
|
<MemoryRouter>
|
|
<AdminSettingsCookies />
|
|
</MemoryRouter>
|
|
);
|
|
|
|
expect(screen.getByLabelText("settings.admin.cookies.fields.enabled.title")).toBeDisabled();
|
|
expect(screen.getByRole("button", { name: "shared.preview" })).toBeEnabled();
|
|
});
|
|
});
|