All files / src/test harness.tsx

100% Statements 15/15
100% Branches 10/10
100% Functions 7/7
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141                                                                                      42x     42x   42x 278x                       492x                   492x                                           492x                                 351x 637x 286x       351x 351x                                       42x      
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider } from "chainr-frontend-shared";
import {
  act,
  render,
  waitFor,
  type RenderResult,
} from "@testing-library/react";
import { WorkspaceProvider, type WorkspaceInfo } from "@/context/WorkspaceContext";
import { PERSONAL_WORKSPACE, WorkspaceRef } from "@/routes/workspace";
import React from "react";
import { MemoryRouter, Route, Routes } from "react-router-dom";
 
/**
 * Render a page the way the app does, with every provider it expects.
 *
 * Page components reach for react-query, the router and the theme, and a page
 * that is missing one of them throws in a way that looks like a bug in the
 * page. Assembling them once here means a smoke test asserts what it means to
 * assert — that the page renders — rather than that the harness is complete.
 */
export interface RenderPageOptions {
  /** The workspace the page is showing (Personal when omitted). */
  workspace?: WorkspaceRef;
  /** What svc-core says of it — the viewer's role there, say. */
  workspaceInfo?: WorkspaceInfo;
  /** Route pattern the page is mounted at, e.g. `/agents/id/:agentId`. */
  path?: string;
  /** Concrete URL to render at. Defaults to `path` with params filled in. */
  url?: string;
}
 
/**
 * Marks the Suspense fallback so a test can tell "still loading the chunk"
 * from "rendered".
 *
 * Without it a lazy page's test passes against an empty fallback: one
 * macrotask is not enough for a dynamic import to resolve, so the page never
 * mounts and a smoke test that only asserts "it did not throw" is satisfied by
 * nothing at all. That is exactly what happened when routes became lazy — 83
 * page tests went green while testing nothing, and only the coverage report
 * noticed.
 */
export const LAZY_PENDING_TESTID = "lazy-page-pending";
 
/** Route params are base64 ids in this app; give them something decodable. */
const PARAM_VALUE = btoa("00000000-0000-4000-8000-000000000000");
 
const fillParams = (path: string) =>
  path.replace(/:([A-Za-z0-9_]+)/g, () => PARAM_VALUE).replace(/\/?\*$/, "");
 
/** What a rendered page gives a test back: the DOM, and the query client
 *  driving it — so a test can wait for the page's data instead of guessing. */
export interface RenderedPage extends RenderResult {
  client: QueryClient;
}
 
export function renderPage(
  element: React.ReactNode,
  { path = "/", url, workspace, workspaceInfo }: RenderPageOptions = {},
): RenderedPage {
  const client = new QueryClient({
    defaultOptions: {
      // A smoke test should see the first render, not a retry storm, and a
      // failed query must not fail the test — the point is that the component
      // survives the failure.
      queries: { retry: false, gcTime: 0, staleTime: 0 },
      mutations: { retry: false },
    },
  });
 
  const view = render(
    <QueryClientProvider client={client}>
      <ThemeProvider>
        <MemoryRouter initialEntries={[url ?? fillParams(path)]}>
          {/* Routed pages are lazy in the app, so a test that renders one
              directly needs the same boundary the app provides — and a
              *detectable* one, so `waitForLazyPage` can tell whether the page
              actually mounted. */}
          <React.Suspense fallback={<div data-testid={LAZY_PENDING_TESTID} />}>
            <WorkspaceProvider
              workspace={workspace ?? PERSONAL_WORKSPACE}
              info={workspaceInfo}
            >
              <Routes>
                <Route path={path} element={element} />
              </Routes>
            </WorkspaceProvider>
          </React.Suspense>
        </MemoryRouter>
      </ThemeProvider>
    </QueryClientProvider>,
  );
  return Object.assign(view, { client });
}
 
/**
 * Wait until the page has no request in flight.
 *
 * Replaces "wait one macrotask and hope". A single tick is a race: under load
 * — a full suite under coverage instrumentation, say — a query can resolve
 * *after* the test's act window, which React reports as an "update was not
 * wrapped in act(...)" warning and the console guard fails. Asking the query
 * client when it is actually idle is deterministic, and finishes sooner than a
 * fixed wait when the page is quick.
 */
export async function settlePage(client: QueryClient): Promise<void> {
  // No outer `act`: `waitFor` already wraps its polling in one, and nesting
  // the two throws "the current testing environment is not configured to
  // support act(...)". Twice now.
  await waitFor(() => {
    if (client.isFetching() > 0 || client.isMutating() > 0) {
      throw new Error("page still has requests in flight");
    }
  });
  // One more turn, inside act, for the re-render those resolutions schedule.
  await act(async () => {
    await new Promise((resolve) => setTimeout(resolve, 0));
  });
}
 
/**
 * Budget for a `beforeAll` that warms a lazily imported module.
 *
 * A test that renders a heavy page warms its module first so no individual
 * test pays the cold transform. That warm-up is a *compile*, not a behaviour,
 * and its cost scales with how loaded the machine is — a page whose graph
 * pulls in the chat surface or a charting library takes the better part of
 * ten seconds here, which is vitest's default hook timeout exactly. So those
 * hooks sat one scheduling hiccup away from failing, and adding a single
 * unrelated test file to the parallel run was enough to trip one.
 *
 * Generous on purpose: nothing here is asserting that a module loads
 * *quickly*, and a warm-up that genuinely hangs still fails, just later.
 * `pages.smoke.test.tsx` keeps its own larger budget — it transforms every
 * page in the app at once, which is a different job.
 */
export const WARM_IMPORT_TIMEOUT_MS = 60_000;
 
export { PARAM_VALUE, fillParams };