// @vitest-environment jsdom
import { cleanup, render } from "@testing-library/react";
import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, describe, expect, it, vi } from "vitest";
import { buildDocumentContentSecurityPolicy } from "~/utils/security/contentSecurityPolicy";
import ScriptAnalytics from "./ScriptAnalytics";
const { hasConsent } = vi.hoisted(() => ({ hasConsent: vi.fn(() => true) }));
vi.mock("react-router", () => ({
useLocation: () => ({ pathname: "/" }),
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({
domainName: "example.test",
userSession: { cookies: [] },
appConfiguration: {
analytics: {
enabled: true,
simpleAnalytics: true,
plausibleAnalytics: true,
},
},
}),
}));
vi.mock("~/utils/app/HostAwareSurface", () => ({
isAppOrAdminSurface: () => false,
}));
vi.mock("~/utils/helpers/CookieHelper", () => ({
default: { hasConsent },
}));
afterEach(() => cleanup());
describe("analytics script CSP nonces", () => {
it("does not contact analytics providers before browser consent", () => {
hasConsent.mockReturnValueOnce(false);
render();
expect(document.querySelector("script[src*='simpleanalyticscdn.com'],script[src*='plausible.io']")).toBeNull();
});
it("renders every executable analytics tag with the nonce used by the response policy", () => {
const nonce = "aBcDeFgHiJkLmNoPqRsTuVwX";
const policy = buildDocumentContentSecurityPolicy(nonce);
render();
const scripts = [
document.querySelector('script[src="https://scripts.simpleanalyticscdn.com/latest.js"]'),
document.querySelector('script[src="https://plausible.io/js/script.js"]'),
];
expect(scripts.every((script) => script?.nonce === nonce)).toBe(true);
expect(policy).toContain(`'nonce-${nonce}'`);
});
it("keeps the tracking pixel decorative for assistive technology", () => {
const markup = renderToStaticMarkup(
,
);
expect(markup).toContain(
'