OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
chore: Add UI test utils (#2353)
Mike Fortmana9b764216f5f
diff --git a/AGENTS.md b/AGENTS.mdindex 898d2f6ff..dd994df94 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -54,6 +54,25 @@ Two suites live in `frontend/`, and **the file extension names the runner**:- Never `vi.mock` a module in `app/api/queries/` or `app/api/mutations/`. Mock the network instead, so the URL, `response.ok` handling, payload shape, and react-query wiring stay under test.- Use `renderWithProviders` from `test-utils/render.tsx`, not `app/providers.tsx`. The latter monkey-patches `window.fetch` for 401 redirects, and `app/api/get-query-client.ts` memoizes one client per browser process, which leaks cache between tests.+**The provider harness.** `app/layout.tsx` nests eight contexts and 69 of the 124 client components consume at least one of them, so `renderWithProviders` mounts the **real** providers on request and drives their state through MSW:++```tsx+renderWithProviders(<ConnectorCard />, {+ providers: ["auth", "brand", "task"], // dependencies are added automatically+ auth: authPresets.viewer, // installs the /api/auth/* handlers+ brand: "ibm", // seeds localStorage before mount+ handlers: [http.get("/api/connectors", ...)], // wins over the auth scenario+});+```++- **Name the contexts the component uses, not the whole tree.** `providers: ["consoleStatus"]` pulls in auth, task, and knowledgeFilter on its own. `providers: "all"` mounts the full layout stack — for page-level tests. Naming two or three keeps failures readable.+- **Auth scenarios live in `test-utils/fixtures/auth.ts`**, one per branch of `checkAuth`: `admin`, `viewer`, `noAuthMode`, `ibmAuthMode`, `unauthenticated`, `rbacDisabled`. Vary one field with `withAuth(preset, {...})` rather than adding a preset per permutation. The three cases that break gates are the ones where "signed in", "allowed", and "has permissions" come apart — no-auth mode grants everything while holding no user, and RBAC-disabled grants everything while holding no permissions.+- **Per-test handlers go in the `handlers` option, not `server.use()`.** The harness installs the auth scenario at render time, which would be prepended over an override set earlier in the test body.+- **Provider state is async** — auth alone is three fetches, so the first paint is always the loading state. Assert with `await screen.findBy…`, never a bare `getBy…` on the first tick (except when you are deliberately asserting the loading state).+- **Fixtures** for `Task`, `TaskFileEntry`, and `Settings` are in `test-utils/fixtures/`. `makeTask()` derives its file counts from the `files` map so they agree; pass counts explicitly only when testing an inconsistent payload.+- **`next/navigation` is mocked globally** in `test-utils/setup.ts` — the one place the "mock the network, not the module" rule does not apply, because it is framework plumbing with no network beneath it. Drive and assert it through `test-utils/router.ts` (`setMockLocation`, `mockRouter.push`). Navigation that must actually re-render a route belongs in Playwright.+- **Default handlers in `test-utils/msw/handlers.ts` cover only what a provider fetches on mount** (`/api/auth/me`, `/api/users/me`, `/api/onboarding-status`, `/api/tasks/enhanced`, `/api/settings`). Anything a *component* fetches belongs in that component's test. Note `/api/auth/me` must always answer: `checkAuth` reschedules itself via `setTimeout` on a 5xx, so an unmocked call does not fail the test — it retries until the test times out.+**Diff coverage gate.** PRs must cover the lines they change: `npm run test:diff-coverage` runs the suite and then `scripts/check-diff-coverage.mjs`, which fails when under 80% of *changed executable lines* are covered. Enforced by the `diff-coverage` job in `test-frontend-unit.yml`.The gate is on changed **lines**, not changed files — a one-line fix to an untested legacy file is not blocked, but new logic must come with tests. It diffs the merge base against the working tree, so it also reports on uncommitted work locally. Tune with `--threshold` / `--base` or `DIFF_COVERAGE_THRESHOLD` / `DIFF_COVERAGE_BASE`.diff --git a/frontend/components/protected-route.test.tsx b/frontend/components/protected-route.test.tsxnew file mode 100644index 000000000..d3105d3e0--- /dev/null+++ b/frontend/components/protected-route.test.tsx@@ -0,0 +1,74 @@+/**+ * The gate every authenticated page sits behind. A mistake here either locks+ * users out of a working install or renders protected content to someone who+ * is not signed in, so all four auth shapes are pinned.+ *+ * Exercises the harness end to end: the real `AuthProvider` resolving from MSW,+ * and the shared `next/navigation` double for the redirect assertions.+ */+import { describe, expect, it } from "vitest";+import { ProtectedRoute } from "@/components/protected-route";+import { authPresets } from "@/test-utils/fixtures/auth";+import { renderWithProviders, screen, waitFor } from "@/test-utils/render";+import { mockRouter, setMockLocation } from "@/test-utils/router";++function renderGate(auth: (typeof authPresets)[keyof typeof authPresets]) {+ return renderWithProviders(+ <ProtectedRoute>+ <p>Secret dashboard</p>+ </ProtectedRoute>,+ { providers: ["auth"], auth },+ );+}++describe("ProtectedRoute", () => {+ it("shows a loading state before auth resolves", () => {+ renderGate(authPresets.admin);++ // Asserted synchronously, before the boot fetches settle.+ expect(screen.getByText("Loading...")).toBeInTheDocument();+ expect(screen.queryByText("Secret dashboard")).not.toBeInTheDocument();+ });++ it("renders children for a signed-in user", async () => {+ renderGate(authPresets.admin);++ expect(await screen.findByText("Secret dashboard")).toBeInTheDocument();+ expect(mockRouter.push).not.toHaveBeenCalled();+ });++ it("renders children in no-auth mode even though nobody is signed in", async () => {+ // OPENRAG_AUTH_ENABLED=false. Treating "no user" as "not allowed" here+ // would lock every page of an auth-disabled install.+ renderGate(authPresets.noAuthMode);++ expect(await screen.findByText("Secret dashboard")).toBeInTheDocument();+ expect(mockRouter.push).not.toHaveBeenCalled();+ });++ it("redirects to login with the current path so the user comes back", async () => {+ setMockLocation({ pathname: "/knowledge/chunks" });++ renderGate(authPresets.unauthenticated);++ await waitFor(() => {+ expect(mockRouter.push).toHaveBeenCalledWith(+ "/login?redirect=%2Fknowledge%2Fchunks",+ );+ });+ expect(screen.queryByText("Secret dashboard")).not.toBeInTheDocument();+ });++ it("sends an unauthenticated IBM tenant to /unauthorized, not /login", async () => {+ // IBM auth has no local login form to land on.+ renderGate({+ ...authPresets.ibmAuthMode,+ me: { ibm_auth_mode: true, authenticated: false, user: null },+ });++ await waitFor(() => {+ expect(mockRouter.push).toHaveBeenCalledWith("/unauthorized");+ });+ expect(screen.queryByText("Secret dashboard")).not.toBeInTheDocument();+ });+});diff --git a/frontend/components/require-permission.test.tsx b/frontend/components/require-permission.test.tsxnew file mode 100644index 000000000..777bb837c--- /dev/null+++ b/frontend/components/require-permission.test.tsx@@ -0,0 +1,124 @@+/**+ * The RBAC affordance wrapper. It is a UX gate only — the backend still 403s —+ * but getting it wrong hides working features from users who do have access,+ * which reads as a broken product.+ *+ * The cases that matter are the two where a user holds no permissions and must+ * still see everything: no-auth mode, and RBAC not enforced.+ */+import { describe, expect, it } from "vitest";+import { RequirePermission } from "@/components/require-permission";+import { type AuthScenario, authPresets } from "@/test-utils/fixtures/auth";+import { renderWithProviders, screen } from "@/test-utils/render";++function renderGate(ui: React.ReactElement, auth: AuthScenario) {+ return renderWithProviders(ui, { providers: ["auth"], auth });+}++describe("RequirePermission", () => {+ it("renders children when the user holds the permission", async () => {+ renderGate(+ <RequirePermission perm="config:write">+ <button type="button">Save</button>+ </RequirePermission>,+ authPresets.admin,+ );++ expect(await screen.findByRole("button", { name: "Save" })).toBeVisible();+ });++ it("renders the fallback when the user does not", async () => {+ renderGate(+ <RequirePermission perm="config:write" fallback={<p>Read only</p>}>+ <button type="button">Save</button>+ </RequirePermission>,+ authPresets.viewer,+ );++ expect(await screen.findByText("Read only")).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Save" })).toBeNull();+ });++ it("hides children by default when there is no fallback", async () => {+ renderGate(+ <>+ <p>Page</p>+ <RequirePermission perm="config:write">+ <button type="button">Save</button>+ </RequirePermission>+ </>,+ authPresets.viewer,+ );++ await screen.findByText("Page");+ expect(screen.queryByRole("button", { name: "Save" })).toBeNull();+ });++ it("requires every permission listed in allOf", async () => {+ renderGate(+ <RequirePermission+ allOf={["config:read", "config:write"]}+ fallback={<p>Denied</p>}+ >+ <button type="button">Save</button>+ </RequirePermission>,+ authPresets.viewer,+ );++ expect(await screen.findByText("Denied")).toBeInTheDocument();+ });++ it("requires only one permission listed in anyOf", async () => {+ renderGate(+ <RequirePermission anyOf={["config:write", "config:read"]}>+ <button type="button">Edit</button>+ </RequirePermission>,+ authPresets.viewer,+ );++ expect(await screen.findByRole("button", { name: "Edit" })).toBeVisible();+ });++ it("grants everything in no-auth mode despite an empty permission set", async () => {+ renderGate(+ <RequirePermission perm="config:write">+ <button type="button">Save</button>+ </RequirePermission>,+ authPresets.noAuthMode,+ );++ expect(await screen.findByRole("button", { name: "Save" })).toBeVisible();+ });++ it("grants everything when the backend is not enforcing RBAC", async () => {+ renderGate(+ <RequirePermission perm="config:write">+ <button type="button">Save</button>+ </RequirePermission>,+ authPresets.rbacDisabled,+ );++ expect(await screen.findByRole("button", { name: "Save" })).toBeVisible();+ });++ it("renders the fallback when no criterion is given at all", async () => {+ // A misconfigured gate must fail closed, not silently allow. The prop+ // union makes this unreachable from TypeScript — hence the cast — but the+ // defensive branch exists, and this pins it in case the union is ever+ // loosened.+ const Gate = RequirePermission as unknown as React.ComponentType<{+ children: React.ReactNode;+ fallback?: React.ReactNode;+ }>;++ renderGate(+ <Gate fallback={<p>Denied</p>}>+ <button type="button">Save</button>+ </Gate>,+ authPresets.admin,+ );++ expect(await screen.findByText("Denied")).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Save" })).toBeNull();+ });+});diff --git a/frontend/components/task-dialog/use-task-dialog.test.tsx b/frontend/components/task-dialog/use-task-dialog.test.tsxindex c5f987efb..7ada539f2 100644--- a/frontend/components/task-dialog/use-task-dialog.test.tsx+++ b/frontend/components/task-dialog/use-task-dialog.test.tsx@@ -1,4 +1,5 @@import { HttpResponse, http } from "msw";+import type { ReactNode } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";import type { RetryTaskResponse } from "@/app/api/mutations/useRetryTaskMutation";import type { Task, TaskFileEntry } from "@/app/api/queries/useGetTasksQuery";@@ -28,8 +29,14 @@ import { useTaskDialog } from "./use-task-dialog";const markTaskFilesProcessing = vi.fn();const refreshTasks = vi.fn().mockResolvedValue(undefined);+// `TaskProvider` is stubbed as a passthrough only because+// `test-utils/render.tsx` imports it from this module to build its provider+// stack. This test never mounts it, so a passthrough is honest — and cheaper+// than `importOriginal`, whose async factory resolves after the module graph+// has already bound the real export here.vi.mock("@/contexts/task-context", () => ({useTask: () => ({ markTaskFilesProcessing, refreshTasks }),+ TaskProvider: ({ children }: { children: ReactNode }) => children,}));const toast = vi.hoisted(() => ({diff --git a/frontend/contexts/auth-context.test.tsx b/frontend/contexts/auth-context.test.tsxnew file mode 100644index 000000000..545f55735--- /dev/null+++ b/frontend/contexts/auth-context.test.tsx@@ -0,0 +1,239 @@+/**+ * `AuthProvider` is the outermost context in `app/layout.tsx` and 33 files call+ * `useAuth()`, so what it resolves to decides what most of the UI renders.+ *+ * Everything here goes through the real provider and real `fetch`; only the+ * three boot endpoints are stubbed, via the shared scenarios in+ * `test-utils/fixtures/auth.ts`. Nothing about the provider is mocked.+ *+ * The cases worth protecting are the ones where "signed in", "allowed", and+ * "has permissions" come apart — no-auth mode grants everything while holding+ * no user, and RBAC-disabled grants everything while holding no permissions.+ * Both look falsy to a naive gate.+ */+import { renderHook, waitFor } from "@testing-library/react";+import { HttpResponse, http, type RequestHandler } from "msw";+import { describe, expect, it } from "vitest";+import { type User, useAuth } from "@/contexts/auth-context";+import {+ type AuthScenario,+ authPresets,+ makeUser,+ withAuth,+} from "@/test-utils/fixtures/auth";+import { server } from "@/test-utils/msw/server";+import { createQueryWrapper } from "@/test-utils/render";++/**+ * Mounts the provider under `scenario` and waits out the boot fetches.+ *+ * Gates on `permissionsResolved` rather than `isLoading`: `/api/auth/me`+ * settling only starts the `/api/users/me` fetch, so asserting on permissions+ * after `isLoading` alone is a race.+ */+async function renderAuth(+ scenario: AuthScenario,+ handlers: RequestHandler[] = [],+) {+ const view = renderHook(() => useAuth(), {+ wrapper: createQueryWrapper({+ providers: ["auth"],+ auth: scenario,+ handlers,+ }),+ });++ await waitFor(() => {+ expect(view.result.current.isLoading).toBe(false);+ expect(view.result.current.permissionsResolved).toBe(true);+ });++ return view;+}++describe("AuthProvider", () => {+ it("throws when useAuth is called outside the provider", () => {+ expect(() => renderHook(() => useAuth())).toThrow(+ "useAuth must be used within an AuthProvider",+ );+ });++ describe("a signed-in user", () => {+ it("exposes the user, roles, and granted permissions", async () => {+ const { result } = await renderAuth(authPresets.admin);++ expect(result.current.isAuthenticated).toBe(true);+ expect(result.current.user?.email).toBe("[email protected]");+ expect(result.current.roles).toEqual(["admin"]);+ expect(result.current.can("config:write")).toBe(true);+ expect(result.current.isNoAuthMode).toBe(false);+ expect(result.current.isIbmAuthMode).toBe(false);+ });++ it("reports the version and run mode from /api/auth/me", async () => {+ const { result } = await renderAuth(+ withAuth(authPresets.admin, { me: { run_mode: "oss" } }),+ );++ expect(result.current.version).toBe("1.0.0");+ expect(result.current.runMode).toBe("oss");+ });++ it("denies a permission the user was not granted", async () => {+ const { result } = await renderAuth(authPresets.viewer);++ expect(result.current.isAuthenticated).toBe(true);+ expect(result.current.can("config:read")).toBe(true);+ expect(result.current.can("config:write")).toBe(false);+ expect(result.current.can("users:write")).toBe(false);+ });+ });++ describe("no-auth mode", () => {+ // OPENRAG_AUTH_ENABLED=false. The trap: there is no user, so any gate+ // written as `user && can(...)` hides UI that should be fully open.+ it("grants every permission despite holding no user", async () => {+ const { result } = await renderAuth(authPresets.noAuthMode);++ expect(result.current.isNoAuthMode).toBe(true);+ expect(result.current.user).toBeNull();+ expect(result.current.isAuthenticated).toBe(false);+ expect(result.current.can("config:write")).toBe(true);+ expect(result.current.can("anything:at:all")).toBe(true);+ });+ });++ describe("RBAC disabled", () => {+ // OPENRAG_RBAC_ENFORCE=false — the pre-RBAC release behaviour, where an+ // authenticated user has full access and the permission set stays empty.+ it("grants every permission despite an empty permission set", async () => {+ const { result } = await renderAuth(authPresets.rbacDisabled);++ expect(result.current.rbacEnforced).toBe(false);+ expect(result.current.permissions.size).toBe(0);+ expect(result.current.can("config:write")).toBe(true);+ });++ it("defaults rbacEnforced to true when the backend omits the field", async () => {+ // Older backends do not send `rbac_enforced`. Defaulting to false would+ // silently open RBAC-gated UI against a backend that is enforcing.+ const { result } = await renderAuth(+ withAuth(authPresets.viewer, { usersMe: { rbac_enforced: undefined } }),+ );++ expect(result.current.rbacEnforced).toBe(true);+ expect(result.current.can("config:write")).toBe(false);+ });+ });++ describe("IBM auth mode", () => {+ it("takes precedence and reports cloud context", async () => {+ const { result } = await renderAuth(authPresets.ibmAuthMode);++ expect(result.current.isIbmAuthMode).toBe(true);+ expect(result.current.isNoAuthMode).toBe(false);+ expect(result.current.cloudContext).toBe(true);+ expect(result.current.isAuthenticated).toBe(true);+ });++ it("wins over no_auth_mode when the backend sends both", async () => {+ // The flags are checked in order in `checkAuth`; this pins that order so+ // a reordering does not silently drop a cloud tenant into no-auth mode.+ const { result } = await renderAuth(+ withAuth(authPresets.ibmAuthMode, { me: { no_auth_mode: true } }),+ );++ expect(result.current.isIbmAuthMode).toBe(true);+ expect(result.current.isNoAuthMode).toBe(false);+ });+ });++ describe("unauthenticated", () => {+ it("resolves with no permissions when /api/users/me is refused", async () => {+ const { result } = await renderAuth(authPresets.unauthenticated);++ expect(result.current.isAuthenticated).toBe(false);+ expect(result.current.permissions.size).toBe(0);+ expect(result.current.roles).toEqual([]);+ expect(result.current.can("config:read")).toBe(false);+ // Must still flip, or consumers that wait on it hang forever.+ expect(result.current.permissionsResolved).toBe(true);+ });+ });++ describe("onboarding status", () => {+ it("reads onboarded and the current step", async () => {+ const { result } = await renderAuth(+ withAuth(authPresets.admin, {+ onboardingStatus: { onboarded: false, current_step: 2 },+ }),+ );++ expect(result.current.isOnboarded).toBe(false);+ expect(result.current.onboardingStep).toBe(2);+ });++ it("leaves isOnboarded null when the endpoint fails", async () => {+ // Deliberately conservative: a failed status call must not be read as+ // "not onboarded" and bounce a working install into the wizard.+ const { result } = await renderAuth(authPresets.admin, [+ http.get("/api/onboarding-status", () =>+ HttpResponse.json({ detail: "boom" }, { status: 500 }),+ ),+ ]);++ expect(result.current.isOnboarded).toBeNull();+ });+ });++ describe("refreshAuth", () => {+ it("picks up a user who signed in after mount", async () => {+ const { result } = await renderAuth(authPresets.unauthenticated);+ expect(result.current.isAuthenticated).toBe(false);++ const signedIn: User = makeUser({ name: "Signed In" });+ server.use(+ http.get("/api/auth/me", () =>+ HttpResponse.json({ authenticated: true, user: signedIn }),+ ),+ http.get("/api/users/me", () =>+ HttpResponse.json({+ permissions: ["config:read"],+ roles: ["viewer"],+ }),+ ),+ );++ await result.current.refreshAuth();++ await waitFor(() => {+ expect(result.current.user?.name).toBe("Signed In");+ expect(result.current.can("config:read")).toBe(true);+ });+ });+ });++ describe("logout", () => {+ it("clears the user", async () => {+ const { result } = await renderAuth(authPresets.admin);+ expect(result.current.isAuthenticated).toBe(true);++ await result.current.logout();++ await waitFor(() => {+ expect(result.current.isAuthenticated).toBe(false);+ expect(result.current.user).toBeNull();+ });+ });++ it("is a no-op in no-auth mode", async () => {+ // There is no session to end; calling the endpoint would 404.+ const { result } = await renderAuth(authPresets.noAuthMode);++ await result.current.logout();++ expect(result.current.isNoAuthMode).toBe(true);+ expect(result.current.can("config:write")).toBe(true);+ });+ });+});diff --git a/frontend/contexts/auth-context.tsx b/frontend/contexts/auth-context.tsxindex 937bae8b1..c61d30b00 100644--- a/frontend/contexts/auth-context.tsx+++ b/frontend/contexts/auth-context.tsx@@ -12,7 +12,7 @@ import { hasRbacPermission } from "@/lib/brand";import type { RunMode } from "@/lib/constants";import { encodeBase64 } from "@/lib/utils";-interface User {+export interface User {user_id: string;email: string;name: string;diff --git a/frontend/hooks/useChatStreaming.test.tsx b/frontend/hooks/useChatStreaming.test.tsxindex ceb73ca22..a5929feb5 100644--- a/frontend/hooks/useChatStreaming.test.tsx+++ b/frontend/hooks/useChatStreaming.test.tsx@@ -1,4 +1,5 @@import { HttpResponse, http } from "msw";+import type { ReactNode } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";import { server } from "@/test-utils/msw/server";import { act, renderHook, waitFor } from "@/test-utils/render";@@ -20,8 +21,14 @@ import { useChatStreaming } from "./useChatStreaming";*/const refreshConversations = vi.fn();+// `ChatProvider` is stubbed as a passthrough only because+// `test-utils/render.tsx` imports it from this module to build its provider+// stack. This test never mounts it, so a passthrough is honest — and cheaper+// than `importOriginal`, whose async factory resolves after the module graph+// has already bound the real export here.vi.mock("@/contexts/chat-context", () => ({useChat: () => ({ refreshConversations }),+ ChatProvider: ({ children }: { children: ReactNode }) => children,}));const ENDPOINT = "/api/langflow";diff --git a/frontend/test-utils/fixtures/auth.ts b/frontend/test-utils/fixtures/auth.tsnew file mode 100644index 000000000..96c1bba16--- /dev/null+++ b/frontend/test-utils/fixtures/auth.ts@@ -0,0 +1,200 @@+/**+ * Fixtures for the auth boot sequence.+ *+ * `AuthProvider` is the outermost context in `app/layout.tsx` and 33 files+ * consume `useAuth()`, so almost every component test starts by deciding who+ * is signed in. That decision is expressed here as an `AuthScenario` — the+ * three payloads the provider fetches on mount — rather than as a fake context+ * value, so the real provider logic (mode precedence, permission resolution,+ * RBAC defaulting) stays under test in every test that uses it.+ *+ * Turn a scenario into MSW handlers with `authHandlers()` from+ * `test-utils/msw/auth.ts`; `renderWithProviders({ auth })` does it for you.+ */+import type { User } from "@/contexts/auth-context";+import type { RunMode } from "@/lib/constants";++/**+ * GET /api/auth/me.+ *+ * Only the fields `checkAuth` in `contexts/auth-context.tsx` actually reads.+ * The mode flags are mutually exclusive in practice and the provider checks+ * them in this order: `ibm_auth_mode`, then `no_auth_mode`, then+ * `authenticated`.+ */+export interface AuthMeResponse {+ authenticated?: boolean;+ user?: User | null;+ no_auth_mode?: boolean;+ ibm_auth_mode?: boolean;+ version?: string;+ run_mode?: RunMode;+}++/** GET /api/users/me — permissions, roles, and the RBAC/cloud flags. */+export interface UsersMeResponse {+ permissions?: string[];+ roles?: string[];+ rbac_enforced?: boolean;+ cloud_context?: boolean;+}++/** GET /api/onboarding-status — public, no auth required. */+export interface OnboardingStatusResponse {+ onboarded?: boolean;+ current_step?: number | string | null;+}++/**+ * The complete boot surface of `AuthProvider`.+ *+ * `usersMe: null` means the endpoint answers 403 — the real shape for a+ * request that is not authenticated, and the branch where the provider resets+ * permission state.+ */+export interface AuthScenario {+ me: AuthMeResponse;+ usersMe: UsersMeResponse | null;+ onboardingStatus: OnboardingStatusResponse;+}++export function makeUser(overrides: Partial<User> = {}): User {+ return {+ user_id: "user-1",+ email: "[email protected]",+ name: "Test User",+ provider: "google",+ ...overrides,+ };+}++/**+ * Every permission the UI gates on today. `authPresets.admin` grants these, so+ * a test that only needs "a signed-in user who can see everything" does not+ * have to enumerate them.+ */+export const ALL_PERMISSIONS = [+ "config:read",+ "config:write",+ "flows:read",+ "flows:write",+ "connectors:manage:access",+ "users:read",+ "users:write",+ "documents:read",+ "documents:write",+] as const;++function scenario(+ me: AuthMeResponse,+ usersMe: UsersMeResponse | null,+ onboardingStatus: OnboardingStatusResponse = {+ onboarded: true,+ current_step: null,+ },+): AuthScenario {+ return { me, usersMe, onboardingStatus };+}++/**+ * Named starting points, one per branch of `checkAuth`.+ *+ * Compose with `withAuth(preset, { ... })` for one-field variations rather+ * than adding a preset per permutation.+ */+export const authPresets = {+ /** Signed in, RBAC on, every permission granted. */+ admin: scenario(+ { authenticated: true, user: makeUser(), version: "1.0.0" },+ {+ permissions: [...ALL_PERMISSIONS],+ roles: ["admin"],+ rbac_enforced: true,+ cloud_context: false,+ },+ ),++ /** Signed in, RBAC on, read-only. The interesting negative case for gates. */+ viewer: scenario(+ {+ authenticated: true,+ user: makeUser({ user_id: "user-2", name: "View Only" }),+ version: "1.0.0",+ },+ {+ permissions: ["config:read", "flows:read", "documents:read"],+ roles: ["viewer"],+ rbac_enforced: true,+ cloud_context: false,+ },+ ),++ /**+ * OPENRAG_AUTH_ENABLED=false. No user object, but `can()` returns true for+ * everything — the pre-auth release behaviour. A frequent source of gating+ * bugs, because "no user" and "no permissions" both look falsy.+ */+ noAuthMode: scenario(+ { no_auth_mode: true, authenticated: false, version: "1.0.0" },+ { permissions: [], roles: [], rbac_enforced: true, cloud_context: false },+ ),++ /** IBM/SaaS: cloud brand, cloud policy context, signed in. */+ ibmAuthMode: scenario(+ {+ ibm_auth_mode: true,+ authenticated: true,+ user: makeUser({ provider: "ibm" }),+ version: "1.0.0",+ },+ {+ permissions: [...ALL_PERMISSIONS],+ roles: ["admin"],+ rbac_enforced: true,+ cloud_context: true,+ },+ ),++ /** Auth enabled, nobody signed in. `/api/users/me` answers 403. */+ unauthenticated: scenario(+ { authenticated: false, user: null, version: "1.0.0" },+ null,+ ),++ /** Signed in with OPENRAG_RBAC_ENFORCE=false — `can()` is always true. */+ rbacDisabled: scenario(+ { authenticated: true, user: makeUser(), version: "1.0.0" },+ {+ permissions: [],+ roles: [],+ rbac_enforced: false,+ cloud_context: false,+ },+ ),+} satisfies Record<string, AuthScenario>;++export type AuthPresetName = keyof typeof authPresets;++/** Shallow-merges each payload, so a test can vary one field of a preset. */+export function withAuth(+ base: AuthScenario,+ overrides: {+ me?: Partial<AuthMeResponse>;+ usersMe?: Partial<UsersMeResponse> | null;+ onboardingStatus?: Partial<OnboardingStatusResponse>;+ },+): AuthScenario {+ return {+ me: { ...base.me, ...overrides.me },+ usersMe:+ overrides.usersMe === null+ ? null+ : overrides.usersMe+ ? { ...(base.usersMe ?? {}), ...overrides.usersMe }+ : base.usersMe,+ onboardingStatus: {+ ...base.onboardingStatus,+ ...overrides.onboardingStatus,+ },+ };+}diff --git a/frontend/test-utils/fixtures/index.ts b/frontend/test-utils/fixtures/index.tsnew file mode 100644index 000000000..9298c7973--- /dev/null+++ b/frontend/test-utils/fixtures/index.ts@@ -0,0 +1,3 @@+export * from "./auth";+export * from "./settings";+export * from "./task";diff --git a/frontend/test-utils/fixtures/settings.ts b/frontend/test-utils/fixtures/settings.tsnew file mode 100644index 000000000..e255e215b--- /dev/null+++ b/frontend/test-utils/fixtures/settings.ts@@ -0,0 +1,32 @@+/**+ * Fixtures for GET /api/settings.+ *+ * Needed by more tests than it looks: `useOnboardingState()` reads+ * `settings.onboarding.current_step`, and both `TaskProvider` and+ * `ChatProvider` call it, so mounting either one hits this endpoint.+ */+import type { Settings } from "@/app/api/queries/useGetSettingsQuery";+import { TOTAL_ONBOARDING_STEPS } from "@/lib/constants";++/**+ * Onboarding finished. This is the default because an *active* onboarding+ * changes behaviour in both providers (task polling, chat routing), and a test+ * should opt into that rather than inherit it.+ */+export function makeSettings(overrides: Partial<Settings> = {}): Settings {+ return {+ langflow_url: "http://localhost:7860",+ flow_id: "flow-1",+ ingest_flow_id: "ingest-flow-1",+ onboarding: { current_step: TOTAL_ONBOARDING_STEPS },+ providers: {},+ knowledge: {},+ agent: {},+ ...overrides,+ };+}++/** Settings with onboarding still in progress at `step`. */+export function makeOnboardingSettings(step = 0): Settings {+ return makeSettings({ onboarding: { current_step: step } });+}diff --git a/frontend/test-utils/fixtures/task.ts b/frontend/test-utils/fixtures/task.tsnew file mode 100644index 000000000..d80b1ccf7--- /dev/null+++ b/frontend/test-utils/fixtures/task.ts@@ -0,0 +1,92 @@+/**+ * Fixtures for `Task` / `TaskFileEntry`.+ *+ * `Task` has 13 optional fields and `files` is a keyed map, so building one+ * inline costs more than the assertion it supports. These builders default to+ * a coherent single-file task and let a test name only what it is testing.+ *+ * Typed against the app's own exported interfaces so a change to the response+ * shape breaks `npm run typecheck` here rather than silently passing.+ */+import type {+ Task,+ TaskFileEntry,+ TasksResponse,+} from "@/app/api/queries/useGetTasksQuery";++/** Fixed so tests never depend on wall-clock ordering. */+const CREATED_AT = "2026-01-01T00:00:00Z";+const UPDATED_AT = "2026-01-01T00:00:05Z";++export function makeTaskFile(+ overrides: Partial<TaskFileEntry> = {},+): TaskFileEntry {+ return {+ status: "completed",+ filename: "report.pdf",+ phase: "complete",+ created_at: CREATED_AT,+ updated_at: UPDATED_AT,+ ...overrides,+ };+}++/**+ * A failed file with the classification fields the enhanced API adds. Split+ * out because `lib/task-error-display.ts` and `lib/task-utils.ts` branch on+ * `failure_phase` / `actionable_by`, and forgetting them yields a file that+ * looks failed but classifies as "unknown".+ */+export function makeFailedTaskFile(+ overrides: Partial<TaskFileEntry> = {},+): TaskFileEntry {+ return makeTaskFile({+ status: "failed",+ component: "docling",+ failure_phase: "parsing",+ actionable_by: "RETRYABLE",+ user_facing_message: "Could not parse the document.",+ error: "parse error",+ ...overrides,+ });+}++/**+ * Builds a task from a `path -> entry` map, deriving the file counts so they+ * agree with `files`. Pass counts explicitly only when testing what the UI+ * does with an inconsistent payload.+ */+export function makeTask(+ overrides: Partial<Task> & { files?: Record<string, TaskFileEntry> } = {},+): Task {+ const files = overrides.files ?? {+ "/data/report.pdf": makeTaskFile(),+ };+ const entries = Object.values(files);+ const isTerminal = (s: TaskFileEntry["status"]) =>+ s === "completed" || s === "skipped" || s === "failed" || s === "error";++ return {+ task_id: "task-1",+ status: "completed",+ created_at: CREATED_AT,+ updated_at: UPDATED_AT,+ total_files: entries.length,+ processed_files: entries.filter((f) => isTerminal(f.status)).length,+ successful_files: entries.filter((f) => f.status === "completed").length,+ failed_files: entries.filter(+ (f) => f.status === "failed" || f.status === "error",+ ).length,+ running_files: entries.filter(+ (f) => f.status === "running" || f.status === "processing",+ ).length,+ pending_files: entries.filter((f) => f.status === "pending").length,+ ...overrides,+ files,+ };+}++/** The GET /api/tasks/enhanced envelope. */+export function makeTasksResponse(tasks: Task[] = []): TasksResponse {+ return { tasks };+}diff --git a/frontend/test-utils/msw/auth.ts b/frontend/test-utils/msw/auth.tsnew file mode 100644index 000000000..8e7bb57f0--- /dev/null+++ b/frontend/test-utils/msw/auth.ts@@ -0,0 +1,49 @@+/**+ * MSW handlers for the `AuthProvider` boot sequence.+ *+ * `renderWithProviders({ auth })` installs these, so most tests never call+ * this module directly. Reach for `authHandlers()` when you need a scenario+ * active before render — e.g. seeding the query cache — or when asserting on+ * the requests themselves.+ *+ * ── Why these must always answer ────────────────────────────────────────────+ * `checkAuth` in `contexts/auth-context.tsx` reschedules itself via+ * `setTimeout(checkAuth, 2000)` on a 5xx or a thrown fetch. Under+ * `onUnhandledRequest: "error"` an unhandled `/api/auth/me` therefore does not+ * fail the test — it retries forever until the test times out. That is why+ * `handlers.ts` ships a default auth scenario rather than leaving auth+ * unmocked. A test that deliberately exercises the retry path needs+ * `vi.useFakeTimers()`.+ */+import { HttpResponse, http } from "msw";+import type {+ AuthMeResponse,+ AuthScenario,+ OnboardingStatusResponse,+ UsersMeResponse,+} from "@/test-utils/fixtures/auth";++export function authHandlers(scenario: AuthScenario) {+ return [+ http.get("/api/auth/me", () =>+ HttpResponse.json<AuthMeResponse>(scenario.me),+ ),++ // 403 is what the backend returns for an unauthenticated caller, and the+ // branch where the provider clears permissions. `null` in the scenario+ // means exactly that.+ http.get("/api/users/me", () =>+ scenario.usersMe === null+ ? HttpResponse.json({ detail: "Not authenticated" }, { status: 403 })+ : HttpResponse.json<UsersMeResponse>(scenario.usersMe),+ ),++ http.get("/api/onboarding-status", () =>+ HttpResponse.json<OnboardingStatusResponse>(scenario.onboardingStatus),+ ),++ // Not part of boot, but `logout()` calls it and an unhandled POST would+ // surface as an "unhandled request" error rather than a logout assertion.+ http.post("/api/auth/logout", () => HttpResponse.json({ success: true })),+ ];+}diff --git a/frontend/test-utils/msw/handlers.ts b/frontend/test-utils/msw/handlers.tsindex 0bd0d4777..bf2cea64b 100644--- a/frontend/test-utils/msw/handlers.ts+++ b/frontend/test-utils/msw/handlers.ts@@ -1,5 +1,9 @@import { HttpResponse, http } from "msw";+import type { Settings } from "@/app/api/queries/useGetSettingsQuery";import type { TasksResponse } from "@/app/api/queries/useGetTasksQuery";+import { authPresets } from "@/test-utils/fixtures/auth";+import { makeSettings } from "@/test-utils/fixtures/settings";+import { authHandlers } from "./auth";/*** Default handlers, shared by every test.@@ -10,9 +14,19 @@ import type { TasksResponse } from "@/app/api/queries/useGetTasksQuery";* `location.origin`, which vitest.config.mts pins to http://localhost:3000 via* `environmentOptions.jsdom.url`.*- * Keep this list minimal: only endpoints many tests need in a boring happy-path- * shape. Anything test-specific belongs in that test via `server.use(...)`,- * which setup.ts resets after every test.+ * ── What belongs here ───────────────────────────────────────────────────────+ * Only the endpoints a *provider* hits on mount. Because `renderWithProviders`+ * mounts the real providers, every one of these is fetched by tests that never+ * mention auth or tasks, and an unmocked one fails the test under+ * `onUnhandledRequest: "error"` (or, for `/api/auth/me`, hangs — see+ * `./auth.ts`). Anything a *component* fetches belongs in that component's+ * test via `renderWithProviders(ui, { handlers })`, which applies them after+ * the auth scenario so they win over it; setup.ts resets them after every+ * test.+ *+ * The default scenario is deliberately the boring one: an admin, RBAC on,+ * onboarding finished, nothing in flight. Tests that care select another via+ * `renderWithProviders({ auth: authPresets.viewer })`.** ── On typing (see R4 in local/plans/frontend-testing-foundation.md) ─────────* Handler bodies are annotated with the frontend's own exported response@@ -32,5 +46,12 @@ import type { TasksResponse } from "@/app/api/queries/useGetTasksQuery";const emptyTasks: TasksResponse = { tasks: [] };export const handlers = [+ // AuthProvider: /api/auth/me, /api/users/me, /api/onboarding-status.+ ...authHandlers(authPresets.admin),++ // TaskProvider.http.get("/api/tasks/enhanced", () => HttpResponse.json(emptyTasks)),++ // useOnboardingState(), reached through both TaskProvider and ChatProvider.+ http.get("/api/settings", () => HttpResponse.json<Settings>(makeSettings())),];diff --git a/frontend/test-utils/render.tsx b/frontend/test-utils/render.tsxindex 1cb9669e7..d9aaa9679 100644--- a/frontend/test-utils/render.tsx+++ b/frontend/test-utils/render.tsx@@ -1,5 +1,20 @@/**- * Test render helper.+ * Test render helpers.+ *+ * ── The problem this solves ─────────────────────────────────────────────────+ * `app/layout.tsx` wraps the app in eight nested contexts, and every one of+ * their hooks throws `"useX must be used within a XProvider"` when absent.+ * 69 of the 124 client components consume at least one of them, so without a+ * shared harness each component test opens by hand-rolling a provider stack —+ * which is why the suite has so far only reached pure helpers in `lib/`.+ *+ * ── The approach ────────────────────────────────────────────────────────────+ * These are the REAL providers, not fake context values. State is driven by+ * MSW payloads, the same way the app drives it, so `AuthProvider`'s mode+ * precedence and permission resolution stay under test in every test that+ * mounts it — consistent with the repo's rule about not mocking away+ * `app/api/queries/`. A component test failing because a provider is broken is+ * the intended behaviour: that is a bug the user would have hit.** Deliberately does NOT use `app/providers.tsx` or* `app/api/get-query-client.ts`:@@ -10,13 +25,33 @@* - `getQueryClient()` memoizes a single client in browser environments, so* cache would leak between tests in the same file.*- * Each render therefore gets a fresh QueryClient with retries off, so a test- * asserting an error state fails fast instead of waiting out react-query's- * default retry/backoff.+ * ── Usage ───────────────────────────────────────────────────────────────────+ * renderWithProviders(<ConnectorCard />, {+ * providers: ["auth", "brand", "task"],+ * auth: authPresets.viewer,+ * brand: "ibm",+ * });+ *+ * Provider state resolves asynchronously (auth alone is three fetches), so the+ * first paint is always the loading state. Assert with `await screen.findBy…`+ * or `await waitFor(...)`, never a bare `getBy…` on the first tick.*/import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { type RenderOptions, render } from "@testing-library/react";-import type { ReactElement, ReactNode } from "react";+import type { RequestHandler } from "msw";+import type { ComponentType, ReactElement, ReactNode } from "react";+import { TooltipProvider } from "@/components/ui/tooltip";+import { AuthProvider } from "@/contexts/auth-context";+import { BrandProvider } from "@/contexts/brand-context";+import { ChatProvider } from "@/contexts/chat-context";+import { ConsoleStatusProvider } from "@/contexts/console-status-context";+import { KnowledgeFilterProvider } from "@/contexts/knowledge-filter-context";+import { TaskProvider } from "@/contexts/task-context";+import { UnsavedChangesProvider } from "@/contexts/unsaved-changes-context";+import type { Brand } from "@/lib/brand";+import type { AuthScenario } from "@/test-utils/fixtures/auth";+import { authHandlers } from "@/test-utils/msw/auth";+import { server } from "@/test-utils/msw/server";export function createTestQueryClient() {return new QueryClient({@@ -32,12 +67,156 @@ export function createTestQueryClient() {});}-interface RenderWithProvidersOptions extends Omit<RenderOptions, "wrapper"> {+export type ProviderName =+ | "tooltip"+ | "auth"+ | "brand"+ | "task"+ | "knowledgeFilter"+ | "consoleStatus"+ | "chat"+ | "unsavedChanges";++/**+ * Which providers each one needs beneath it.+ *+ * Listing a provider pulls its dependencies in automatically, so a test names+ * what the component uses rather than what the tree happens to require —+ * `providers: ["consoleStatus"]` is enough, even though it reads `useAuth`,+ * `useTask`, and `useKnowledgeFilter`.+ */+const PROVIDER_DEPENDENCIES: Record<ProviderName, ProviderName[]> = {+ tooltip: [],+ auth: [],+ brand: ["auth"],+ task: ["auth"],+ knowledgeFilter: [],+ consoleStatus: ["auth", "knowledgeFilter", "task"],+ chat: [],+ unsavedChanges: [],+};++/**+ * Nesting order, outermost first. Matches `app/layout.tsx` exactly — every+ * dependency above happens to be satisfied by that order, and keeping the two+ * in step means a test tree behaves like the real one.+ */+const PROVIDER_ORDER: ProviderName[] = [+ "tooltip",+ "auth",+ "brand",+ "task",+ "knowledgeFilter",+ "consoleStatus",+ "chat",+ "unsavedChanges",+];++const PROVIDER_COMPONENTS: Record<+ ProviderName,+ ComponentType<{ children: ReactNode }>+> = {+ tooltip: TooltipProvider,+ auth: AuthProvider,+ brand: BrandProvider,+ task: TaskProvider,+ knowledgeFilter: KnowledgeFilterProvider,+ consoleStatus: ConsoleStatusProvider,+ chat: ChatProvider,+ unsavedChanges: UnsavedChangesProvider,+};++function resolveProviders(requested: ProviderName[]): ProviderName[] {+ const selected = new Set<ProviderName>();++ const visit = (name: ProviderName) => {+ if (selected.has(name)) return;+ selected.add(name);+ for (const dep of PROVIDER_DEPENDENCIES[name]) visit(dep);+ };+ for (const name of requested) visit(name);++ return PROVIDER_ORDER.filter((name) => selected.has(name));+}++export interface ProviderOptions {+ /**+ * Contexts the component under test needs. Dependencies are added+ * automatically. `"all"` mounts the full `app/layout.tsx` stack — use it for+ * page-level tests; naming the two or three a component actually uses keeps+ * failures readable.+ */+ providers?: ProviderName[] | "all";+ /**+ * Auth scenario, installed as MSW handlers for `/api/auth/me`,+ * `/api/users/me`, and `/api/onboarding-status`. Defaults to whatever+ * `handlers.ts` ships (an admin with RBAC on). See+ * `test-utils/fixtures/auth.ts` for the presets.+ */+ auth?: AuthScenario;+ /**+ * Seeds the brand `BrandProvider` reads from localStorage. Note IBM auth+ * mode forces `"ibm"` regardless — set the auth scenario, not this, when+ * testing that path.+ */+ brand?: Brand;+ /**+ * Extra MSW handlers for this render, applied AFTER the auth scenario so+ * they win over it.+ *+ * Use this rather than calling `server.use()` in the test body: the harness+ * installs the auth scenario at render time, which would otherwise be+ * prepended over an override the test set up earlier. Handlers that have+ * nothing to do with the provider stack can still go through `server.use()`+ * directly.+ */+ handlers?: RequestHandler[];queryClient?: QueryClient;}+interface RenderWithProvidersOptions+ extends Omit<RenderOptions, "wrapper">,+ ProviderOptions {}++function applyProviderOptions({ auth, brand, handlers }: ProviderOptions) {+ // Prepended, so it wins over the defaults in handlers.ts. setup.ts calls+ // server.resetHandlers() after every test, so this does not leak.+ if (auth) server.use(...authHandlers(auth));+ // After the scenario, so a per-render override beats it. MSW resolves with+ // the most recently prepended matching handler.+ if (handlers?.length) server.use(...handlers);+ // Written before render because BrandProvider reads localStorage in its+ // mount effect.+ if (brand) localStorage.setItem("brand", brand);+}++function buildWrapper(+ queryClient: QueryClient,+ providers: ProviderName[] | "all",+) {+ const active = resolveProviders(+ providers === "all" ? PROVIDER_ORDER : providers,+ );++ return function Wrapper({ children }: { children: ReactNode }) {+ // Reduced from the innermost outwards, so `active`'s order is the nesting+ // order in the rendered tree.+ const tree = active.reduceRight<ReactNode>((acc, name) => {+ const Provider = PROVIDER_COMPONENTS[name];+ // Keyed by provider name: these nest rather than sit as siblings, but a+ // stable key keeps React from remounting the whole stack if the set of+ // active providers ever changes between renders.+ return <Provider key={name}>{acc}</Provider>;+ }, children);++ return (+ <QueryClientProvider client={queryClient}>{tree}</QueryClientProvider>+ );+ };+}+/**- * Renders `ui` inside a fresh react-query provider.+ * Renders `ui` inside a fresh react-query provider and the requested contexts.** Returns the QueryClient alongside RTL's usual result so a test can seed or* inspect the cache directly when it needs to.@@ -46,18 +225,21 @@ export function renderWithProviders(ui: ReactElement,{queryClient = createTestQueryClient(),+ providers = [],+ auth,+ brand,+ handlers,...options}: RenderWithProvidersOptions = {},) {- function Wrapper({ children }: { children: ReactNode }) {- return (- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>- );- }+ applyProviderOptions({ auth, brand, handlers });return {queryClient,- ...render(ui, { wrapper: Wrapper, ...options }),+ ...render(ui, {+ wrapper: buildWrapper(queryClient, providers),+ ...options,+ }),};}@@ -65,13 +247,25 @@ export function renderWithProviders(* Wrapper for `renderHook`, which takes a component rather than a render call.** Each call builds its own QueryClient, so hooks under test never share cache.+ * Takes the same provider options as `renderWithProviders`:+ *+ * renderHook(() => usePermissions(), {+ * wrapper: createQueryWrapper({ providers: ["auth"], auth: authPresets.viewer }),+ * });*/-export function createQueryWrapper(queryClient = createTestQueryClient()) {- return function QueryWrapper({ children }: { children: ReactNode }) {- return (- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>- );- };+export function createQueryWrapper(+ options: ProviderOptions | QueryClient = {},+) {+ // Historically this took a QueryClient positionally; keep that working.+ const opts: ProviderOptions =+ options instanceof QueryClient ? { queryClient: options } : options;++ applyProviderOptions(opts);++ return buildWrapper(+ opts.queryClient ?? createTestQueryClient(),+ opts.providers ?? [],+ );}export * from "@testing-library/react";diff --git a/frontend/test-utils/router.ts b/frontend/test-utils/router.tsnew file mode 100644index 000000000..e10ce260b--- /dev/null+++ b/frontend/test-utils/router.ts@@ -0,0 +1,114 @@+/**+ * Shared `next/navigation` test double.+ *+ * 28 files import from `next/navigation` (48 `useRouter`, 14 `usePathname`,+ * 12 `useSearchParams`), and outside a Next app-router tree those hooks throw+ * or return null. Every component test would otherwise open with the same+ * `vi.mock("next/navigation", ...)` block — and each copy would drift.+ *+ * The mock is registered once, globally, in `test-utils/setup.ts`. This module+ * holds the state behind it so a test can drive and assert navigation:+ *+ * setMockLocation({ pathname: "/knowledge", searchParams: { id: "f1" } });+ * ...+ * expect(mockRouter.push).toHaveBeenCalledWith("/chat");+ *+ * `resetMockRouter()` runs in `afterEach`, so state never leaks between tests.+ *+ * Note this is a genuine `vi.mock` — the one place the repo's "mock the+ * network, not the module" rule does not apply, because `next/navigation` is+ * framework plumbing with no network under it to intercept. Navigation that+ * must actually re-render a route belongs in Playwright.+ */+import { vi } from "vitest";++const DEFAULT_PATHNAME = "/";++export const mockRouter = {+ push: vi.fn(),+ replace: vi.fn(),+ refresh: vi.fn(),+ back: vi.fn(),+ forward: vi.fn(),+ prefetch: vi.fn(),+};++let pathname = DEFAULT_PATHNAME;+let searchParams = new URLSearchParams();+let params: Record<string, string | string[]> = {};++export interface MockLocation {+ pathname?: string;+ /** Object form is converted to `URLSearchParams`; a string is parsed. */+ searchParams?: Record<string, string> | string;+ /** Dynamic route segments, for `useParams()`. */+ params?: Record<string, string | string[]>;+}++export function setMockLocation(location: MockLocation) {+ if (location.pathname !== undefined) pathname = location.pathname;+ if (location.searchParams !== undefined) {+ searchParams =+ typeof location.searchParams === "string"+ ? new URLSearchParams(location.searchParams)+ : new URLSearchParams(location.searchParams);+ }+ if (location.params !== undefined) params = location.params;+}++export function resetMockRouter() {+ for (const fn of Object.values(mockRouter)) fn.mockClear();+ // `redirect` and `notFound` live on `navigationMock`, not `mockRouter`, and+ // would otherwise carry call history across tests.+ navigationMock.redirect.mockClear();+ navigationMock.notFound.mockClear();+ pathname = DEFAULT_PATHNAME;+ searchParams = new URLSearchParams();+ params = {};+}++/**+ * `redirect()` and `notFound()` are typed `never` in Next: they throw a+ * control-flow error the framework catches, so nothing after the call runs. A+ * bare `vi.fn()` returns `undefined` instead, and code under test would sail+ * past a guard that should have bailed out — every branch below a `redirect()`+ * would execute. These sentinels restore the terminating behaviour, and are+ * distinct so a test can tell which one fired:+ *+ * await expect(SettingsTabPage({ params })).rejects.toBeInstanceOf(+ * MockRedirectError,+ * );+ * expect(navigationMock.redirect).toHaveBeenCalledWith("/settings/connectors");+ */+export class MockRedirectError extends Error {+ constructor(readonly url: string) {+ super(`NEXT_REDIRECT: ${url}`);+ this.name = "MockRedirectError";+ }+}++export class MockNotFoundError extends Error {+ constructor() {+ super("NEXT_NOT_FOUND");+ this.name = "MockNotFoundError";+ }+}++/**+ * The module shape handed to `vi.mock("next/navigation")`.+ *+ * The hooks read the module-level state at call time rather than closing over+ * it, so `setMockLocation` inside a test affects the next render.+ */+export const navigationMock = {+ useRouter: () => mockRouter,+ usePathname: () => pathname,+ useSearchParams: () => searchParams,+ useParams: () => params,+ redirect: vi.fn((url: string): never => {+ throw new MockRedirectError(url);+ }),+ notFound: vi.fn((): never => {+ throw new MockNotFoundError();+ }),+};diff --git a/frontend/test-utils/setup.ts b/frontend/test-utils/setup.tsindex 09958a039..1ecf05719 100644--- a/frontend/test-utils/setup.ts+++ b/frontend/test-utils/setup.ts@@ -9,11 +9,26 @@ import "@testing-library/jest-dom/vitest";import { cleanup } from "@testing-library/react";import { afterAll, afterEach, beforeAll, vi } from "vitest";import { server } from "./msw/server";+import { navigationMock, resetMockRouter } from "./router";++// Registered here rather than per test file so all 28 next/navigation+// consumers share one router double. A setupFile mock applies to every test+// file in the run. See test-utils/router.ts for why this is a vi.mock at all.+vi.mock("next/navigation", async () => navigationMock);// RTL auto-cleans when it detects a global afterEach, but we register it// explicitly so behaviour does not silently change if `globals` is turned off.afterEach(() => {cleanup();+ resetMockRouter();+ // BrandProvider persists the active brand, and auth-context writes several+ // `auth_*` keys during login. jsdom keeps localStorage for the whole file,+ // so without this a brand set in one test leaks into the next.+ localStorage.clear();+ sessionStorage.clear();+ // BrandProvider stamps `data-theme="ibm"` on <html> and only removes it on+ // re-render, so a cloud-brand test would otherwise leave the attribute set.+ document.documentElement.removeAttribute("data-theme");});// `onUnhandledRequest: "error"` makes an unmocked call fail loudly and