Skip to content

armgit / memos

Public Imported from GitHub
0

Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.

5.7 KB
Raw Blame
import { render, screen } from "@testing-library/react";
import type { ReactNode } from "react";
import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
import { beforeEach, describe, expect, it, vi } from "vitest";

vi.mock("@/hooks/useCurrentUser", () => ({
  __esModule: true,
  default: vi.fn(),
}));

const initialization = vi.hoisted(() => ({ auth: true, instance: true }));

vi.mock("@/contexts/AuthContext", () => ({
  useAuth: () => ({ isInitialized: initialization.auth }),
}));

vi.mock("@/contexts/InstanceContext", () => ({
  useInstance: () => ({ isInitialized: initialization.instance }),
}));

import useCurrentUser from "@/hooks/useCurrentUser";
import { RequireAuthRoute, RequireFullInitializationRoute, RequireGuestRoute, RequireInstanceInitializationRoute } from "@/router/guards";

const mockedUseCurrentUser = vi.mocked(useCurrentUser);

// Minimal User-like stand-in — guards only check truthiness on the value.
const fakeUser = { name: "users/steven" } as unknown as ReturnType<typeof useCurrentUser>;

const LocationProbe = () => {
  const location = useLocation();
  return <div data-testid="location">{`${location.pathname}${location.search}${location.hash}`}</div>;
};

const renderAt = (initialEntry: string, children: ReactNode) =>
  render(<MemoryRouter initialEntries={[initialEntry]}>{children}</MemoryRouter>);

beforeEach(() => {
  initialization.auth = true;
  initialization.instance = true;
});

describe("initialization guards", () => {
  it("keeps instance-dependent pages hidden until instance settings settle", () => {
    initialization.instance = false;

    renderAt(
      "/auth",
      <Routes>
        <Route element={<RequireInstanceInitializationRoute />}>
          <Route path="/auth" element={<div data-testid="instance-ready">ready</div>} />
        </Route>
      </Routes>,
    );

    expect(screen.queryByTestId("instance-ready")).not.toBeInTheDocument();
  });

  it("keeps non-feed pages hidden until both contexts fully initialize", () => {
    initialization.auth = false;

    renderAt(
      "/setting",
      <Routes>
        <Route element={<RequireFullInitializationRoute />}>
          <Route path="/setting" element={<div data-testid="fully-ready">ready</div>} />
        </Route>
      </Routes>,
    );

    expect(screen.queryByTestId("fully-ready")).not.toBeInTheDocument();
  });
});

describe("RequireAuthRoute", () => {
  it("renders the protected content for authenticated users", () => {
    mockedUseCurrentUser.mockReturnValue(fakeUser);

    renderAt(
      "/setting",
      <Routes>
        <Route element={<RequireAuthRoute />}>
          <Route path="/setting" element={<div data-testid="protected">secret</div>} />
        </Route>
      </Routes>,
    );

    expect(screen.getByTestId("protected")).toHaveTextContent("secret");
  });

  it("redirects unauthenticated users to /auth with the preserved location", () => {
    mockedUseCurrentUser.mockReturnValue(undefined);

    renderAt(
      "/setting?tab=pins#latest",
      <Routes>
        <Route element={<RequireAuthRoute />}>
          <Route path="/setting" element={<div data-testid="protected">secret</div>} />
        </Route>
        <Route path="/auth" element={<LocationProbe />} />
      </Routes>,
    );

    expect(screen.getByTestId("location").textContent).toBe("/auth?redirect=%2Fsetting%3Ftab%3Dpins%23latest");
  });
});

describe("RequireGuestRoute", () => {
  it("renders the auth page when no user is present", () => {
    mockedUseCurrentUser.mockReturnValue(undefined);

    renderAt(
      "/auth",
      <Routes>
        <Route element={<RequireGuestRoute />}>
          <Route path="/auth" element={<div data-testid="sign-in">sign in</div>} />
        </Route>
      </Routes>,
    );

    expect(screen.getByTestId("sign-in")).toHaveTextContent("sign in");
  });

  it("redirects already-authenticated users to / by default", () => {
    mockedUseCurrentUser.mockReturnValue(fakeUser);

    renderAt(
      "/auth",
      <Routes>
        <Route element={<RequireGuestRoute />}>
          <Route path="/auth" element={<div>sign in</div>} />
        </Route>
        <Route path="/" element={<LocationProbe />} />
      </Routes>,
    );

    expect(screen.getByTestId("location").textContent).toBe("/");
  });

  it("honours a safe redirect target from the query string", () => {
    mockedUseCurrentUser.mockReturnValue(fakeUser);

    renderAt(
      "/auth?redirect=%2Fsetting",
      <Routes>
        <Route element={<RequireGuestRoute />}>
          <Route path="/auth" element={<div>sign in</div>} />
        </Route>
        <Route path="/setting" element={<LocationProbe />} />
        <Route path="/" element={<LocationProbe />} />
      </Routes>,
    );

    expect(screen.getByTestId("location").textContent).toBe("/setting");
  });

  it("ignores an auth-family redirect target and falls back to /", () => {
    mockedUseCurrentUser.mockReturnValue(fakeUser);

    renderAt(
      "/auth?redirect=%2Fauth%2Fcallback",
      <Routes>
        <Route element={<RequireGuestRoute />}>
          <Route path="/auth" element={<div>sign in</div>} />
        </Route>
        <Route path="/" element={<LocationProbe />} />
      </Routes>,
    );

    expect(screen.getByTestId("location").textContent).toBe("/");
  });

  it("ignores an external redirect target and falls back to /", () => {
    mockedUseCurrentUser.mockReturnValue(fakeUser);

    renderAt(
      "/auth?redirect=%2F%2Fevil.example%2Fphish",
      <Routes>
        <Route element={<RequireGuestRoute />}>
          <Route path="/auth" element={<div>sign in</div>} />
        </Route>
        <Route path="/" element={<LocationProbe />} />
      </Routes>,
    );

    expect(screen.getByTestId("location").textContent).toBe("/");
  });
});