import { fireEvent, render, screen } from "@testing-library/react"; import type HoverPrefetchLinkType from "./HoverPrefetchLink"; /** * Caminho-base de HoverPrefetchLink que só existe com next/navigation sem `usePathname` (os testes que trocam o * módulo por um dublê só com `notFound`): o `navigation.usePathname ?? (() => null)` do módulo cai no `null` e * nada muda no pré-carregamento, nem para uma âncora da home vista de outra página. * Arquivo à parte: o módulo é carregado isolado, depois de registrar o dublê, e não pode ter sido importado antes. */ jest.mock("next/link", () => ({ __esModule: true, default: ({ children, prefetch, ...props }: { children?: React.ReactNode; prefetch?: boolean | null } & Record< string, unknown >) => ( {children} ), })); function loadWithoutUsePathname() { const React = jest.requireActual("react"); let loaded: typeof HoverPrefetchLinkType | undefined; jest.isolateModules(() => { // o mesmo React do teste, para os hooks do componente isolado jest.doMock("react", () => React); jest.doMock("next/navigation", () => ({ notFound: jest.fn() })); loaded = require("./HoverPrefetchLink").default; }); jest.dontMock("react"); jest.dontMock("next/navigation"); if (!loaded) throw new Error("o módulo isolado não carregou"); return loaded; } describe("HoverPrefetchLink sem usePathname em next/navigation", () => { it("path: unknown page -> a home anchor waits for the first touch and then prefetches as usual", () => { const Isolated = loadWithoutUsePathname(); render(Ir); const link = screen.getByRole("link", { name: "Ir" }); expect(link).toHaveAttribute("data-prefetch", "false"); fireEvent.mouseEnter(link); expect(link).toHaveAttribute("data-prefetch", "null"); }); it("path: unknown page -> a link to another page behaves the same", () => { const Isolated = loadWithoutUsePathname(); render(Ir); const link = screen.getByRole("link", { name: "Ir" }); fireEvent.focus(link); expect(link).toHaveAttribute("data-prefetch", "null"); }); });