import { describe, it, expect, afterEach, vi } from "vitest"; import { render, cleanup, waitFor } from "@testing-library/react"; import PreviewPage from "@/app/preview/page"; // next/navigation 의 useRouter 를 목으로 대체해 인증 실패 시 리다이렉트 동작을 검증한다. export const pushMock = vi.fn(); vi.mock("next/navigation", () => { return { __esModule: true, useRouter: () => ({ push: pushMock }), }; }); describe("PreviewPage 인증 가드", () => { afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.clearAllMocks(); }); it("/api/auth/me 가 401 을 반환하면 /login 으로 리다이렉트해야 한다", async () => { const fetchMock = vi.fn().mockImplementation((input: any, init?: any) => { const url = typeof input === "string" ? input : input.url; const method = init?.method ?? "GET"; if (url === "/api/auth/me" && method === "GET") { return Promise.resolve( new Response(JSON.stringify({ message: "인증이 필요합니다." }), { status: 401, headers: { "Content-Type": "application/json" }, }), ); } // 기타 요청은 200 으로 처리하되, 테스트에서는 사용하지 않는다. return Promise.resolve(new Response(null, { status: 200 })); }); vi.stubGlobal("fetch", fetchMock as any); render(); await waitFor(() => { expect(fetchMock).toHaveBeenCalled(); }); await waitFor(() => { expect(pushMock).toHaveBeenCalledWith("/login"); }); }); });