/**
* @jest-environment-options {"url": "https://evandro.dev.br/"}
*/
import { act, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { ComponentProps } from "react";
import { openCookiePreferences } from "@/lib/analytics";
import GoogleAnalytics from "./GoogleAnalytics";
/**
* Caminho de GoogleAnalytics (expireAnalyticsCookies) quando o site roda no próprio domínio evandro.dev.br:
* host e domínio raiz são o mesmo, então só há um atributo Domain.
*/
jest.mock("next/script", () => ({
__esModule: true,
default: ({
strategy: _strategy,
...props
}: ComponentProps<"script"> & { strategy?: string }) => ,
}));
const CONSENT_KEY = "evandro.analytics-consent.v1";
function setCookie(value: string) {
// biome-ignore lint/suspicious/noDocumentCookie: JSDOM cookie setup is the behavior boundary exercised by revocation.
document.cookie = value;
}
beforeEach(() => {
jest.replaceProperty(process.env, "NODE_ENV", "production");
localStorage.setItem(CONSENT_KEY, "granted");
});
afterEach(() => {
jest.restoreAllMocks();
localStorage.clear();
});
it("path: host is the site domain itself -> expires _ga on the path and once on the domain", async () => {
const user = userEvent.setup();
expect(window.location.hostname).toBe("evandro.dev.br");
setCookie("_ga=1; Path=/");
setCookie("_ga_ABC=1; Path=/");
render(
<>
>,
);
await screen.findByTestId("google-analytics-script");
const cookieWrites = jest.spyOn(document, "cookie", "set");
await user.click(
screen.getByRole("button", { name: "Preferências de cookies" }),
);
await act(async () => {});
await user.click(screen.getByRole("button", { name: "Recusar" }));
const writes = cookieWrites.mock.calls.map(([value]) => String(value));
// dois cookies (_ga e _ga_ABC), cada um: sem Domain e com Domain=evandro.dev.br (host == raiz, sem duplicar)
expect(writes).toHaveLength(4);
expect(writes.filter((w) => w.includes("Domain="))).toEqual([
expect.stringMatching(/^_ga=.*; Domain=evandro\.dev\.br$/),
expect.stringMatching(/^_ga_ABC=.*; Domain=evandro\.dev\.br$/),
]);
});