67 lines
2.2 KiB
TypeScript
67 lines
2.2 KiB
TypeScript
// @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(<ScriptAnalytics nonce="aBcDeFgHiJkLmNoPqRsTuVwX" />);
|
|
|
|
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(<ScriptAnalytics nonce={nonce} />);
|
|
const scripts = [
|
|
document.querySelector<HTMLScriptElement>('script[src="https://scripts.simpleanalyticscdn.com/latest.js"]'),
|
|
document.querySelector<HTMLScriptElement>('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(
|
|
<ScriptAnalytics nonce="aBcDeFgHiJkLmNoPqRsTuVwX" />,
|
|
);
|
|
|
|
expect(markup).toContain(
|
|
'<img src="https://queue.simpleanalyticscdn.com/noscript.gif" alt=""',
|
|
);
|
|
});
|
|
});
|