Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Add routing behavior lock-down tests (#76322)

Romeo Van Snick4dcb2a7f86f5
diff --git a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx
new file mode 100644
index 00000000000..479a8687cb6
--- /dev/null
+++ b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx
@@ -0,0 +1,243 @@
+import { act } from "@testing-library/react";
+import type { Location } from "history";
+import { push, replace } from "react-router-redux";
+
+import { renderHookWithProviders } from "__support__/ui";
+import { isEmbedPreview } from "metabase/embedding/config";
+import { selectTab } from "metabase/redux/dashboard";
+import {
+ createMockDashboardState,
+ createMockSettingsState,
+ createMockState,
+ createMockStoreDashboard,
+} from "metabase/redux/store/mocks";
+import type { ParameterValueOrArray } from "metabase-types/api";
+import { createMockParameter } from "metabase-types/api/mocks";
+
+import { useDashboardUrlQuery } from "./use-dashboard-url-query";
+
+// Pins the dashboard URL-query sync seam: how dashboard parameter and tab state
+// gets pushed or replaced into the location query string, plus the router.listen
+// tab subscription. The react-router migration re-plumbs both of these, and
+// router.listen has no direct v7 equivalent, so this locks current behavior.
+
+jest.mock("react-router-redux", () => ({
+ ...jest.requireActual("react-router-redux"),
+ push: jest.fn((descriptor) => ({ type: "MOCK_PUSH", payload: descriptor })),
+ replace: jest.fn((descriptor) => ({
+ type: "MOCK_REPLACE",
+ payload: descriptor,
+ })),
+}));
+
+jest.mock("metabase/embedding/config", () => ({
+ ...jest.requireActual("metabase/embedding/config"),
+ isEmbedPreview: jest.fn(() => false),
+}));
+
+const DASHBOARD_ID = 1;
+
+type SetupOptions = {
+ dashboardId?: number | null;
+ parameters?: ReturnType<typeof createMockParameter>[];
+ parameterValues?: Record<string, ParameterValueOrArray | null | undefined>;
+ tabs?: { id: number; name: string }[];
+ selectedTabId?: number | null;
+ pathname?: string;
+ query?: Record<string, unknown>;
+};
+
+function setup({
+ dashboardId = DASHBOARD_ID,
+ parameters = [],
+ parameterValues = {},
+ tabs,
+ selectedTabId = null,
+ pathname = `/dashboard/${DASHBOARD_ID}`,
+ query = {},
+}: SetupOptions = {}) {
+ const listeners: ((location: Location) => void)[] = [];
+ const unsubscribe = jest.fn();
+ const router = {
+ listen: jest.fn((cb: (location: Location) => void) => {
+ listeners.push(cb);
+ return unsubscribe;
+ }),
+ };
+
+ const location = {
+ pathname,
+ query,
+ search: "",
+ hash: "",
+ state: null,
+ } as unknown as Location;
+
+ const dashboards =
+ dashboardId == null
+ ? {}
+ : {
+ [dashboardId]: createMockStoreDashboard({
+ id: dashboardId,
+ parameters,
+ tabs: tabs?.map((tab) => ({ ...tab }) as any),
+ }),
+ };
+
+ const storeInitialState = createMockState({
+ dashboard: createMockDashboardState({
+ dashboardId,
+ dashboards,
+ parameterValues,
+ selectedTabId,
+ }),
+ settings: createMockSettingsState({ "site-url": "" }),
+ });
+
+ const { store, unmount } = renderHookWithProviders(
+ () => useDashboardUrlQuery(router as any, location),
+ { storeInitialState },
+ );
+
+ return { store, unmount, router, listeners, unsubscribe, location };
+}
+
+describe("useDashboardUrlQuery", () => {
+ beforeEach(() => {
+ (push as jest.Mock).mockClear();
+ (replace as jest.Mock).mockClear();
+ (isEmbedPreview as jest.Mock).mockReturnValue(false);
+ });
+
+ it("syncs a parameter-value change with replace (not push), writing the parameter slug values into the query", () => {
+ setup({
+ parameters: [createMockParameter({ id: "1", slug: "text" })],
+ parameterValues: { "1": "bar" },
+ });
+
+ expect(replace).toHaveBeenCalledTimes(1);
+ expect(replace).toHaveBeenCalledWith(
+ expect.objectContaining({
+ query: expect.objectContaining({ text: "bar" }),
+ }),
+ );
+ expect(push).not.toHaveBeenCalled();
+ });
+
+ it("syncs a tab change with push (not replace), writing the new tab slug into the query", () => {
+ const { store } = setup({
+ tabs: [
+ { id: 1, name: "Tab 1" },
+ { id: 2, name: "Tab 2" },
+ ],
+ selectedTabId: 1,
+ });
+
+ // The mount sync (previous query params were undefined) uses replace.
+ (push as jest.Mock).mockClear();
+ (replace as jest.Mock).mockClear();
+
+ act(() => {
+ store.dispatch(selectTab({ tabId: 2 }));
+ });
+
+ expect(push).toHaveBeenCalledTimes(1);
+ expect(push).toHaveBeenCalledWith(
+ expect.objectContaining({
+ query: expect.objectContaining({ tab: "2-tab-2" }),
+ }),
+ );
+ expect(replace).not.toHaveBeenCalled();
+ });
+
+ it("does not sync when isEmbedPreview() is true", () => {
+ (isEmbedPreview as jest.Mock).mockReturnValue(true);
+
+ setup({
+ parameters: [createMockParameter({ id: "1", slug: "text" })],
+ parameterValues: { "1": "bar" },
+ });
+
+ expect(push).not.toHaveBeenCalled();
+ expect(replace).not.toHaveBeenCalled();
+ });
+
+ it("does not sync when there is no dashboardId", () => {
+ setup({
+ dashboardId: null,
+ parameters: [createMockParameter({ id: "1", slug: "text" })],
+ parameterValues: { "1": "bar" },
+ });
+
+ expect(push).not.toHaveBeenCalled();
+ expect(replace).not.toHaveBeenCalled();
+ });
+
+ describe("router.listen tab subscription", () => {
+ it("selects the tab when a same-pathname navigation changes the tab query id", () => {
+ const { store, listeners, location } = setup();
+
+ expect(store.getState().dashboard.selectedTabId).toBe(null);
+
+ act(() => {
+ listeners[0]({
+ ...location,
+ query: { tab: "5-tab-5" },
+ } as unknown as Location);
+ });
+
+ // selectTab is the only reducer that sets selectedTabId, so this pins that
+ // selectTab({ tabId: 5 }) was dispatched by the subscription.
+ expect(store.getState().dashboard.selectedTabId).toBe(5);
+ });
+
+ it("does nothing when the pathname changes", () => {
+ const { store, listeners, location } = setup();
+
+ act(() => {
+ listeners[0]({
+ ...location,
+ pathname: "/dashboard/999",
+ query: { tab: "5-tab-5" },
+ } as unknown as Location);
+ });
+
+ expect(store.getState().dashboard.selectedTabId).toBe(null);
+ });
+
+ it("unsubscribes on unmount", () => {
+ const { unmount, unsubscribe } = setup();
+
+ expect(unsubscribe).not.toHaveBeenCalled();
+ unmount();
+ expect(unsubscribe).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ it("does not sync while navigation is in progress (URL dashboard id differs from current)", () => {
+ setup({
+ dashboardId: DASHBOARD_ID,
+ parameters: [createMockParameter({ id: "1", slug: "text" })],
+ parameterValues: { "1": "bar" },
+ pathname: "/dashboard/999",
+ });
+
+ expect(push).not.toHaveBeenCalled();
+ expect(replace).not.toHaveBeenCalled();
+ });
+
+ it("preserves an allow-listed query param (objectId) when syncing", () => {
+ setup({
+ parameters: [createMockParameter({ id: "1", slug: "text" })],
+ parameterValues: { "1": "bar" },
+ query: { objectId: "42" },
+ });
+
+ expect(replace).toHaveBeenCalledTimes(1);
+ expect(replace).toHaveBeenCalledWith(
+ expect.objectContaining({
+ query: expect.objectContaining({ objectId: "42", text: "bar" }),
+ }),
+ );
+ });
+});
diff --git a/frontend/src/metabase/query_builder/actions/navigation.unit.spec.ts b/frontend/src/metabase/query_builder/actions/navigation.unit.spec.ts
new file mode 100644
index 00000000000..99c1099dee5
--- /dev/null
+++ b/frontend/src/metabase/query_builder/actions/navigation.unit.spec.ts
@@ -0,0 +1,142 @@
+// Pins the QB location-change read seam, the counterpart to url.ts which
+// produces the pushes. locationChanged decides between re-running initializeQB
+// and dispatching popState based on location.action plus location.state. The
+// router migration re-plumbs this read seam, so this locks the current matrix.
+import type { Location } from "history";
+
+import * as initializeQBModule from "./core/initializeQB";
+import { locationChanged } from "./navigation";
+
+const loc = (over: Partial<Location> = {}): Location =>
+ ({
+ pathname: "/question/1",
+ search: "",
+ hash: "",
+ action: "PUSH",
+ state: null,
+ ...over,
+ }) as Location;
+
+const dispatchedAThunk = (dispatch: jest.Mock) =>
+ dispatch.mock.calls.some(([action]) => typeof action === "function");
+
+describe("locationChanged", () => {
+ let dispatch: jest.Mock;
+ let initSpy: jest.SpyInstance;
+
+ beforeEach(() => {
+ dispatch = jest.fn();
+ initSpy = jest
+ .spyOn(initializeQBModule, "initializeQB")
+ .mockReturnValue({ type: "MOCK_INIT" } as any);
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it("does nothing when location and nextLocation are the same reference", () => {
+ const location = loc();
+
+ locationChanged(location, location, {})(dispatch);
+
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(initSpy).not.toHaveBeenCalled();
+ });
+
+ it("re-initializes QB on an external PUSH to a different pathname", () => {
+ const location = loc({ pathname: "/question/1" });
+ const nextLocation = loc({
+ pathname: "/question/2",
+ action: "PUSH",
+ state: null,
+ });
+ const nextParams = { slug: "2" };
+
+ locationChanged(location, nextLocation, nextParams)(dispatch);
+
+ expect(initSpy).toHaveBeenCalledTimes(1);
+ expect(initSpy).toHaveBeenCalledWith(nextLocation, nextParams);
+ expect(dispatchedAThunk(dispatch)).toBe(false);
+ });
+
+ it("ignores an app-initiated PUSH that carries state", () => {
+ const location = loc({ pathname: "/question/1" });
+ const nextLocation = loc({
+ pathname: "/question/2",
+ action: "PUSH",
+ state: { card: { id: 2 } },
+ });
+
+ locationChanged(location, nextLocation, {})(dispatch);
+
+ expect(initSpy).not.toHaveBeenCalled();
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it("re-initializes QB on an external REPLACE", () => {
+ const location = loc({ pathname: "/question/1" });
+ const nextLocation = loc({
+ pathname: "/question/2",
+ action: "REPLACE",
+ state: null,
+ });
+
+ locationChanged(location, nextLocation, {})(dispatch);
+
+ expect(initSpy).toHaveBeenCalledTimes(1);
+ expect(dispatchedAThunk(dispatch)).toBe(false);
+ });
+
+ it("ignores an app-initiated REPLACE that carries state", () => {
+ const location = loc({ pathname: "/question/1" });
+ const nextLocation = loc({
+ pathname: "/question/2",
+ action: "REPLACE",
+ state: { card: { id: 2 } },
+ });
+
+ locationChanged(location, nextLocation, {})(dispatch);
+
+ expect(initSpy).not.toHaveBeenCalled();
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it("dispatches popState and re-initializes QB on an external POP that changed the url", () => {
+ const location = loc({ pathname: "/question/1" });
+ const nextLocation = loc({
+ pathname: "/question/2",
+ action: "POP",
+ state: null,
+ });
+
+ locationChanged(location, nextLocation, {})(dispatch);
+
+ expect(initSpy).toHaveBeenCalledTimes(1);
+ expect(dispatchedAThunk(dispatch)).toBe(true);
+ });
+
+ it("dispatches popState but does not re-initialize QB on an app-initiated POP that changed the url", () => {
+ const location = loc({ pathname: "/question/1" });
+ const nextLocation = loc({
+ pathname: "/question/2",
+ action: "POP",
+ state: { card: { id: 2 } },
+ });
+
+ locationChanged(location, nextLocation, {})(dispatch);
+
+ expect(initSpy).not.toHaveBeenCalled();
+ expect(dispatchedAThunk(dispatch)).toBe(true);
+ });
+
+ it("does nothing on a POP that did not change the url", () => {
+ const location = loc({ pathname: "/question/1" });
+ const nextLocation = loc({ pathname: "/question/1", action: "POP" });
+
+ locationChanged(location, nextLocation, {})(dispatch);
+
+ expect(initSpy).not.toHaveBeenCalled();
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/metabase/query_builder/actions/url.unit.spec.ts b/frontend/src/metabase/query_builder/actions/url.unit.spec.ts
new file mode 100644
index 00000000000..c53da0baf05
--- /dev/null
+++ b/frontend/src/metabase/query_builder/actions/url.unit.spec.ts
@@ -0,0 +1,309 @@
+// Characterization test for the navigation PRODUCER seam.
+//
+// This pins updateUrl -> dispatch(push/replace, { ..., state }), the QB side that
+// decides which router action to emit and what card state to carry on it. It is a
+// lock-down net for the upcoming react-router migration and is complementary to
+// redux/routing-contract.unit.spec.ts, which pins the transport side (how the
+// dispatched push/replace action mutates state.routing).
+
+import { createMockEntitiesState } from "__support__/store";
+import {
+ createMockQueryBuilderState,
+ createMockQueryBuilderUIControlsState,
+ createMockState,
+} from "metabase/redux/store/mocks";
+import { getMetadata } from "metabase/selectors/metadata";
+import * as Urls from "metabase/urls";
+import { checkNotNull } from "metabase/utils/types";
+import registerVisualizations from "metabase/visualizations/register";
+import type Question from "metabase-lib/v1/Question";
+import type { Card } from "metabase-types/api";
+import {
+ ORDERS_ID,
+ createSampleDatabase,
+ createSavedStructuredCard,
+} from "metabase-types/api/mocks/presets";
+
+import { getTableUrlForPristineQuestion } from "../utils";
+
+import { SET_CURRENT_STATE } from "./state";
+import { updateUrl } from "./url";
+
+registerVisualizations();
+
+const CALL_HISTORY_METHOD = "@@router/CALL_HISTORY_METHOD";
+
+type UpdateUrlOptions = Parameters<typeof updateUrl>[1];
+
+function buildSavedQuestion(card: Card): Question {
+ const entities = createMockEntitiesState({
+ databases: [createSampleDatabase()],
+ questions: [card],
+ });
+ const metadata = getMetadata(createMockState({ entities }));
+ return checkNotNull(metadata.question(card.id));
+}
+
+function buildPristineTableQuestion(): Question {
+ const entities = createMockEntitiesState({
+ databases: [createSampleDatabase()],
+ });
+ const metadata = getMetadata(createMockState({ entities }));
+ return checkNotNull(metadata.table(ORDERS_ID)).newQuestion();
+}
+
+function getDispatchedNavigation(dispatch: jest.Mock) {
+ const call = dispatch.mock.calls.find(
+ ([action]) => action?.type === CALL_HISTORY_METHOD,
+ );
+ if (!call) {
+ return null;
+ }
+ const { method, args } = call[0].payload;
+ return { method, descriptor: args[0] };
+}
+
+function dispatchedSetCurrentState(dispatch: jest.Mock) {
+ return dispatch.mock.calls.find(
+ ([action]) => action?.type === SET_CURRENT_STATE,
+ );
+}
+
+type SetupOpts = {
+ question: Question;
+ options?: UpdateUrlOptions;
+ currentState?: { card: Card; cardId?: number; serializedCard: string } | null;
+};
+
+async function setup({
+ question,
+ options = {},
+ currentState = null,
+}: SetupOpts) {
+ const dispatch = jest.fn();
+ const qb = createMockQueryBuilderState({
+ card: question.card(),
+ originalCard: null,
+ currentState,
+ uiControls: createMockQueryBuilderUIControlsState({
+ queryBuilderMode: "view",
+ }),
+ });
+ const getState = () => ({
+ ...createMockState(),
+ qb,
+ });
+
+ await updateUrl(question, options)(dispatch, getState as any);
+
+ return { dispatch };
+}
+
+describe("QB Actions > updateUrl (navigation producer contract)", () => {
+ beforeEach(() => {
+ jest.spyOn(console, "warn").mockImplementation(() => {});
+ window.history.replaceState({}, "", "/");
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it("carries the serialized card on location.state (back/forward restore contract)", async () => {
+ const card = createSavedStructuredCard();
+ const question = buildSavedQuestion(card);
+
+ const { dispatch } = await setup({
+ question,
+ options: { dirty: true, replaceState: false },
+ });
+
+ const navigation = getDispatchedNavigation(dispatch);
+ expect(navigation).not.toBeNull();
+ expect(navigation?.descriptor.state).toEqual({
+ card: question.card(),
+ cardId: question.id(),
+ objectId: undefined,
+ });
+ });
+
+ describe("push vs replace decision", () => {
+ it("replaces when replaceState is undefined, the card is unchanged and the mode is unchanged", async () => {
+ const card = createSavedStructuredCard();
+ const question = buildSavedQuestion(card);
+
+ const { dispatch } = await setup({
+ question,
+ options: { dirty: false },
+ currentState: { card: question.card(), serializedCard: "" },
+ });
+
+ expect(getDispatchedNavigation(dispatch)?.method).toBe("replace");
+ });
+
+ it("forces replace when replaceState is explicitly true", async () => {
+ const card = createSavedStructuredCard();
+ const question = buildSavedQuestion(card);
+
+ const { dispatch } = await setup({
+ question,
+ options: { dirty: true, replaceState: true },
+ });
+
+ expect(getDispatchedNavigation(dispatch)?.method).toBe("replace");
+ });
+
+ it("forces push when replaceState is explicitly false", async () => {
+ const card = createSavedStructuredCard();
+ const question = buildSavedQuestion(card);
+
+ const { dispatch } = await setup({
+ question,
+ options: { dirty: false, replaceState: false },
+ currentState: { card: question.card(), serializedCard: "" },
+ });
+
+ expect(getDispatchedNavigation(dispatch)?.method).toBe("push");
+ });
+ });
+
+ it("short-circuits (no navigation, no setCurrentState) when the card and URL are both unchanged", async () => {
+ const card = createSavedStructuredCard();
+ const question = buildSavedQuestion(card);
+
+ // First run: observe the descriptor the question produces.
+ const first = await setup({
+ question,
+ options: { dirty: false },
+ });
+ const descriptor = getDispatchedNavigation(first.dispatch)?.descriptor;
+ expect(descriptor).toBeDefined();
+
+ // Align window.location with the descriptor so isSameURL becomes true, and
+ // set currentState.card to the same card so isSameCard becomes true.
+ const search = descriptor.search ?? "";
+ const hash = descriptor.hash ?? "";
+ window.history.replaceState(
+ {},
+ "",
+ `${descriptor.pathname}${search}${hash}`,
+ );
+
+ const { dispatch } = await setup({
+ question,
+ options: { dirty: false },
+ currentState: { card: question.card(), serializedCard: "" },
+ });
+
+ expect(getDispatchedNavigation(dispatch)).toBeNull();
+ expect(dispatchedSetCurrentState(dispatch)).toBeUndefined();
+ });
+
+ describe("preserveNavbarState", () => {
+ it("merges preserveNavbarState into location.state on the replace path", async () => {
+ const card = createSavedStructuredCard();
+ const question = buildSavedQuestion(card);
+
+ const { dispatch } = await setup({
+ question,
+ options: { dirty: true, replaceState: true, preserveNavbarState: true },
+ });
+
+ const navigation = getDispatchedNavigation(dispatch);
+ expect(navigation?.method).toBe("replace");
+ expect(navigation?.descriptor.state).toEqual({
+ card: question.card(),
+ cardId: question.id(),
+ objectId: undefined,
+ preserveNavbarState: true,
+ });
+ });
+
+ it("does not add preserveNavbarState on the push path", async () => {
+ const card = createSavedStructuredCard();
+ const question = buildSavedQuestion(card);
+
+ const { dispatch } = await setup({
+ question,
+ options: {
+ dirty: true,
+ replaceState: false,
+ preserveNavbarState: true,
+ },
+ });
+
+ const navigation = getDispatchedNavigation(dispatch);
+ expect(navigation?.method).toBe("push");
+ expect(navigation?.descriptor.state).not.toHaveProperty(
+ "preserveNavbarState",
+ );
+ });
+ });
+
+ it("flows objectId through onto location.state", async () => {
+ const card = createSavedStructuredCard();
+ const question = buildSavedQuestion(card);
+
+ const { dispatch } = await setup({
+ question,
+ options: { dirty: true, replaceState: false, objectId: "42" },
+ });
+
+ expect(getDispatchedNavigation(dispatch)?.descriptor.state.objectId).toBe(
+ "42",
+ );
+ });
+
+ describe("table route preservation", () => {
+ it("keeps the canonical /table URL when on a /table/... route", async () => {
+ const question = buildPristineTableQuestion();
+ const expectedUrl = Urls.table({
+ id: ORDERS_ID,
+ name: question.metadata().table(ORDERS_ID)?.display_name,
+ });
+
+ window.history.replaceState({}, "", "/table/anything");
+
+ const { dispatch } = await setup({
+ question,
+ options: { queryBuilderMode: "view" },
+ });
+
+ const navigation = getDispatchedNavigation(dispatch);
+ expect(navigation?.descriptor.pathname).toBe(expectedUrl);
+ expect(navigation?.descriptor.pathname).toBe(
+ getTableUrlForPristineQuestion(question),
+ );
+ });
+
+ it("falls through to the card-state URL when off a /table/... route", async () => {
+ const question = buildPristineTableQuestion();
+
+ window.history.replaceState({}, "", "/question");
+
+ const { dispatch } = await setup({
+ question,
+ options: { queryBuilderMode: "view" },
+ });
+
+ const pathname = getDispatchedNavigation(dispatch)?.descriptor.pathname;
+ expect(pathname).toBe("/question");
+ expect(pathname).not.toMatch(/^\/table\//);
+ });
+
+ it("falls through to the card-state URL on a /table/... route when objectId is set", async () => {
+ const question = buildPristineTableQuestion();
+
+ window.history.replaceState({}, "", "/table/anything");
+
+ const { dispatch } = await setup({
+ question,
+ options: { queryBuilderMode: "view", objectId: "5" },
+ });
+
+ expect(
+ getDispatchedNavigation(dispatch)?.descriptor.pathname,
+ ).not.toMatch(/^\/table\//);
+ });
+ });
+});
diff --git a/frontend/src/metabase/redux/app.unit.spec.ts b/frontend/src/metabase/redux/app.unit.spec.ts
new file mode 100644
index 00000000000..c564b3155a6
--- /dev/null
+++ b/frontend/src/metabase/redux/app.unit.spec.ts
@@ -0,0 +1,139 @@
+import appReducer, {
+ closeNavbar,
+ isNavbarOpenForPathname,
+ openNavbar,
+ resetErrorPage,
+ setErrorPage,
+ toggleNavbar,
+} from "metabase/redux/app";
+
+// Characterization tests for the two reducers that react to navigation via the
+// `@@router/LOCATION_CHANGE` action (`isNavbarOpen` collapse-by-pathname and
+// `errorPage` clear-on-navigate). The router migration re-owns this action with
+// a byte-identical type string and payload shape, so these tests must keep
+// passing through the migration — they lock the subtle behaviour most likely to
+// drift.
+
+const LOCATION_CHANGE = "@@router/LOCATION_CHANGE";
+
+const locationChange = (payload: Record<string, unknown>) => ({
+ type: LOCATION_CHANGE,
+ payload,
+});
+
+const initialState = () => appReducer(undefined, { type: "@@INIT" } as any);
+
+describe("app reducer — navigation reactions", () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ describe("isNavbarOpen on LOCATION_CHANGE", () => {
+ it("collapses when navigating to a path in the collapse list", () => {
+ const state = appReducer(
+ initialState(),
+ locationChange({ pathname: "/question/1" }),
+ );
+ expect(state.isNavbarOpen).toBe(false);
+ });
+
+ it("stays open when navigating to a non-collapsing path", () => {
+ const state = appReducer(
+ initialState(),
+ locationChange({ pathname: "/collection/1" }),
+ );
+ expect(state.isNavbarOpen).toBe(true);
+ });
+
+ it("preserves the previous state when payload.state.preserveNavbarState is set", () => {
+ const state = appReducer(
+ initialState(),
+ locationChange({
+ pathname: "/question/1",
+ state: { preserveNavbarState: true },
+ }),
+ );
+ expect(state.isNavbarOpen).toBe(true);
+ });
+
+ // Word-boundary cases pinned by the regex comment in app.ts: a partial match
+ // must not collapse the navbar.
+ it.each([
+ ["/model/1", false], // a model — collapses
+ ["/browse/models", true], // listing — must NOT collapse
+ ["/question/1", false], // a question — collapses
+ ["/reference/segments/1/questions", true], // listing — must NOT collapse
+ ["/dashboard/1", false],
+ ["/metabot", false],
+ ["/document/1", false],
+ ["/explore", false],
+ ["/collection/root", true],
+ ["/browse/databases", true],
+ ])("pathname %s => isNavbarOpen %s", (pathname, expected) => {
+ const state = appReducer(initialState(), locationChange({ pathname }));
+ expect(state.isNavbarOpen).toBe(expected);
+ });
+
+ it("does not reopen a closed navbar just because the path is non-collapsing", () => {
+ const closed = appReducer(initialState(), closeNavbar());
+ const state = appReducer(
+ closed,
+ locationChange({ pathname: "/collection/1" }),
+ );
+ expect(state.isNavbarOpen).toBe(false);
+ });
+ });
+
+ describe("isNavbarOpen on explicit actions", () => {
+ it("opens / closes / toggles", () => {
+ let state = appReducer(initialState(), closeNavbar());
+ expect(state.isNavbarOpen).toBe(false);
+
+ state = appReducer(state, openNavbar());
+ expect(state.isNavbarOpen).toBe(true);
+
+ state = appReducer(state, toggleNavbar());
+ expect(state.isNavbarOpen).toBe(false);
+ });
+ });
+
+ describe("errorPage", () => {
+ it("is cleared on navigation", () => {
+ jest.spyOn(console, "error").mockImplementation(() => {});
+ const withError = appReducer(
+ initialState(),
+ setErrorPage({ status: 500 }),
+ );
+ expect(withError.errorPage).toEqual({ status: 500 });
+
+ const navigated = appReducer(
+ withError,
+ locationChange({ pathname: "/question/1" }),
+ );
+ expect(navigated.errorPage).toBeNull();
+ });
+
+ it("is cleared on resetErrorPage", () => {
+ jest.spyOn(console, "error").mockImplementation(() => {});
+ const withError = appReducer(
+ initialState(),
+ setErrorPage({ status: 404 }),
+ );
+ const reset = appReducer(withError, resetErrorPage());
+ expect(reset.errorPage).toBeNull();
+ });
+ });
+});
+
+describe("isNavbarOpenForPathname", () => {
+ it.each([
+ ["/question/1", true, false],
+ ["/collection/1", true, true],
+ ["/browse/models", true, true],
+ ["/model/1", true, false],
+ // a collapsing path can never force the navbar open when it was closed
+ ["/collection/1", false, false],
+ ])("pathname %s with prevState %s => %s", (pathname, prevState, expected) => {
+ expect(isNavbarOpenForPathname(pathname, prevState)).toBe(expected);
+ });
+});
diff --git a/frontend/src/metabase/redux/routing-contract.unit.spec.ts b/frontend/src/metabase/redux/routing-contract.unit.spec.ts
new file mode 100644
index 00000000000..6b8388313c5
--- /dev/null
+++ b/frontend/src/metabase/redux/routing-contract.unit.spec.ts
@@ -0,0 +1,136 @@
+import { configureStore } from "@reduxjs/toolkit";
+import { createMemoryHistory } from "history";
+import {
+ goBack,
+ push,
+ replace,
+ routerMiddleware,
+ routerReducer,
+ syncHistoryWithStore,
+} from "react-router-redux";
+
+import { getLocation } from "metabase/selectors/routing";
+
+// Keystone characterization test for the navigation TRANSPORT seam.
+//
+// The router migration replaces react-router-redux's `push`/`replace`/`goBack`
+// action creators + `routerMiddleware` + `routerReducer` + `syncHistoryWithStore`
+// with our own ~50-line equivalents (see TANSTACK-MIGRATION-PLAN.md, the
+// "react-router-redux" section). This test pins the observable contract that the
+// replacement must preserve byte-for-byte:
+//
+// dispatch(push/replace/goBack) -> state.routing + @@router/LOCATION_CHANGE
+//
+// It wires up the SAME transport `store.js` / `app.js` use (routerMiddleware +
+// routerReducer + a memory history + syncHistoryWithStore), isolated from the
+// rest of the app graph. POST-MIGRATION: swap the four react-router-redux imports
+// for their `metabase/router` equivalents and this test must still pass.
+
+const LOCATION_CHANGE = "@@router/LOCATION_CHANGE";
+
+const setup = () => {
+ const actions: Array<{ type: string; payload?: any }> = [];
+ const recorder = () => (next: any) => (action: any) => {
+ actions.push(action);
+ return next(action);
+ };
+
+ const history = createMemoryHistory();
+ const store = configureStore({
+ reducer: { routing: routerReducer },
+ middleware: (getDefaultMiddleware) =>
+ getDefaultMiddleware({
+ serializableCheck: false,
+ immutableCheck: false,
+ }).concat(routerMiddleware(history), recorder),
+ });
+ const syncedHistory = syncHistoryWithStore(history, store);
+
+ const locationChanges = () =>
+ actions.filter((a) => a.type === LOCATION_CHANGE);
+ const location = () => getLocation(store.getState() as any);
+
+ return { store, history: syncedHistory, location, locationChanges };
+};
+
+describe("routing transport contract", () => {
+ it("mirrors the initial location into state.routing on sync", () => {
+ const { location } = setup();
+ expect(location().pathname).toBe("/");
+ });
+
+ it("push(string) updates pathname, search and hash", () => {
+ const { store, location } = setup();
+
+ store.dispatch(push("/question/42?x=1#hash"));
+
+ expect(location().pathname).toBe("/question/42");
+ expect(location().search).toBe("?x=1");
+ expect(location().hash).toBe("#hash");
+ });
+
+ it("push(descriptor) round-trips location.state (the QB card-state case)", () => {
+ // query_builder/actions/url.ts dispatches push() with the serialized card on
+ // `state`; the migration's history proxy must forward state across engines.
+ const { store, location } = setup();
+ const cardState = {
+ card: { id: 7, name: "Q" },
+ cardId: 7,
+ objectId: undefined,
+ };
+
+ store.dispatch(
+ push({
+ pathname: "/question",
+ search: "?y=2",
+ hash: "#abc",
+ state: cardState,
+ }),
+ );
+
+ expect(location().pathname).toBe("/question");
+ expect(location().state).toEqual(cardState);
+ });
+
+ it("preserves the preserveNavbarState flag on location.state", () => {
+ const { store, location } = setup();
+
+ store.dispatch(
+ push({ pathname: "/question/1", state: { preserveNavbarState: true } }),
+ );
+
+ expect(location().state).toEqual({ preserveNavbarState: true });
+ });
+
+ it("distinguishes push from replace via location.action", () => {
+ const { store, location } = setup();
+
+ store.dispatch(push("/a"));
+ expect(location().action).toBe("PUSH");
+
+ store.dispatch(replace("/b"));
+ expect(location().pathname).toBe("/b");
+ expect(location().action).toBe("REPLACE");
+ });
+
+ it("goBack returns to the previous entry", () => {
+ const { store, location } = setup();
+
+ store.dispatch(push("/first"));
+ store.dispatch(push("/second"));
+ expect(location().pathname).toBe("/second");
+
+ store.dispatch(goBack());
+ expect(location().pathname).toBe("/first");
+ });
+
+ it("emits @@router/LOCATION_CHANGE with the location payload on every navigation", () => {
+ const { store, locationChanges } = setup();
+
+ store.dispatch(push("/one"));
+ store.dispatch(push("/two"));
+
+ const paths = locationChanges().map((a) => a.payload.pathname);
+ expect(paths).toEqual(expect.arrayContaining(["/one", "/two"]));
+ });
+});
diff --git a/frontend/src/metabase/selectors/routing.unit.spec.ts b/frontend/src/metabase/selectors/routing.unit.spec.ts
new file mode 100644
index 00000000000..32a43ae7c93
--- /dev/null
+++ b/frontend/src/metabase/selectors/routing.unit.spec.ts
@@ -0,0 +1,37 @@
+import {
+ createMockLocation,
+ createMockRoutingState,
+ createMockState,
+} from "metabase/redux/store/mocks";
+
+import { getLocation } from "./routing";
+
+// Characterization tests — these lock the public shape of `getLocation` so the
+// router migration (react-router v3 -> TanStack) cannot silently change what
+// `state.routing` exposes. The migration keeps the `routing` slice shape and
+// the `locationBeforeTransitions` key on purpose; these tests are the net.
+describe("getLocation", () => {
+ it("returns state.routing.locationBeforeTransitions", () => {
+ const location = createMockLocation({
+ pathname: "/question/1",
+ search: "?a=1",
+ hash: "#abc",
+ });
+ const state = createMockState({
+ routing: createMockRoutingState({ locationBeforeTransitions: location }),
+ });
+
+ const result = getLocation(state);
+ expect(result.pathname).toBe("/question/1");
+ expect(result.search).toBe("?a=1");
+ expect(result.hash).toBe("#abc");
+ });
+
+ it("falls back to { pathname: '' } when routing is absent", () => {
+ // The optional-chaining fallback in the selector — relied on before the
+ // history sync has run.
+ const state = { ...createMockState(), routing: undefined } as any;
+
+ expect(getLocation(state)).toEqual({ pathname: "" });
+ });
+});