42 lines
1.7 KiB
React
42 lines
1.7 KiB
React
import { render, screen } from "@testing-library/react";
|
|
import { MemoryRouter, Route, Routes } from "react-router-dom";
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import ProtectedRoute from "./ProtectedRoute";
|
|
import { useAuth } from "../contexts/AuthContext";
|
|
|
|
vi.mock("../contexts/AuthContext", () => ({ useAuth: vi.fn() }));
|
|
|
|
describe("protected routes", () => {
|
|
beforeEach(() => vi.mocked(useAuth).mockReset());
|
|
|
|
it("offers login instead of protected content to a guest", () => {
|
|
vi.mocked(useAuth).mockReturnValue({ user: null });
|
|
render(
|
|
<MemoryRouter initialEntries={["/dashboard"]}>
|
|
<Routes>
|
|
<Route element={<ProtectedRoute />}>
|
|
<Route path="dashboard" element={<p>Protected dashboard</p>} />
|
|
</Route>
|
|
</Routes>
|
|
</MemoryRouter>
|
|
);
|
|
expect(screen.getByRole("heading", { name: "Unauthorized" })).toBeInTheDocument();
|
|
expect(screen.queryByText("Protected dashboard")).not.toBeInTheDocument();
|
|
expect(screen.getByRole("link", { name: "Login" })).toHaveAttribute("href", "/login");
|
|
});
|
|
|
|
it("renders protected content for an authenticated user", () => {
|
|
vi.mocked(useAuth).mockReturnValue({ user: { user_id: 1 } });
|
|
render(
|
|
<MemoryRouter initialEntries={["/dashboard"]}>
|
|
<Routes>
|
|
<Route element={<ProtectedRoute />}>
|
|
<Route path="dashboard" element={<p>Protected dashboard</p>} />
|
|
</Route>
|
|
</Routes>
|
|
</MemoryRouter>
|
|
);
|
|
expect(screen.getByText("Protected dashboard")).toBeInTheDocument();
|
|
});
|
|
});
|