The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Add v7 conformance tests for the metabase/router facade (#77064)
Romeo Van Snick2a8bbb797c2d
diff --git a/bun.lock b/bun.lockindex 7c3a6eb7c77..bc9d46200c5 100644--- a/bun.lock+++ b/bun.lock@@ -379,6 +379,7 @@"raf": "^3.4.0","react-docgen-typescript-plugin": "^1.0.6","react-refresh": "^0.14.2",+ "react-router-v7": "npm:[email protected]","reg-cli": "^0.17.7","semver": "^7.6.3","shadow-cljs": "^3.3.5",@@ -4688,6 +4689,8 @@"react-router-redux": ["[email protected]", "", {}, "sha1-InQDWWtRUeGCN32rg1tdRfD4BU4="],+ "react-router-v7": ["[email protected]", "", { "dependencies": { "cookie": "^1.0.1", "set-cookie-parser": "^2.6.0" }, "peerDependencies": { "react": ">=18", "react-dom": ">=18" }, "optionalPeers": ["react-dom"] }, "sha512-GDLgg3i3uM0aeJO3Fm+TCS+sDQ7gu12T6x0qdTEzcwqEfleci7JwugVNIF3U//0FWKnJT7ptG+20B2jfDqnZAg=="],+"react-style-singleton": ["[email protected]", "", { "dependencies": { "get-nonce": "^1.0.0", "tslib": "^2.0.0" } }, "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ=="],"react-tabs": ["[email protected]", "", { "dependencies": { "clsx": "^2.0.0", "prop-types": "^15.5.0" }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0" } }, "sha512-6QtbTRDKM+jA/MZTTefvigNxo0zz+gnBTVFw2CFVvq+f2BuH0nF0vDLNClL045nuTAdOoK/IL1vTP0ZLX0DAyQ=="],@@ -6960,6 +6963,8 @@"react-router/react-is": ["[email protected]", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="],+ "react-router-v7/cookie": ["[email protected]", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="],+"react-style-singleton/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],"react-use/tslib": ["[email protected]", "", {}, "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q=="],diff --git a/frontend/src/metabase/router/conformance/Navigate.conformance.unit.spec.tsx b/frontend/src/metabase/router/conformance/Navigate.conformance.unit.spec.tsxnew file mode 100644index 00000000000..b29ea5c8f42--- /dev/null+++ b/frontend/src/metabase/router/conformance/Navigate.conformance.unit.spec.tsx@@ -0,0 +1,104 @@+import userEvent from "@testing-library/user-event";+import { useState } from "react";++import { screen } from "__support__/ui";++import type { Probe, RouterApi } from "./test-utils";+import { runBoth } from "./test-utils";++// Because the facade churns its `navigate` identity like v7, a mounted+// <Navigate> re-fires whenever the pathname changes and snaps forward to its+// target again. So on both engines, going back re-asserts the destination.+function makeLandingProbe(to: string, replace: boolean): Probe {+ return function LandingProbe({ api }: { api: RouterApi }) {+ const { Navigate } = api;+ const navigate = api.useNavigate();+ const location = api.useLocation();+ return (+ <div>+ <span data-testid="rr-pathname">{location.pathname}</span>+ <Navigate to={to} replace={replace} />+ <button onClick={() => navigate(-1)}>back</button>+ </div>+ );+ };+}++function RenavigateProbe({ api }: { api: RouterApi }) {+ const { Navigate } = api;+ const location = api.useLocation();+ const [to, setTo] = useState("/first");+ return (+ <div>+ <span data-testid="rr-pathname">{location.pathname}</span>+ <Navigate to={to} />+ <button onClick={() => setTo("/second")}>change</button>+ </div>+ );+}++const RICH_STATE = { when: new Date(0), n: NaN };++function StateProbe({ api }: { api: RouterApi }) {+ const { Navigate } = api;+ const location = api.useLocation();+ const state = location.state as typeof RICH_STATE | null;+ return (+ <div>+ <span data-testid="rr-pathname">{location.pathname}</span>+ <span data-testid="rr-when-is-date">+ {String(state?.when instanceof Date)}+ </span>+ <span data-testid="rr-n-is-nan">{String(Number.isNaN(state?.n))}</span>+ <Navigate to="/dest" state={RICH_STATE} />+ </div>+ );+}++describe("router/Navigate conformance", () => {+ it("matches v7 when landing on the destination on mount (push)", async () => {+ const { facade, v7 } = await runBoth(makeLandingProbe("/dest", false), {+ initialRoute: "/home",+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-pathname"]).toBe("/dest");+ });++ it("matches v7 when landing on the destination on mount (replace)", async () => {+ const { facade, v7 } = await runBoth(makeLandingProbe("/dest", true), {+ initialRoute: "/home",+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-pathname"]).toBe("/dest");+ });++ it("matches v7 when re-asserting the pushed target on back", async () => {+ const { facade, v7 } = await runBoth(makeLandingProbe("/dest", false), {+ initialRoute: "/home",+ interact: () =>+ userEvent.click(screen.getByRole("button", { name: "back" })),+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-pathname"]).toBe("/dest");+ });++ it("matches v7 when re-navigating after the target prop changes", async () => {+ const { facade, v7 } = await runBoth(RenavigateProbe, {+ initialRoute: "/home",+ interact: () =>+ userEvent.click(screen.getByRole("button", { name: "change" })),+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-pathname"]).toBe("/second");+ });++ it("matches v7 when passing rich state through by reference", async () => {+ const { facade, v7 } = await runBoth(StateProbe, {+ initialRoute: "/home",+ });+ expect(facade).toEqual(v7);+ // Serializing would turn the Date into a string and NaN into null.+ expect(facade["rr-when-is-date"]).toBe("true");+ expect(facade["rr-n-is-nan"]).toBe("true");+ });+});diff --git a/frontend/src/metabase/router/conformance/test-utils.tsx b/frontend/src/metabase/router/conformance/test-utils.tsxnew file mode 100644index 00000000000..31d9e0e5610--- /dev/null+++ b/frontend/src/metabase/router/conformance/test-utils.tsx@@ -0,0 +1,152 @@+import type { ComponentType } from "react";+import { Route } from "react-router";+import {+ MemoryRouter,+ Navigate as V7Navigate,+ Route as V7Route,+ Routes as V7Routes,+ useLocation as v7UseLocation,+ useNavigate as v7UseNavigate,+ useParams as v7UseParams,+ useSearchParams as v7UseSearchParams,+} from "react-router-v7";++import { act, cleanup, renderWithProviders } from "__support__/ui";+import {+ Navigate,+ useLocation,+ useNavigate,+ useParams,+ useSearchParams,+} from "metabase/router";++/**+ * The slice of the router API that both the `metabase/router` facade (running on+ * react-router v3) and real react-router v7 expose with the same names and+ * signatures. A `Probe` receives one of these and cannot tell which engine it is+ * rendered against, which is what lets a single probe drive both adapters.+ */+export type RouterApi = {+ useNavigate: typeof useNavigate;+ useLocation: typeof useLocation;+ useSearchParams: typeof useSearchParams;+ useParams: typeof useParams;+ // Probes only ever pass string destinations, which both engines accept.+ Navigate: ComponentType<{ to: string; replace?: boolean; state?: unknown }>;+};++export const facadeApi: RouterApi = {+ useNavigate,+ useLocation,+ useSearchParams,+ useParams,+ Navigate,+};++/**+ * Real react-router v7's hooks and components share the facade's shapes but not+ * its exact types (v7 adds options like `relative`), so the object is asserted+ * to the shared `RouterApi` rather than structurally assignable.+ */+export const v7Api = {+ useNavigate: v7UseNavigate,+ useLocation: v7UseLocation,+ useSearchParams: v7UseSearchParams,+ useParams: v7UseParams,+ Navigate: V7Navigate,+} as unknown as RouterApi;++/**+ * A probe renders readouts from the router API it is handed. Every readout it+ * emits must be a `data-testid` starting with `rr-` so the harness can collect+ * and compare exactly those, ignoring provider chrome.+ */+export type Probe = ComponentType<{ api: RouterApi }>;++const READOUT_PREFIX = "rr-";++export type RenderOptions = {+ initialRoute: string;+ facadePath?: string;+ v7Path?: string;+};++function renderFacade(+ Probe: Probe,+ { initialRoute, facadePath = "*" }: RenderOptions,+) {+ const Mounted = () => <Probe api={facadeApi} />;+ renderWithProviders(<Route path={facadePath} component={Mounted} />, {+ withRouter: true,+ initialRoute,+ });+}++function renderV7(Probe: Probe, { initialRoute, v7Path = "*" }: RenderOptions) {+ renderWithProviders(+ <MemoryRouter initialEntries={[initialRoute]}>+ <V7Routes>+ <V7Route path={v7Path} element={<Probe api={v7Api} />} />+ </V7Routes>+ </MemoryRouter>,+ );+}++function collectReadouts(): Record<string, string | null> {+ const nodes = document.querySelectorAll(`[data-testid^="${READOUT_PREFIX}"]`);+ const readouts: Record<string, string | null> = {};+ nodes.forEach((node) => {+ const id = node.getAttribute("data-testid");+ if (id) {+ readouts[id] = node.textContent;+ }+ });+ return readouts;+}++async function settle() {+ // Flush mount effects (e.g. <Navigate>) and the re-render they trigger.+ await act(async () => {});+}++async function renderAndCollect(+ render: () => void,+ interact?: () => Promise<void>,+): Promise<Record<string, string | null>> {+ render();+ // Always unmount, even if a step throws, so one render's `rr-` nodes can never+ // leak into the next.+ try {+ await settle();+ await interact?.();+ return collectReadouts();+ } finally {+ cleanup();+ }+}++/**+ * Render the same probe against the facade and against real v7, running the+ * optional interaction against each, and return the `rr-` readouts from both so+ * a spec can assert they are identical.+ */+export async function runBoth(+ Probe: Probe,+ options: RenderOptions & { interact?: () => Promise<void> },+): Promise<{+ facade: Record<string, string | null>;+ v7: Record<string, string | null>;+}> {+ const { interact, ...renderOptions } = options;++ const facade = await renderAndCollect(+ () => renderFacade(Probe, renderOptions),+ interact,+ );+ const v7 = await renderAndCollect(+ () => renderV7(Probe, renderOptions),+ interact,+ );++ return { facade, v7 };+}diff --git a/frontend/src/metabase/router/conformance/types.conformance.unit.spec.ts b/frontend/src/metabase/router/conformance/types.conformance.unit.spec.tsnew file mode 100644index 00000000000..26cdf7c05c3--- /dev/null+++ b/frontend/src/metabase/router/conformance/types.conformance.unit.spec.ts@@ -0,0 +1,137 @@+import type { ComponentProps } from "react";+import type {+ Location as V7Location,+ NavigateFunction as V7NavigateFunction,+ NavigateOptions as V7NavigateOptions,+ NavigateProps as V7NavigateProps,+ OutletProps as V7OutletProps,+ Params as V7Params,+ Path as V7Path,+ SetURLSearchParams as V7SetURLSearchParams,+ To as V7To,+ URLSearchParamsInit as V7URLSearchParamsInit,+ useNavigate as v7UseNavigate,+ useParams as v7UseParams,+ useSearchParams as v7UseSearchParams,+} from "react-router-v7";++import type {+ Navigate,+ NavigateFunction,+ NavigateOptions,+ Outlet,+ Params,+ Path,+ SetURLSearchParams,+ To,+ URLSearchParamsInit,+ useLocation,+ useNavigate,+ useParams,+ useSearchParams,+} from "metabase/router";++/*+ * Compile-time conformance: these assertions fail `tsc` (not jest) if the+ * facade's public types drift from react-router v7's. Runtime behavior lives in+ * the sibling *.conformance specs; this file guards the type contract, the layer+ * a behavioral test cannot see (the missing `defaultInit` argument slipped+ * through exactly here).+ */++type Extends<A, B> = [A] extends [B] ? true : false;+type Equal<A, B> =+ Extends<A, B> extends true+ ? Extends<B, A> extends true+ ? true+ : false+ : false;+type Expect<T extends true> = T;++// The pure data types must be identical to v7's.+type _To = Expect<Equal<To, V7To>>;+type _Path = Expect<Equal<Path, V7Path>>;+type _Params = Expect<Equal<Params, V7Params>>;+type _Init = Expect<Equal<URLSearchParamsInit, V7URLSearchParamsInit>>;++// Hook signatures must match v7's, arguments included. This is the assertion+// that would have caught the missing `useSearchParams(defaultInit)` argument.+type _UseSearchParamsArgs = Expect<+ Equal<+ Parameters<typeof useSearchParams>,+ Parameters<typeof v7UseSearchParams>+ >+>;+type _UseNavigateArgs = Expect<+ Equal<Parameters<typeof useNavigate>, Parameters<typeof v7UseNavigate>>+>;+type _UseParamsReturn = Expect<+ Equal<ReturnType<typeof useParams>, ReturnType<typeof v7UseParams>>+>;++// The facade's location shape must match v7's. `state` is excluded on purpose:+// v7 types it `any`, the facade uses the safer `unknown` (the codebase bans+// `any`). Both are mutually assignable, so the swap is unaffected.+type _Location = Expect<+ Equal<+ Omit<ReturnType<typeof useLocation>, "state">,+ Omit<V7Location, "state">+ >+>;++// Where the facade omits v7 options it must be a strict subset (assignable to+// v7), so facade-typed code keeps compiling after the swap. The omitted options+// themselves are enumerated as known gaps below.+type _NavigateOptionsSubset = Expect<+ Extends<NavigateOptions, V7NavigateOptions>+>;+type _NavigateFnSubset = Expect<Extends<NavigateFunction, V7NavigateFunction>>;+type _SetSearchParamsSubset = Expect<+ Extends<SetURLSearchParams, V7SetURLSearchParams>+>;+type _NavigatePropsSubset = Expect<+ Extends<ComponentProps<typeof Navigate>, V7NavigateProps>+>;++/*+ * Coverage: every option/prop v7 exposes must be either implemented by the+ * facade or listed here as a deliberate gap. When a v7 upgrade adds a key, the+ * matching `Unaccounted` type stops being `never` and this file fails to+ * compile, forcing a conscious decision instead of a silent divergence.+ */++// Need the engine swap (relative resolution, scroll/transition control, URL+// masking, data-router revalidation), so intentionally unsupported on v3.+type KnownGapNavigateOptions =+ | "mask"+ | "preventScrollReset"+ | "relative"+ | "viewTransition"+ | "flushSync"+ | "defaultShouldRevalidate";+type UnaccountedNavigateOptions = Exclude<+ keyof V7NavigateOptions,+ keyof NavigateOptions | KnownGapNavigateOptions+>;+type _NavigateOptionsCovered = Expect<Equal<UnaccountedNavigateOptions, never>>;++type KnownGapNavigateProps = "relative";+type UnaccountedNavigateProps = Exclude<+ keyof V7NavigateProps,+ keyof ComponentProps<typeof Navigate> | KnownGapNavigateProps+>;+type _NavigatePropsCovered = Expect<Equal<UnaccountedNavigateProps, never>>;++// The facade's <Outlet> does not pass context down (no useOutletContext yet).+type KnownGapOutletProps = "context";+type UnaccountedOutletProps = Exclude<+ keyof V7OutletProps,+ keyof ComponentProps<typeof Outlet> | KnownGapOutletProps+>;+type _OutletPropsCovered = Expect<Equal<UnaccountedOutletProps, never>>;++describe("router type conformance", () => {+ it("is enforced by tsc, not at runtime", () => {+ expect(true).toBe(true);+ });+});diff --git a/frontend/src/metabase/router/conformance/use-location.conformance.unit.spec.tsx b/frontend/src/metabase/router/conformance/use-location.conformance.unit.spec.tsxnew file mode 100644index 00000000000..c4ace9839fe--- /dev/null+++ b/frontend/src/metabase/router/conformance/use-location.conformance.unit.spec.tsx@@ -0,0 +1,38 @@+import type { RouterApi } from "./test-utils";+import { runBoth } from "./test-utils";++// v7's runtime `Location` carries an extra, undocumented `mask` field, so the+// differential compares the documented field values rather than the raw key set.+// The exact 5-field shape is locked down in use-location.unit.spec.tsx.+function LocationProbe({ api }: { api: RouterApi }) {+ const location = api.useLocation();+ return (+ <div>+ <span data-testid="rr-pathname">{location.pathname}</span>+ <span data-testid="rr-search">{location.search}</span>+ <span data-testid="rr-hash">{location.hash}</span>+ <span data-testid="rr-state">{JSON.stringify(location.state)}</span>+ </div>+ );+}++describe("router/useLocation conformance", () => {+ it("matches v7 for a url with search and hash", async () => {+ const { facade, v7 } = await runBoth(LocationProbe, {+ initialRoute: "/foo/bar?x=1&y=2#section",+ facadePath: "foo/bar",+ v7Path: "foo/bar",+ });+ expect(facade).toEqual(v7);+ });++ it("matches v7's Location field set and null state default", async () => {+ const { facade, v7 } = await runBoth(LocationProbe, {+ initialRoute: "/foo/bar",+ facadePath: "foo/bar",+ v7Path: "foo/bar",+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-state"]).toBe("null");+ });+});diff --git a/frontend/src/metabase/router/conformance/use-navigate.conformance.unit.spec.tsx b/frontend/src/metabase/router/conformance/use-navigate.conformance.unit.spec.tsxnew file mode 100644index 00000000000..a0c30196332--- /dev/null+++ b/frontend/src/metabase/router/conformance/use-navigate.conformance.unit.spec.tsx@@ -0,0 +1,134 @@+import userEvent from "@testing-library/user-event";+import { useEffect, useState } from "react";++import { screen } from "__support__/ui";++import type { RouterApi } from "./test-utils";+import { runBoth } from "./test-utils";++function NavigateProbe({ api }: { api: RouterApi }) {+ const navigate = api.useNavigate();+ const location = api.useLocation();+ return (+ <div>+ <span data-testid="rr-pathname">{location.pathname}</span>+ <span data-testid="rr-search">{location.search}</span>+ <span data-testid="rr-hash">{location.hash}</span>+ <span data-testid="rr-state">{JSON.stringify(location.state)}</span>+ <button onClick={() => navigate("/foo")}>push</button>+ <button onClick={() => navigate("/bar", { state: { from: "here" } })}>+ push-state+ </button>+ <button onClick={() => navigate({ pathname: "/obj", search: "?x=1" })}>+ push-object+ </button>+ <button onClick={() => navigate("/bar?x=1", { state: { from: "here" } })}>+ push-string-query-state+ </button>+ <button onClick={() => navigate("/baz", { replace: true })}>+ replace+ </button>+ <button onClick={() => navigate(-1)}>back</button>+ </div>+ );+}++// v7's `useNavigate` lists the current pathname in its callback dependencies, so+// the returned `navigate` gets a new identity on every navigation and anything+// depending on it (an effect, or `<Navigate>`) re-runs per navigation. The+// facade matches this, so a `[navigate]` effect runs the same number of times.+function EffectCountProbe({ api }: { api: RouterApi }) {+ const navigate = api.useNavigate();+ const location = api.useLocation();+ const [runs, setRuns] = useState(0);+ useEffect(() => {+ setRuns((count) => count + 1);+ }, [navigate]);+ return (+ <div>+ <span data-testid="rr-effect-runs">{runs}</span>+ <span data-testid="rr-pathname">{location.pathname}</span>+ <button onClick={() => navigate("/next")}>go</button>+ </div>+ );+}++const click = (name: string) =>+ userEvent.click(screen.getByRole("button", { name }));++describe("router/useNavigate conformance", () => {+ it("matches v7 when pushing a string destination", async () => {+ const { facade, v7 } = await runBoth(NavigateProbe, {+ initialRoute: "/start",+ interact: () => click("push"),+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-pathname"]).toBe("/foo");+ });++ it("matches v7 when attaching state to a string destination", async () => {+ const { facade, v7 } = await runBoth(NavigateProbe, {+ initialRoute: "/start",+ interact: () => click("push-state"),+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-state"]).toBe(JSON.stringify({ from: "here" }));+ });++ it("matches v7 when navigating to an object destination", async () => {+ const { facade, v7 } = await runBoth(NavigateProbe, {+ initialRoute: "/start",+ interact: () => click("push-object"),+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-pathname"]).toBe("/obj");+ expect(facade["rr-search"]).toBe("?x=1");+ });++ it("matches v7 when a string destination carries both a query and state", async () => {+ const { facade, v7 } = await runBoth(NavigateProbe, {+ initialRoute: "/start",+ interact: () => click("push-string-query-state"),+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-pathname"]).toBe("/bar");+ expect(facade["rr-search"]).toBe("?x=1");+ expect(facade["rr-state"]).toBe(JSON.stringify({ from: "here" }));+ });++ it("matches v7 when replacing then going back", async () => {+ const { facade, v7 } = await runBoth(NavigateProbe, {+ initialRoute: "/start",+ interact: async () => {+ await click("push"); // /foo+ await click("replace"); // replaces /foo with /baz+ await click("back"); // back past the replaced entry+ },+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-pathname"]).toBe("/start");+ });++ it("matches v7 when moving through history with a numeric delta", async () => {+ const { facade, v7 } = await runBoth(NavigateProbe, {+ initialRoute: "/start",+ interact: async () => {+ await click("push"); // /foo+ await click("back"); // navigate(-1)+ },+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-pathname"]).toBe("/start");+ });++ it("matches v7's navigate identity churn across a navigation", async () => {+ const { facade, v7 } = await runBoth(EffectCountProbe, {+ initialRoute: "/start",+ interact: () => click("go"),+ });+ expect(facade).toEqual(v7);+ // A `[navigate]` effect re-runs on the navigation because the identity+ // changed, on both engines.+ expect(Number(facade["rr-effect-runs"])).toBeGreaterThan(1);+ });+});diff --git a/frontend/src/metabase/router/conformance/use-params.conformance.unit.spec.tsx b/frontend/src/metabase/router/conformance/use-params.conformance.unit.spec.tsxnew file mode 100644index 00000000000..2bd1d555574--- /dev/null+++ b/frontend/src/metabase/router/conformance/use-params.conformance.unit.spec.tsx@@ -0,0 +1,50 @@+import type { RouterApi } from "./test-utils";+import { runBoth } from "./test-utils";++function ParamsProbe({ api }: { api: RouterApi }) {+ const params = api.useParams();+ return (+ <div>+ <span data-testid="rr-segmentId">{params.segmentId}</span>+ <span data-testid="rr-fieldId">{params.fieldId}</span>+ <span data-testid="rr-id">{params.id}</span>+ <span data-testid="rr-splat">{params["*"]}</span>+ <span data-testid="rr-has-splat-key">{String("splat" in params)}</span>+ </div>+ );+}++describe("router/useParams conformance", () => {+ it("matches v7 for params matched by the route", async () => {+ const path = "reference/segments/:segmentId/fields/:fieldId";+ const { facade, v7 } = await runBoth(ParamsProbe, {+ initialRoute: "/reference/segments/42/fields/7",+ facadePath: path,+ v7Path: path,+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-segmentId"]).toBe("42");+ expect(facade["rr-fieldId"]).toBe("7");+ });++ it("matches v7 when decoding a URI-encoded segment", async () => {+ const { facade, v7 } = await runBoth(ParamsProbe, {+ initialRoute: "/x/a%20b",+ facadePath: "x/:id",+ v7Path: "x/:id",+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-id"]).toBe("a b");+ });++ it("matches v7 by exposing the splat under the `*` key", async () => {+ const { facade, v7 } = await runBoth(ParamsProbe, {+ initialRoute: "/files/a/b",+ facadePath: "files/**",+ v7Path: "files/*",+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-splat"]).toBe("a/b");+ expect(facade["rr-has-splat-key"]).toBe("false");+ });+});diff --git a/frontend/src/metabase/router/conformance/use-search-params.conformance.unit.spec.tsx b/frontend/src/metabase/router/conformance/use-search-params.conformance.unit.spec.tsxnew file mode 100644index 00000000000..8f89558be7a--- /dev/null+++ b/frontend/src/metabase/router/conformance/use-search-params.conformance.unit.spec.tsx@@ -0,0 +1,143 @@+import userEvent from "@testing-library/user-event";++import { screen } from "__support__/ui";++import type { RouterApi } from "./test-utils";+import { runBoth } from "./test-utils";++function SearchParamsProbe({ api }: { api: RouterApi }) {+ const [searchParams, setSearchParams] = api.useSearchParams();+ const location = api.useLocation();+ return (+ <div>+ <span data-testid="rr-x">{searchParams.get("x")}</span>+ <span data-testid="rr-y">{searchParams.get("y")}</span>+ <span data-testid="rr-brand">+ {searchParams.getAll("brand").join(",")}+ </span>+ <span data-testid="rr-pathname">{location.pathname}</span>+ <span data-testid="rr-search">{location.search}</span>+ <span data-testid="rr-hash">{location.hash}</span>+ <button onClick={() => setSearchParams({ x: "2", y: "9" })}>set</button>+ <button onClick={() => setSearchParams({ brand: ["nike", "reebok"] })}>+ set-array+ </button>+ <button onClick={() => setSearchParams()}>clear</button>+ <button+ onClick={() =>+ setSearchParams((prev) => {+ prev.set("x", "3");+ return prev;+ })+ }+ >+ update+ </button>+ </div>+ );+}++function DefaultInitProbe({ api }: { api: RouterApi }) {+ const [searchParams, setSearchParams] = api.useSearchParams({ page: "1" });+ return (+ <div>+ <span data-testid="rr-page">{searchParams.get("page")}</span>+ <span data-testid="rr-q">{searchParams.get("q")}</span>+ <button onClick={() => setSearchParams({ q: "x" })}>set-other</button>+ </div>+ );+}++const click = (name: string) =>+ userEvent.click(screen.getByRole("button", { name }));++const AT_FOO = { facadePath: "foo", v7Path: "foo" };++describe("router/useSearchParams conformance", () => {+ it("matches v7 when reading the current query string", async () => {+ const { facade, v7 } = await runBoth(SearchParamsProbe, {+ ...AT_FOO,+ initialRoute: "/foo?x=1",+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-x"]).toBe("1");+ });++ it("matches v7 when setting new params", async () => {+ const { facade, v7 } = await runBoth(SearchParamsProbe, {+ ...AT_FOO,+ initialRoute: "/foo?x=1",+ interact: () => click("set"),+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-search"]).toBe("?x=2&y=9");+ });++ it("matches v7 when expanding array values into repeated params", async () => {+ const { facade, v7 } = await runBoth(SearchParamsProbe, {+ ...AT_FOO,+ initialRoute: "/foo",+ interact: () => click("set-array"),+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-brand"]).toBe("nike,reebok");+ });++ it("matches v7 for a functional updater over the previous params", async () => {+ const { facade, v7 } = await runBoth(SearchParamsProbe, {+ ...AT_FOO,+ initialRoute: "/foo?x=1",+ interact: () => click("update"),+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-x"]).toBe("3");+ });++ it("matches v7 when clearing the query", async () => {+ const { facade, v7 } = await runBoth(SearchParamsProbe, {+ ...AT_FOO,+ initialRoute: "/foo?x=1",+ interact: () => click("clear"),+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-search"]).toBe("");+ });++ it("matches v7's handling of the existing hash when setting params", async () => {+ const { facade, v7 } = await runBoth(SearchParamsProbe, {+ ...AT_FOO,+ initialRoute: "/foo?x=1#section",+ interact: () => click("set"),+ });+ expect(facade).toEqual(v7);+ });++ it("matches v7 when filling in a default the URL is missing", async () => {+ const { facade, v7 } = await runBoth(DefaultInitProbe, {+ ...AT_FOO,+ initialRoute: "/foo",+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-page"]).toBe("1");+ });++ it("matches v7 when the URL value wins over the default", async () => {+ const { facade, v7 } = await runBoth(DefaultInitProbe, {+ ...AT_FOO,+ initialRoute: "/foo?page=5",+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-page"]).toBe("5");+ });++ it("matches v7 when a default stops being merged after a set", async () => {+ const { facade, v7 } = await runBoth(DefaultInitProbe, {+ ...AT_FOO,+ initialRoute: "/foo",+ interact: () => click("set-other"),+ });+ expect(facade).toEqual(v7);+ expect(facade["rr-page"]).toBe("");+ expect(facade["rr-q"]).toBe("x");+ });+});diff --git a/package.json b/package.jsonindex 9a8fa7d21b2..02e926123da 100644--- a/package.json+++ b/package.json@@ -388,6 +388,7 @@"raf": "^3.4.0","react-docgen-typescript-plugin": "^1.0.6","react-refresh": "^0.14.2",+ "react-router-v7": "npm:[email protected]","reg-cli": "^0.17.7","semver": "^7.6.3","shadow-cljs": "^3.3.5",