import { fireEvent, render, screen } from "@testing-library/react"; import HoverPrefetchLink from "./HoverPrefetchLink"; jest.mock("next/link", () => ({ __esModule: true, default: ({ children, prefetch, ...props }: { children?: React.ReactNode; prefetch?: boolean | null } & Record< string, unknown >) => ( {children} ), })); const link = () => screen.getByRole("link", { name: "Cases" }); it("does not prefetch when the page opens", () => { render(Cases); expect(link()).toHaveAttribute("data-prefetch", "false"); expect(link()).toHaveAttribute("href", "/cases"); }); it.each([ ["mouse", (element: Element) => fireEvent.mouseEnter(element)], ["keyboard focus", (element: Element) => fireEvent.focus(element)], ["touch", (element: Element) => fireEvent.touchStart(element)], ])("starts prefetching when the visitor reaches it by %s", (_label, reach) => { render(Cases); reach(link()); // null = o comportamento padrão do Link (pré-carrega a rota) expect(link()).toHaveAttribute("data-prefetch", "null"); }); it("keeps the callers' own handlers", () => { const onMouseEnter = jest.fn(); const onFocus = jest.fn(); const onClick = jest.fn(); render( Cases , ); fireEvent.mouseEnter(link()); fireEvent.focus(link()); fireEvent.click(link()); expect(onMouseEnter).toHaveBeenCalledTimes(1); expect(onFocus).toHaveBeenCalledTimes(1); expect(onClick).toHaveBeenCalledTimes(1); }); it("only prefetches the link that was reached, not its siblings", () => { render( <> Cases Serviços , ); fireEvent.mouseEnter(link()); expect(link()).toHaveAttribute("data-prefetch", "null"); expect(screen.getByRole("link", { name: "Serviços" })).toHaveAttribute( "data-prefetch", "false", ); });