Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
52 lines
2.2 KiB
TypeScript
52 lines
2.2 KiB
TypeScript
import { render, screen } from "@testing-library/react";
|
|
import userEvent from "@testing-library/user-event";
|
|
import Link from "next/link";
|
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
|
|
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
|
|
|
import { memoryRouter } from "@/test/memoryRouter";
|
|
import { LeaveGuard } from "./LeaveGuard";
|
|
|
|
// add-page-visual-editor: unsaved edits are guarded against in-app links too, not only reloads.
|
|
beforeEach(() => memoryRouter.reset("/pages/5"));
|
|
|
|
const menu = (
|
|
<nav>
|
|
<Link href="/events">Events</Link>
|
|
<a href="/p/INS/hotel" target="_blank" rel="noopener noreferrer">View page</a>
|
|
<a href="#top">Top</a>
|
|
</nav>
|
|
);
|
|
|
|
describe("LeaveGuard", () => {
|
|
it("asks before an in-app link leaves unsaved edits: Cancel stays, Leave goes", async () => {
|
|
const user = userEvent.setup();
|
|
render(<>{menu}<LeaveGuard dirty /></>);
|
|
await user.click(screen.getByRole("link", { name: "Events" }));
|
|
expect(screen.getByRole("dialog", { name: "Leave without saving?" })).toBeInTheDocument();
|
|
await user.click(screen.getByRole("button", { name: "Cancel" }));
|
|
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
|
expect(memoryRouter.push).not.toHaveBeenCalled();
|
|
|
|
await user.click(screen.getByRole("link", { name: "Events" }));
|
|
await user.click(screen.getByRole("button", { name: "Leave" }));
|
|
expect(memoryRouter.push).toHaveBeenCalledWith("/events");
|
|
});
|
|
|
|
it("lets links through when nothing is unsaved, and never stops a new tab or a link within the page", async () => {
|
|
const user = userEvent.setup();
|
|
const { rerender } = render(<>{menu}<LeaveGuard dirty={false} /></>);
|
|
await user.click(screen.getByRole("link", { name: "Events" }));
|
|
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
|
|
|
rerender(<>{menu}<LeaveGuard dirty /></>);
|
|
await user.click(screen.getByRole("link", { name: "View page" }));
|
|
await user.click(screen.getByRole("link", { name: "Top" }));
|
|
await user.keyboard("{Control>}");
|
|
await user.click(screen.getByRole("link", { name: "Events" }));
|
|
await user.keyboard("{/Control}");
|
|
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
|
});
|
|
});
|