Skip to content

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

Use more robust approach to detecting unmocked routes (#64508)

Fraser2637538cee83
diff --git a/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbs.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbs.unit.spec.tsx
index dc32265606c..487b65e05ca 100644
--- a/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbs.unit.spec.tsx
+++ b/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbs.unit.spec.tsx
@@ -111,7 +111,7 @@ describe("SdkBreadcrumbs", () => {
});
await waitFor(() => {
- expect(screen.getByText("Last edited by")).toBeInTheDocument();
+ expect(screen.getByText("This collection is empty")).toBeInTheDocument();
});
expect(
diff --git a/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/setup.spec.tsx b/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/setup.spec.tsx
index aeee28a6431..05c38767e3c 100644
--- a/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/setup.spec.tsx
+++ b/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/setup.spec.tsx
@@ -6,11 +6,13 @@ import {
setupCardEndpoints,
setupCardQueryEndpoints,
setupCardQueryMetadataEndpoint,
+ setupCollectionByIdEndpoint,
setupCollectionItemsEndpoint,
setupCollectionsEndpoints,
setupDashboardEndpoints,
setupDashboardQueryMetadataEndpoint,
setupDatabaseEndpoints,
+ setupDatabaseListEndpoint,
setupTableEndpoints,
} from "__support__/server-mocks";
import { setupNotificationChannelsEndpoints } from "__support__/server-mocks/pulse";
@@ -156,6 +158,10 @@ export const setup = async () => {
collections: [ROOT_TEST_COLLECTION, NESTED_COLLECTION],
});
+ setupCollectionByIdEndpoint({
+ collections: [ROOT_TEST_COLLECTION, NESTED_COLLECTION],
+ });
+
setupCollectionItemsEndpoint({
collection: ROOT_TEST_COLLECTION,
collectionItems,
@@ -185,6 +191,7 @@ export const setup = async () => {
);
setupAlertsEndpoints(TEST_CARD, []);
setupDatabaseEndpoints(TEST_DATABASE);
+ setupDatabaseListEndpoint([TEST_DATABASE]);
setupTableEndpoints(TEST_TABLE);
setupNotificationChannelsEndpoints({});
diff --git a/enterprise/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx
index 871b21a373a..567c0eeace1 100644
--- a/enterprise/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx
+++ b/enterprise/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx
@@ -94,19 +94,20 @@ const TEST_CARD = createMockCard({
parameters: [TEST_PARAM],
});
-const setup = ({
+const setup = async ({
isValidCard = true,
title,
withCustomLayout = false,
withChartTypeSelector = false,
initialSqlParameters,
cardId = TEST_CARD_ID,
+ preventWaitForLoader = false,
}: Partial<
Pick<BaseSdkQuestionProps, "initialSqlParameters"> &
Pick<SdkQuestionDefaultViewProps, "withChartTypeSelector" | "title"> & {
isValidCard?: boolean;
withCustomLayout?: boolean;
- } & { cardId: BaseEntityId | CardId }
+ } & { cardId: BaseEntityId | CardId; preventWaitForLoader?: boolean }
> = {}) => {
const { state } = setupSdkState({
currentUser: TEST_USER,
@@ -132,7 +133,7 @@ const setup = ({
setupEntityIdEndpoint({ card: { [TEST_ENTITY_ID]: TEST_CARD_ID } });
- return renderWithSDKProviders(
+ renderWithSDKProviders(
<SdkQuestion
questionId={cardId}
title={title}
@@ -148,13 +149,17 @@ const setup = ({
storeInitialState: state,
},
);
+
+ if (!preventWaitForLoader) {
+ await waitForLoaderToBeRemoved();
+ }
};
describe("InteractiveQuestion", () => {
it("should initially render with a loader", async () => {
- setup();
-
+ await setup({ preventWaitForLoader: true });
expect(screen.getByTestId("loading-indicator")).toBeInTheDocument();
+ await waitForLoaderToBeRemoved();
});
describe("table visualization", () => {
@@ -162,22 +167,8 @@ describe("InteractiveQuestion", () => {
mockGetBoundingClientRect();
});
- beforeEach(() => {
- jest.useFakeTimers();
- });
-
- afterEach(() => {
- jest.useRealTimers();
- });
-
it("should render loading state when rerunning the query", async () => {
- setup({ withCustomLayout: true });
-
- await waitForLoaderToBeRemoved();
-
- act(() => {
- jest.runAllTimers();
- });
+ await setup({ withCustomLayout: true });
expect(
await within(screen.getByTestId("table-root")).findByText(
@@ -202,13 +193,7 @@ describe("InteractiveQuestion", () => {
});
it("should render when question is valid", async () => {
- setup();
-
- await waitForLoaderToBeRemoved();
-
- act(() => {
- jest.runAllTimers();
- });
+ await setup();
expect(
within(screen.getByTestId("table-root")).getByText(
@@ -221,18 +206,14 @@ describe("InteractiveQuestion", () => {
});
it("should not render an error if a question isn't found before the question loaded", async () => {
- setup();
-
- await waitForLoaderToBeRemoved();
+ await setup();
expect(screen.queryByText("Error")).not.toBeInTheDocument();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("should render an error if a question isn't found", async () => {
- setup({ isValidCard: false });
-
- await waitForLoaderToBeRemoved();
+ await setup({ isValidCard: false });
expect(screen.getByRole("alert")).toHaveTextContent(
`Question ${TEST_CARD.id} not found. Make sure you pass the correct ID.`,
@@ -260,8 +241,7 @@ describe("InteractiveQuestion", () => {
])(
"shows the question title according to the title prop",
async (titleProp, expectedTitle) => {
- setup({ title: titleProp });
- await waitForLoaderToBeRemoved();
+ await setup({ title: titleProp });
const element = screen.queryByText(expectedTitle ?? "My Question");
expect(element?.textContent ?? null).toBe(expectedTitle);
@@ -269,8 +249,7 @@ describe("InteractiveQuestion", () => {
);
it("should show a chart type selector button if withChartTypeSelector is true", async () => {
- setup({ withChartTypeSelector: true });
- await waitForLoaderToBeRemoved();
+ await setup({ withChartTypeSelector: true });
expect(
screen.getByTestId("chart-type-selector-button"),
@@ -278,8 +257,7 @@ describe("InteractiveQuestion", () => {
});
it("should not show a chart type selector button if withChartTypeSelector is false", async () => {
- setup({ withChartTypeSelector: false });
- await waitForLoaderToBeRemoved();
+ await setup({ withChartTypeSelector: false });
expect(
screen.queryByTestId("chart-type-selector-button"),
@@ -287,8 +265,7 @@ describe("InteractiveQuestion", () => {
});
it("should change the visualization if a different visualization is selected", async () => {
- setup({ withChartTypeSelector: true });
- await waitForLoaderToBeRemoved();
+ await setup({ withChartTypeSelector: true });
expect(
screen.getByTestId("chart-type-selector-button"),
).toBeInTheDocument();
@@ -314,8 +291,7 @@ describe("InteractiveQuestion", () => {
// Obviously, we can't test every single permutation of chart settings right now, but tests in the core
// app should cover most cases anyway.
it("should allow user to use chart settings", async () => {
- setup({ withChartTypeSelector: true });
- await waitForLoaderToBeRemoved();
+ await setup({ withChartTypeSelector: true });
await userEvent.click(screen.getByLabelText("gear icon"));
@@ -333,9 +309,7 @@ describe("InteractiveQuestion", () => {
});
it("should query with the parameters in a parameterized question", async () => {
- setup({ initialSqlParameters: { product_id: 1024 } });
-
- await waitForLoaderToBeRemoved();
+ await setup({ initialSqlParameters: { product_id: 1024 } });
const lastQuery = fetchMock.callHistory.lastCall(
`path:/api/card/${TEST_CARD.id}/query`,
@@ -352,9 +326,7 @@ describe("InteractiveQuestion", () => {
it("should not flash an error when loading with an entity ID (metabase#57059)", async () => {
setupCardByEntityIdEndpoints({ ...TEST_CARD, entity_id: TEST_ENTITY_ID });
- setup({ cardId: TEST_ENTITY_ID });
-
- await waitForLoaderToBeRemoved();
+ await setup({ cardId: TEST_ENTITY_ID });
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
expect(
diff --git a/enterprise/frontend/src/embedding-sdk-bundle/test/auth-flow/jwt.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-bundle/test/auth-flow/jwt.unit.spec.tsx
index b99d9ef101d..e7f0d63a6f1 100644
--- a/enterprise/frontend/src/embedding-sdk-bundle/test/auth-flow/jwt.unit.spec.tsx
+++ b/enterprise/frontend/src/embedding-sdk-bundle/test/auth-flow/jwt.unit.spec.tsx
@@ -1,6 +1,10 @@
import { screen } from "@testing-library/react";
import fetchMock from "fetch-mock";
+import {
+ setupCurrentUserEndpoint,
+ setupPropertiesEndpoints,
+} from "__support__/server-mocks";
import { renderWithProviders, waitForLoaderToBeRemoved } from "__support__/ui";
import { waitForRequest } from "__support__/utils";
import { ComponentProvider } from "embedding-sdk-bundle/components/public/ComponentProvider";
@@ -148,6 +152,11 @@ describe("Auth Flow - JWT", () => {
// we can't use the usual mocks here as they use mocks that don't expect the subpath
const instanceUrlWithSubpath = `${MOCK_INSTANCE_URL}/subpath`;
+ // Set up base URL mocks FIRST, before subpath-specific mocks
+ // This test doesn't use the shared setup() function, so it needs its own mocks
+ setupCurrentUserEndpoint(createMockUser());
+ setupPropertiesEndpoints(createMockSettings());
+
fetchMock.get(`${instanceUrlWithSubpath}/auth/sso`, {
status: 200,
body: { url: MOCK_JWT_PROVIDER_URI, method: "jwt" },
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsx
index 24ff4287816..77d5050e2a5 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsx
@@ -1,6 +1,15 @@
import userEvent from "@testing-library/user-event";
+import {
+ setupCardEndpoints,
+ setupCardQueryMetadataEndpoint,
+} from "__support__/server-mocks";
import { screen } from "__support__/ui";
+import {
+ createMockCard,
+ createMockCardQueryMetadata,
+ createMockDatabase,
+} from "metabase-types/api/mocks";
import { setup } from "./test-setup";
@@ -98,6 +107,17 @@ describe("Embed flow > forward and backward navigation", () => {
describe("Embed flow > pre-selection via url parameter", () => {
it("pre-selects question when resource_type=question is in URL", async () => {
+ const mockDatabase = createMockDatabase();
+ const mockCard = createMockCard({ id: 456 });
+
+ setupCardEndpoints(mockCard);
+ setupCardQueryMetadataEndpoint(
+ mockCard,
+ createMockCardQueryMetadata({
+ databases: [mockDatabase],
+ }),
+ );
+
setup({
simpleEmbeddingEnabled: true,
urlSearchParams: "?resource_type=question&resource_id=456",
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/test-setup.tsx b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/test-setup.tsx
index f43f97df087..45710e28a48 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/test-setup.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/components/tests/test-setup.tsx
@@ -1,12 +1,18 @@
import {
findRequests,
setupDashboardEndpoints,
+ setupDashboardQueryMetadataEndpoint,
setupRecentViewsAndSelectionsEndpoints,
+ setupSearchEndpoints,
setupUpdateSettingEndpoint,
setupUpdateSettingsEndpoint,
} from "__support__/server-mocks";
import { renderWithProviders, waitFor } from "__support__/ui";
-import { createMockDashboard } from "metabase-types/api/mocks";
+import {
+ createMockDashboard,
+ createMockDashboardQueryMetadata,
+ createMockDatabase,
+} from "metabase-types/api/mocks";
import {
createMockSettingsState,
createMockState,
@@ -26,8 +32,17 @@ export const setup = (options?: {
jwtReady?: boolean;
urlSearchParams?: string;
}) => {
+ const mockDatabase = createMockDatabase();
+ const mockDashboard = createMockDashboard();
setupRecentViewsAndSelectionsEndpoints([], ["selections", "views"]);
- setupDashboardEndpoints(createMockDashboard());
+ setupSearchEndpoints([]);
+ setupDashboardEndpoints(mockDashboard);
+ setupDashboardQueryMetadataEndpoint(
+ mockDashboard,
+ createMockDashboardQueryMetadata({
+ databases: [mockDatabase],
+ }),
+ );
setupUpdateSettingsEndpoint();
setupUpdateSettingEndpoint();
diff --git a/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveSyncStatus.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveSyncStatus.unit.spec.tsx
index b4e7480a883..02f2fdfa23d 100644
--- a/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveSyncStatus.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveSyncStatus.unit.spec.tsx
@@ -2,8 +2,10 @@ import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
import {
+ setupDatabaseListEndpoint,
setupGdriveGetFolderEndpoint,
setupGdriveServiceAccountEndpoint,
+ setupTablesEndpoints,
} from "__support__/server-mocks";
import { act, renderWithProviders, screen, waitFor } from "__support__/ui";
import { useListDatabasesQuery, useListTablesQuery } from "metabase/api";
@@ -63,6 +65,9 @@ const setup = ({
);
+ setupDatabaseListEndpoint([]);
+ setupTablesEndpoints([]);
+
return renderWithProviders(<TestComponent />, {
storeInitialState: {
settings: createMockSettingsState(settings),
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.unit.spec.tsx
index 66adcc26346..238217e78df 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.unit.spec.tsx
@@ -3,6 +3,8 @@ import type { Editor } from "@tiptap/core";
import { useState } from "react";
import {
+ setupCollectionByIdEndpoint,
+ setupCollectionItemsEndpoint,
setupRecentViewsEndpoints,
setupSearchEndpoints,
} from "__support__/server-mocks";
@@ -320,6 +322,15 @@ describe("CommandSuggestion", () => {
// Setup with empty recent items to reproduce the bug
setupSearchEndpoints(SEARCH_ITEMS);
setupRecentViewsEndpoints([]);
+ setupCollectionByIdEndpoint({ collections: [] });
+ setupCollectionItemsEndpoint({
+ collection: { id: "root" },
+ collectionItems: [],
+ });
+ setupCollectionItemsEndpoint({
+ collection: { id: 1 },
+ collectionItems: [],
+ });
const command = jest.fn();
const editor = {
@@ -349,6 +360,15 @@ describe("CommandSuggestion", () => {
// Setup with empty recent items to reproduce the bug
setupSearchEndpoints(SEARCH_ITEMS);
setupRecentViewsEndpoints([]);
+ setupCollectionByIdEndpoint({ collections: [] });
+ setupCollectionItemsEndpoint({
+ collection: { id: "root" },
+ collectionItems: [],
+ });
+ setupCollectionItemsEndpoint({
+ collection: { id: 1 },
+ collectionItems: [],
+ });
const command = jest.fn();
const editor = {
diff --git a/frontend/src/metabase-types/api/mocks/index.ts b/frontend/src/metabase-types/api/mocks/index.ts
index 344e437eee7..bc7a6338910 100644
--- a/frontend/src/metabase-types/api/mocks/index.ts
+++ b/frontend/src/metabase-types/api/mocks/index.ts
@@ -38,3 +38,4 @@ export * from "./timeline";
export * from "./transform";
export * from "./undo";
export * from "./user";
+export * from "./util";
diff --git a/frontend/src/metabase-types/api/mocks/util.ts b/frontend/src/metabase-types/api/mocks/util.ts
new file mode 100644
index 00000000000..9ea62335cf8
--- /dev/null
+++ b/frontend/src/metabase-types/api/mocks/util.ts
@@ -0,0 +1,19 @@
+import type { MetabaseInfo } from "metabase-types/api";
+
+export const createMockMetabaseInfo = (
+ opts?: Partial<MetabaseInfo>,
+): MetabaseInfo => ({
+ "application-database": "h2",
+ "application-database-details": {},
+ databases: [],
+ "hosting-env": "unknown",
+ "run-mode": "dev",
+ settings: {},
+ version: {
+ date: "2024-01-01",
+ hash: "abc123",
+ src_hash: "def456",
+ tag: "v1.0.0",
+ },
+ ...opts,
+});
diff --git a/frontend/src/metabase/admin/settings/components/CloudPanel/CloudPanel.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/CloudPanel/CloudPanel.unit.spec.tsx
index cb33511710b..1a4d387866d 100644
--- a/frontend/src/metabase/admin/settings/components/CloudPanel/CloudPanel.unit.spec.tsx
+++ b/frontend/src/metabase/admin/settings/components/CloudPanel/CloudPanel.unit.spec.tsx
@@ -1,7 +1,10 @@
import userEvent from "@testing-library/user-event";
import fetchMock, { type UserRouteConfig } from "fetch-mock";
-import { setupPropertiesEndpoints } from "__support__/server-mocks";
+import {
+ setupBugReportingDetailsEndpoint,
+ setupPropertiesEndpoints,
+} from "__support__/server-mocks";
import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
import type { CloudMigration } from "metabase-types/api/cloud-migration";
import { createMockSettings, createMockUser } from "metabase-types/api/mocks";
@@ -37,9 +40,7 @@ describe("CloudPanel", () => {
setupPropertiesEndpoints(createMockSettings());
fetchMock.post(`path:/api/cloud-migration`, INIT_RESPONSE);
fetchMock.put(`path:/api/cloud-migration/cancel`, 200);
- fetchMock.get("path:/api/bug-reporting/details", {
- "metabase-info": { "run-mode": "prod" },
- });
+ setupBugReportingDetailsEndpoint({ "run-mode": "prod" });
});
it("should be able to successfully go through migration flow", async () => {
diff --git a/frontend/src/metabase/admin/settings/components/Email/SMTPConnectionCard/tests/setup.tsx b/frontend/src/metabase/admin/settings/components/Email/SMTPConnectionCard/tests/setup.tsx
index 14b1da6154b..3bd9575870d 100644
--- a/frontend/src/metabase/admin/settings/components/Email/SMTPConnectionCard/tests/setup.tsx
+++ b/frontend/src/metabase/admin/settings/components/Email/SMTPConnectionCard/tests/setup.tsx
@@ -1,10 +1,14 @@
import { setupEnterprisePlugins } from "__support__/enterprise";
-import { setupPropertiesEndpoints } from "__support__/server-mocks";
+import {
+ setupPropertiesEndpoints,
+ setupSettingsEndpoints,
+} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { renderWithProviders } from "__support__/ui";
import { SMTPConnectionCard } from "metabase/admin/settings/components/Email/SMTPConnectionCard/SMTPConnectionCard";
-import type { TokenFeatures } from "metabase-types/api";
+import type { SettingKey, TokenFeatures } from "metabase-types/api";
import {
+ createMockSettingDefinition,
createMockSettings,
createMockTokenFeatures,
} from "metabase-types/api/mocks";
@@ -30,6 +34,11 @@ export function setup({
};
setupPropertiesEndpoints(createMockSettings(settings));
+ setupSettingsEndpoints(
+ Object.entries(settings).map(([key, value]) =>
+ createMockSettingDefinition({ key: key as SettingKey, value }),
+ ),
+ );
const state = createMockState({ settings: mockSettings(settings) });
diff --git a/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHub.unit.spec.tsx b/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHub.unit.spec.tsx
index 0c05685a581..98934a1f43d 100644
--- a/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHub.unit.spec.tsx
+++ b/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHub.unit.spec.tsx
@@ -1,7 +1,9 @@
import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
import { push } from "react-router-redux";
import {
+ setupDatabaseListEndpoint,
setupRecentViewsAndSelectionsEndpoints,
setupSearchEndpoints,
} from "__support__/server-mocks";
@@ -48,6 +50,15 @@ const setup = ({ isAdmin = true } = {}) => {
);
setupSearchEndpoints([]);
+ setupDatabaseListEndpoint([]);
+
+ // Additional query param variant for uploadable databases
+ fetchMock.get({
+ url: "path:/api/database",
+ query: { include_only_uploadable: true },
+ response: { data: [], total: 0 },
+ });
+ fetchMock.get("path:/api/ee/embedding-hub/checklist", {});
return renderWithProviders(<EmbeddingHub />, { storeInitialState: state });
};
diff --git a/frontend/src/metabase/home/components/Onboarding/tests/setup.tsx b/frontend/src/metabase/home/components/Onboarding/tests/setup.tsx
index 49c84710018..ad6c59a36a8 100644
--- a/frontend/src/metabase/home/components/Onboarding/tests/setup.tsx
+++ b/frontend/src/metabase/home/components/Onboarding/tests/setup.tsx
@@ -1,7 +1,10 @@
import { Route } from "react-router";
import { setupEnterprisePlugins } from "__support__/enterprise";
-import { setupPropertiesEndpoints } from "__support__/server-mocks";
+import {
+ setupBugReportingDetailsEndpoint,
+ setupPropertiesEndpoints,
+} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { renderWithProviders } from "__support__/ui";
import type { TokenFeatures } from "metabase-types/api";
@@ -44,6 +47,7 @@ export const setup = ({
}: SetupProps = {}) => {
const hasTokenFeatures = Object.entries(tokenFeatures).length > 0;
setupPropertiesEndpoints(createMockSettings());
+ setupBugReportingDetailsEndpoint();
const state = createMockState({
app: createMockAppState({
tempStorage: {
diff --git a/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx b/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx
index e9f0bb75216..d0c8673f4e9 100644
--- a/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx
+++ b/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx
@@ -6,6 +6,7 @@ import { createMockMetadata } from "__support__/metadata";
import {
setupCardQueryMetadataEndpoint,
setupCardsEndpoints,
+ setupCardsUsingModelEndpoint,
setupCollectionsEndpoints,
setupDatabasesEndpoints,
setupModelActionsEndpoints,
@@ -199,13 +200,7 @@ async function setup({
const modelUpdateSpy = jest.spyOn(Models.actions, "update");
setupDatabasesEndpoints(databases);
-
- fetchMock.get({
- url: "path:/api/card",
- query: { f: "using_model", model_id: card.id },
- response: usedBy,
- });
-
+ setupCardsUsingModelEndpoint(card, usedBy);
setupCardsEndpoints([card]);
setupCardQueryMetadataEndpoint(
card,
diff --git a/frontend/src/metabase/nav/components/ProfileLink/ProfileLink.unit.spec.tsx b/frontend/src/metabase/nav/components/ProfileLink/ProfileLink.unit.spec.tsx
index 1bed9ebeba9..7331a29be8b 100644
--- a/frontend/src/metabase/nav/components/ProfileLink/ProfileLink.unit.spec.tsx
+++ b/frontend/src/metabase/nav/components/ProfileLink/ProfileLink.unit.spec.tsx
@@ -1,12 +1,13 @@
import userEvent from "@testing-library/user-event";
import dayjs from "dayjs";
-import fetchMock from "fetch-mock";
+import { setupBugReportingDetailsEndpoint } from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen, waitFor } from "__support__/ui";
import { ProfileLink } from "metabase/nav/components/ProfileLink";
import type { HelpLinkSetting } from "metabase-types/api";
import {
+ createMockMetabaseInfo,
createMockTokenStatus,
createMockUser,
} from "metabase-types/api/mocks";
@@ -74,7 +75,7 @@ function setupHosted(opts = {}) {
describe("ProfileLink", () => {
beforeEach(() => {
- fetchMock.get("path:/api/bug-reporting/details", "mockBugReportDetails");
+ setupBugReportingDetailsEndpoint();
});
describe("self-hosted", () => {
@@ -185,7 +186,7 @@ describe("ProfileLink", () => {
expect(link).toBeInTheDocument();
const mockBugReportDetails = encodeURIComponent(
- JSON.stringify("mockBugReportDetails"),
+ JSON.stringify(createMockMetabaseInfo()),
);
const expected = `https://www.metabase.com/help-premium?utm_source=in-product&utm_medium=menu&utm_campaign=help&instance_version=v1&diag=${mockBugReportDetails}`;
await waitFor(() => expect(link).toHaveProperty("href", expected));
diff --git a/frontend/src/metabase/nav/components/ProfileLink/useHelpLink.unit.spec.ts b/frontend/src/metabase/nav/components/ProfileLink/useHelpLink.unit.spec.ts
index 0da894ccb21..9c25ba27f93 100644
--- a/frontend/src/metabase/nav/components/ProfileLink/useHelpLink.unit.spec.ts
+++ b/frontend/src/metabase/nav/components/ProfileLink/useHelpLink.unit.spec.ts
@@ -1,5 +1,4 @@
-import fetchMock from "fetch-mock";
-
+import { setupBugReportingDetailsEndpoint } from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { renderHookWithProviders, waitFor } from "__support__/ui";
import type { HelpLinkSetting } from "metabase-types/api";
@@ -45,7 +44,7 @@ const premiumHelpLink =
describe("useHelpLink", () => {
beforeEach(() => {
- fetchMock.get("path:/api/bug-reporting/details", "");
+ setupBugReportingDetailsEndpoint();
});
describe("metabase help link", () => {
diff --git a/frontend/src/metabase/parameters/components/ValuesSourceModal/tests/setup.tsx b/frontend/src/metabase/parameters/components/ValuesSourceModal/tests/setup.tsx
index 6dd2529c231..665ff15b23c 100644
--- a/frontend/src/metabase/parameters/components/ValuesSourceModal/tests/setup.tsx
+++ b/frontend/src/metabase/parameters/components/ValuesSourceModal/tests/setup.tsx
@@ -65,12 +65,16 @@ export const setup = async ({
setupSearchEndpoints([]);
setupRecentViewsAndSelectionsEndpoints([]);
setupCollectionByIdEndpoint({
- collections: [personalCollection],
+ collections: [personalCollection, rootCollection],
});
setupCollectionItemsEndpoint({
collection: personalCollection,
collectionItems: [],
});
+ setupCollectionItemsEndpoint({
+ collection: rootCollection,
+ collectionItems: [],
+ });
if (hasCollectionAccess) {
setupCollectionsEndpoints({ collections: [rootCollection] });
diff --git a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetEditor.unit.spec.tsx b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetEditor.unit.spec.tsx
index 68ee6829fdd..fabbfad1593 100644
--- a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetEditor.unit.spec.tsx
+++ b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetEditor.unit.spec.tsx
@@ -4,6 +4,7 @@ import {
setupCollectionsEndpoints,
setupDatabasesEndpoints,
setupNativeQuerySnippetEndpoints,
+ setupRecentViewsAndSelectionsEndpoints,
} from "__support__/server-mocks";
import { renderWithProviders, screen } from "__support__/ui";
import { DatasetEditor } from "metabase/query_builder/components/DatasetEditor";
@@ -66,6 +67,7 @@ const renderDatasetEditor = async (card: Card | UnsavedCard) => {
setupDatabasesEndpoints([TEST_DB]);
setupCollectionsEndpoints({ collections: [ROOT_COLLECTION] });
setupNativeQuerySnippetEndpoints();
+ setupRecentViewsAndSelectionsEndpoints([], ["selections"]);
const question = new Question(card);
fetchMock.get("path:/api/search", { body: { data: [] } });
diff --git a/frontend/src/metabase/query_builder/components/view/sidebars/QuestionInfoSidebar/components/ModelUsageDetails.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/sidebars/QuestionInfoSidebar/components/ModelUsageDetails.unit.spec.tsx
index 253d8929ae4..633dcaa5f73 100644
--- a/frontend/src/metabase/query_builder/components/view/sidebars/QuestionInfoSidebar/components/ModelUsageDetails.unit.spec.tsx
+++ b/frontend/src/metabase/query_builder/components/view/sidebars/QuestionInfoSidebar/components/ModelUsageDetails.unit.spec.tsx
@@ -1,11 +1,11 @@
import userEvent from "@testing-library/user-event";
-import fetchMock from "fetch-mock";
import { Route } from "react-router";
import { createMockMetadata } from "__support__/metadata";
import {
setupCardQueryMetadataEndpoint,
setupCardsEndpoints,
+ setupCardsUsingModelEndpoint,
setupCollectionsEndpoints,
setupDatabasesEndpoints,
} from "__support__/server-mocks";
@@ -152,13 +152,7 @@ async function setup({
);
setupDatabasesEndpoints(databases);
-
- fetchMock.get({
- url: "path:/api/card",
- query: { f: "using_model", model_id: card.id },
- response: usedBy,
- });
-
+ setupCardsUsingModelEndpoint(card, usedBy);
setupCardsEndpoints([card]);
setupCardQueryMetadataEndpoint(
card,
diff --git a/frontend/src/metabase/query_builder/components/view/sidebars/QuestionInfoSidebar/tests/setup.tsx b/frontend/src/metabase/query_builder/components/view/sidebars/QuestionInfoSidebar/tests/setup.tsx
index 54b4c425666..a46e387bcf9 100644
--- a/frontend/src/metabase/query_builder/components/view/sidebars/QuestionInfoSidebar/tests/setup.tsx
+++ b/frontend/src/metabase/query_builder/components/view/sidebars/QuestionInfoSidebar/tests/setup.tsx
@@ -4,6 +4,7 @@ import { setupEnterprisePlugins } from "__support__/enterprise";
import {
setupAuditInfoEndpoint,
setupCardEndpoints,
+ setupCardsUsingModelEndpoint,
setupRevisionsEndpoints,
setupTokenStatusEndpoint,
setupUsersEndpoints,
@@ -43,6 +44,7 @@ export const setup = async ({
}: SetupOpts = {}) => {
const currentUser = createMockUser(user);
setupCardEndpoints(card);
+ setupCardsUsingModelEndpoint(card);
setupUsersEndpoints([currentUser]);
setupRevisionsEndpoints([]);
setupPerformanceEndpoints([]);
diff --git a/frontend/test/__support__/server-mocks/bug-report.ts b/frontend/test/__support__/server-mocks/bug-report.ts
index 9632cde45f5..8fa5de96ce3 100644
--- a/frontend/test/__support__/server-mocks/bug-report.ts
+++ b/frontend/test/__support__/server-mocks/bug-report.ts
@@ -1,5 +1,8 @@
import fetchMock from "fetch-mock";
+import type { MetabaseInfo } from "metabase-types/api";
+import { createMockMetabaseInfo } from "metabase-types/api/mocks";
+
export const setupBugReportEndpoints = (responses = [{ success: true }]) => {
fetchMock.post(
"path:/api/slack/bug-report",
@@ -9,3 +12,12 @@ export const setupBugReportEndpoints = (responses = [{ success: true }]) => {
},
);
};
+
+export const setupBugReportingDetailsEndpoint = (
+ info: Partial<MetabaseInfo> = {},
+) => {
+ fetchMock.get(
+ "path:/api/bug-reporting/details",
+ createMockMetabaseInfo(info),
+ );
+};
diff --git a/frontend/test/__support__/server-mocks/card.ts b/frontend/test/__support__/server-mocks/card.ts
index 8f7f2aee0e6..6b20a92eadf 100644
--- a/frontend/test/__support__/server-mocks/card.ts
+++ b/frontend/test/__support__/server-mocks/card.ts
@@ -65,6 +65,14 @@ export function setupCardsEndpoints(cards: Card[]) {
cards.forEach((card) => setupCardEndpoints(card));
}
+export function setupCardsUsingModelEndpoint(card: Card, usedBy: Card[] = []) {
+ fetchMock.get({
+ url: "path:/api/card",
+ query: { f: "using_model", model_id: card.id },
+ response: usedBy,
+ });
+}
+
export function setupCardCreateEndpoint() {
fetchMock.post(
"path:/api/card",
diff --git a/frontend/test/jest-setup-env.js b/frontend/test/jest-setup-env.js
index a50a9fa317c..6cd65f0be0b 100644
--- a/frontend/test/jest-setup-env.js
+++ b/frontend/test/jest-setup-env.js
@@ -1,30 +1,31 @@
import "@testing-library/jest-dom";
+import { cleanup } from "@testing-library/react";
import fetchMock from "fetch-mock";
-// Fail tests on any unmocked fetch requests
-// errors in fetchMock.catch don't fail the test immediately, so we need to
-// collect them and fail the test in afterEach
-let unmockedRouteErrors = [];
-
beforeEach(() => {
- unmockedRouteErrors = [];
fetchMock.mockGlobal();
- fetchMock.catch((callLog) => {
- const { url, options } = callLog;
- const errorMessage = `Unmocked ${options.method} request to: ${url}`;
- unmockedRouteErrors.push(errorMessage);
- throw new Error(errorMessage);
- });
});
-afterEach(() => {
+afterEach(async () => {
+ // Cleanup React components FIRST to trigger any unmount effects
+ cleanup();
+ // Wait for any pending fetch requests to complete
+ await fetchMock.callHistory.flush();
+
+ // Fail the test if there were any unmocked routes
+ const calls = fetchMock.callHistory.calls();
+ const unmatched = calls.filter((call) => !call.route);
+
+ // ensure we always reset, even if there were unmatched calls
fetchMock.removeRoutes();
fetchMock.callHistory.clear();
- // Fail the test if there were any unmocked routes
- if (unmockedRouteErrors.length > 0) {
- const errors = unmockedRouteErrors.join("\n");
- unmockedRouteErrors = [];
- throw new Error(`Test completed with unmocked routes:\n${errors}`);
+ if (unmatched.length > 0) {
+ const errors = unmatched.map(
+ (call) => `Unmocked ${call.options.method} request to: ${call.url}`,
+ );
+ throw new Error(
+ `Test completed with unmocked routes:\n${errors.join("\n")}`,
+ );
}
});