testRouterRendersThePageItsAt

tcmts.react.test.testRouterRendersThePageItsAt · #diqx5t6h · term

The router over a page's globals: its first paint reads the page's location, under its base, and <Pages> renders the route the path matches, with its parameters and query (or notFound).

import { createRouter } from "#codebase/tcmts/react";
import type { PageProps } from "#codebase/tcmts/react";
import { createElement } from "react";
import { renderToString } from "react-dom/server";
import { expect } from "vitest";

export const testRouterRendersThePageItsAt = () => {
  const pageAt = (pathname: string, search = "") =>
    ({
      __TCM_BASE__: "/apps/x",
      location: {
        pathname,
        search,
        hash: "",
        href: `http://app${pathname}${search}`,
        origin: "http://app",
      },
      history: { state: null },
      addEventListener: () => {},
      removeEventListener: () => {},
    }) as unknown as typeof globalThis;
  const render = (page: typeof globalThis) => {
    const router = createRouter(page);
    const Where = () => {
      const { path, query } = router.useLocation();
      return createElement("p", null, `${path} ${query.get("q") ?? ""}`);
    };
    const Note = ({ params, query }: PageProps) =>
      createElement("h1", null, `note ${params.id} ${query.get("q") ?? ""}`);
    const routes = { "/n/:id": Note };
    const Missing = () => createElement("h1", null, "missing");
    const Shown = () => router.Pages({ routes, notFound: Missing }) as never;
    return renderToString(createElement("div", null, createElement(Where), createElement(Shown)));
  };
  const at = render(pageAt("/apps/x/n/7", "?q=hi"));
  expect(at).toMatch(/<p>\/n\/7 hi<\/p>/);
  expect(at).toMatch(/<h1>note 7 hi<\/h1>/);
  expect(render(pageAt("/apps/x/elsewhere"))).toMatch(/<h1>missing<\/h1>/);
}

uses