import { render, screen } from "@testing-library/react" import { MemoryRouter, Routes, Route } from "react-router-dom" import { describe, it, expect, vi } from "vitest" import { ProtectedRoute } from "./ProtectedRoute" import * as AuthContextModule from "./AuthContext" function renderWithAuth(authValue: Partial) { vi.spyOn(AuthContextModule, "useAuth").mockReturnValue({ user: null, project: null, loading: false, login: vi.fn(), register: vi.fn(), logout: vi.fn(), ...authValue, }) return render( login page} />
protected content
} />
, ) } describe("ProtectedRoute", () => { it("показывает спиннер, пока идёт проверка сессии", () => { renderWithAuth({ user: null, loading: true }) expect(screen.queryByText("protected content")).not.toBeInTheDocument() expect(screen.queryByText("login page")).not.toBeInTheDocument() expect(screen.getByRole("status")).toBeInTheDocument() }) it("редиректит на /login, когда пользователь не авторизован", () => { renderWithAuth({ user: null, loading: false }) expect(screen.getByText("login page")).toBeInTheDocument() expect(screen.queryByText("protected content")).not.toBeInTheDocument() }) it("рендерит children, когда пользователь авторизован", () => { renderWithAuth({ user: { id: "u1", email: "a@b.com" }, loading: false }) expect(screen.getByText("protected content")).toBeInTheDocument() expect(screen.queryByText("login page")).not.toBeInTheDocument() }) })