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
test: cleanup jest warnings from query_builder folder (#74640)
Uladzimir Havenchyk07ba1d345972
diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.tsindex 4c66260f170..b5cdf0d24ab 100644--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts@@ -169,9 +169,19 @@ const NATIVE_QUESTION_WITH_SNIPPET: NativeDatasetQuery = {},};+// Silence `console.warn` / `console.error` at module load so that describe-body+// invocations of `setErrorPage(...)` (which logs via `console.error`) don't+// produce noise. `beforeAll` would fire too late — describes are registered+// during module evaluation.+const originalWarn = console.warn;+const originalError = console.error;+console.warn = jest.fn();+console.error = jest.fn();+describe("QB Actions > initializeQB", () => {- beforeAll(() => {- console.warn = jest.fn();+ afterAll(() => {+ console.warn = originalWarn;+ console.error = originalError;});afterEach(() => {diff --git a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetQueryEditor.jsx b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetQueryEditor.jsxindex d864447eed8..4195a6533c1 100644--- a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetQueryEditor.jsx+++ b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetQueryEditor.jsx@@ -25,7 +25,9 @@ const SMOOTH_RESIZE_STYLE = { transition: "height 0.25s" };const propTypes = {question: PropTypes.object.isRequired,isActive: PropTypes.bool.isRequired, // if QB mode is set to "query"- availableHeight: PropTypes.number.isRequired,+ // optional: derived from a measured container, so it is undefined until+ // the container has been laid out (e.g. on first render and in jsdom).+ availableHeight: PropTypes.number,height: PropTypes.number.isRequired,onSetDatabaseId: PropTypes.func,};diff --git a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetQueryEditor.unit.spec.tsx b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetQueryEditor.unit.spec.tsxindex 3b6b377f06c..5fe61ec79e3 100644--- a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetQueryEditor.unit.spec.tsx+++ b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetQueryEditor.unit.spec.tsx@@ -7,7 +7,12 @@ import {setupUserMetabotPermissionsEndpoint,} from "__support__/server-mocks";import { createMockEntitiesState } from "__support__/store";-import { renderWithProviders, screen } from "__support__/ui";+import {+ renderWithProviders,+ screen,+ waitFor,+ waitForLoaderToBeRemoved,+} from "__support__/ui";import { createMockState } from "metabase/redux/store/mocks";import { getMetadata } from "metabase/selectors/metadata";import { checkNotNull } from "metabase/utils/types";@@ -37,6 +42,7 @@ const ROOT_COLLECTION = createMockCollection({ id: "root" });interface SetupOpts {card?: Card;height?: number;+ availableHeight?: number;isActive: boolean;readOnly?: boolean;}@@ -44,6 +50,7 @@ interface SetupOpts {const setup = async ({card = TEST_NATIVE_CARD,height = 300,+ availableHeight = 600,isActive,readOnly = false,}: SetupOpts) => {@@ -68,6 +75,7 @@ const setup = async ({<DatasetQueryEditorisActive={isActive}height={height}+ availableHeight={availableHeight}query={query}question={question}readOnly={readOnly}@@ -77,6 +85,9 @@ const setup = async ({/>,);+ // required for preventing memory leak+ await waitForLoaderToBeRemoved();+return { query, question, rerender };};@@ -144,6 +155,7 @@ describe("DatasetQueryEditor", () => {<DatasetQueryEditorisActive={false}height={0}+ availableHeight={600}query={query}question={question}readOnly={false}@@ -152,8 +164,10 @@ describe("DatasetQueryEditor", () => {/>,);- expect(- screen.queryByTestId("native-query-editor-action-buttons"),- ).not.toBeInTheDocument();+ await waitFor(() => {+ expect(+ screen.queryByTestId("native-query-editor-action-buttons"),+ ).not.toBeInTheDocument();+ });});});diff --git a/frontend/src/metabase/query_builder/components/QuestionDownloadWidget/QuestionDownloadWidget.unit.spec.tsx b/frontend/src/metabase/query_builder/components/QuestionDownloadWidget/QuestionDownloadWidget.unit.spec.tsxindex 71943b20b46..e7312e5e5e0 100644--- a/frontend/src/metabase/query_builder/components/QuestionDownloadWidget/QuestionDownloadWidget.unit.spec.tsx+++ b/frontend/src/metabase/query_builder/components/QuestionDownloadWidget/QuestionDownloadWidget.unit.spec.tsx@@ -6,7 +6,7 @@ import {} from "__support__/server-mocks";import { mockSettings } from "__support__/settings";import { createMockEntitiesState } from "__support__/store";-import { act, renderWithProviders, screen } from "__support__/ui";+import { renderWithProviders, screen } from "__support__/ui";import { QuestionDownloadWidget } from "metabase/common/components/QuestionDownloadWidget";import { createMockState } from "metabase/redux/store/mocks";import { getMetadata } from "metabase/selectors/metadata";@@ -94,7 +94,7 @@ describe("QuestionDownloadWidget", () => {it("should trigger download on click", async () => {const { onDownload } = setup();- await act(async () => await userEvent.click(screen.getByText(/csv/)));+ await userEvent.click(screen.getByText(/csv/));await userEvent.click(await screen.findByTestId("download-results-button"));expect(onDownload).toHaveBeenCalledWith({type: "csv",diff --git a/frontend/src/metabase/query_builder/components/template_tags/TagEditorHelp/TagEditorHelp.tsx b/frontend/src/metabase/query_builder/components/template_tags/TagEditorHelp/TagEditorHelp.tsxindex d3a42fbd517..f7d7a7c5ff8 100644--- a/frontend/src/metabase/query_builder/components/template_tags/TagEditorHelp/TagEditorHelp.tsx+++ b/frontend/src/metabase/query_builder/components/template_tags/TagEditorHelp/TagEditorHelp.tsx@@ -5,7 +5,7 @@ import { Button } from "metabase/common/components/Button";import { ExternalLink } from "metabase/common/components/ExternalLink";import { useDocsUrl } from "metabase/common/hooks";import CS from "metabase/css/core/index.css";-import { Code } from "metabase/ui";+import { Box, Code } from "metabase/ui";import { uuid } from "metabase/utils/uuid";import type Database from "metabase-lib/v1/metadata/Database";import type { DatabaseId, NativeDatasetQuery } from "metabase-types/api";@@ -204,7 +204,7 @@ interface TagExampleProps {const TagExample = ({ datasetQuery, setDatasetQuery }: TagExampleProps) => (<div><h5>{t`Example:`}</h5>- <p>+ <Box py="sm"><Code block>{datasetQuery.native.query}</Code>{setDatasetQuery && (<Button@@ -215,7 +215,7 @@ const TagExample = ({ datasetQuery, setDatasetQuery }: TagExampleProps) => ({t`Try it`}</Button>)}- </p>+ </Box></div>);diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.enterprise.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.enterprise.unit.spec.tsxindex bb9718ec576..820022b168b 100644--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.enterprise.unit.spec.tsx+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.enterprise.unit.spec.tsx@@ -1,6 +1,6 @@import userEvent from "@testing-library/user-event";-import { screen } from "__support__/ui";+import { screen, waitFor } from "__support__/ui";import { createMockCollection } from "metabase-types/api/mocks";import { setupQuestionSharingMenu } from "./tests/setup";@@ -31,12 +31,18 @@ describe("QuestionSharingMenu > Enterprise", () => {await userEvent.click(screen.getByTestId("sharing-menu-button"));+ // popover content mounts asynchronously after the clickexpect(- screen.getByTestId("public-link-popover-content"),+ await screen.findByTestId("public-link-popover-content"),).toBeInTheDocument();- expect(screen.getByTestId("public-link-input")).toHaveDisplayValue(+ const input = screen.getByTestId("public-link-input");+ expect(input).toHaveDisplayValue("http://localhost:3000/public/question/1337bad801",);++ // the input drops its loading placeholder once the link-loading+ // effect resolves+ await waitFor(() => expect(input).not.toHaveAttribute("placeholder"));});it("should show a 'ask your admin to create a public link' tooltip if public sharing is disabled", async () => {diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.unit.spec.tsxindex 75a980cf7e0..2b46fef044b 100644--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.unit.spec.tsx+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.unit.spec.tsx@@ -1,19 +1,19 @@import userEvent from "@testing-library/user-event";-import { screen } from "__support__/ui";+import { screen, waitFor } from "__support__/ui";import { openMenu, setupQuestionSharingMenu } from "./tests/setup";describe("QuestionSharingMenu", () => {it("should not render anything if the question is a model", async () => {- setupQuestionSharingMenu({+ await setupQuestionSharingMenu({question: { type: "model" },});expect(screen.queryByTestId("sharing-menu-button")).not.toBeInTheDocument();});- it("should have a 'sharing' tooltip by default", () => {- setupQuestionSharingMenu({+ it("should have a 'sharing' tooltip by default", async () => {+ await setupQuestionSharingMenu({isAdmin: true,});expect(screen.getByTestId("sharing-menu-button")).toHaveAttribute(@@ -23,7 +23,7 @@ describe("QuestionSharingMenu", () => {});it("should not appear for archived questions", async () => {- setupQuestionSharingMenu({+ await setupQuestionSharingMenu({isAdmin: true,question: { archived: true },});@@ -32,7 +32,7 @@ describe("QuestionSharingMenu", () => {});it("should prompt you to save an unsaved question", async () => {- setupQuestionSharingMenu({+ await setupQuestionSharingMenu({isAdmin: true,question: { id: undefined },});@@ -46,7 +46,7 @@ describe("QuestionSharingMenu", () => {describe("public links", () => {describe("admins", () => {it('should show a "Create Public link" menu item if public sharing is enabled', async () => {- setupQuestionSharingMenu({+ await setupQuestionSharingMenu({isAdmin: true,isPublicSharingEnabled: true,});@@ -55,7 +55,7 @@ describe("QuestionSharingMenu", () => {});it("clicking the sharing button should open the public link popover", async () => {- setupQuestionSharingMenu({+ await setupQuestionSharingMenu({isAdmin: true,isPublicSharingEnabled: true,hasPublicLink: true,@@ -64,15 +64,21 @@ describe("QuestionSharingMenu", () => {await userEvent.click(screen.getByText("Public link"));expect(- screen.getByTestId("public-link-popover-content"),+ await screen.findByTestId("public-link-popover-content"),).toBeInTheDocument();- expect(screen.getByTestId("public-link-input")).toHaveDisplayValue(- "http://localhost:3000/public/question/1337bad801",- );++ // The PublicLinkPopover's useAsync hook flips its loading state after+ // the popover mounts; wait for the input to receive the public link url+ // so that state update stays wrapped in act.+ await waitFor(() => {+ expect(screen.getByTestId("public-link-input")).toHaveDisplayValue(+ "http://localhost:3000/public/question/1337bad801",+ );+ });});it('should show a "Public link" menu item if public sharing is enabled and a public link exists already', async () => {- setupQuestionSharingMenu({+ await setupQuestionSharingMenu({isAdmin: true,isPublicSharingEnabled: true,hasPublicLink: true,@@ -85,7 +91,7 @@ describe("QuestionSharingMenu", () => {});it('should show an "Enable" link if public sharing is disabled', async () => {- setupQuestionSharingMenu({+ await setupQuestionSharingMenu({isAdmin: true,isPublicSharingEnabled: false,});@@ -102,7 +108,7 @@ describe("QuestionSharingMenu", () => {describe("non-admins", () => {it('should show a "Public link" menu item if there is a public link for the question', async () => {- setupQuestionSharingMenu({+ await setupQuestionSharingMenu({isAdmin: false,isPublicSharingEnabled: true,hasPublicLink: true,@@ -112,7 +118,7 @@ describe("QuestionSharingMenu", () => {});it('should show an "Ask your admin to create a public link" menu item if there is no public link for the question', async () => {- setupQuestionSharingMenu({+ await setupQuestionSharingMenu({isAdmin: false,isPublicSharingEnabled: true,hasPublicLink: false,@@ -128,7 +134,7 @@ describe("QuestionSharingMenu", () => {describe("embedding", () => {describe("non-admins", () => {it("should not show the 'Embed' menu item if embedding is enabled", async () => {- setupQuestionSharingMenu({+ await setupQuestionSharingMenu({isAdmin: false,isEmbeddingEnabled: true,});@@ -137,7 +143,7 @@ describe("QuestionSharingMenu", () => {});it("should not show the 'Embed' menu item if embedding is disabled", async () => {- setupQuestionSharingMenu({+ await setupQuestionSharingMenu({isAdmin: false,isEmbeddingEnabled: false,});diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/tests/setup.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/tests/setup.tsxindex 7c117527139..116a83446d9 100644--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/tests/setup.tsx+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/tests/setup.tsx@@ -92,7 +92,7 @@ const setupState = ({});};-export function setupQuestionSharingMenu({+export async function setupQuestionSharingMenu({isPublicSharingEnabled = false,isEmbeddingEnabled = false,isEmailSetup = false,@@ -147,8 +147,19 @@ export function setupQuestionSharingMenu({</div>,{ storeInitialState: state },);++ // QuestionSharingMenu eagerly mounts QuestionPublicLinkPopover, whose+ // useAsync hook flips its loading state shortly after mount. Wait for the+ // sharing menu button to settle so that async update stays wrapped in act.+ // Some scenarios (models, archived questions) render nothing at all, so we+ // only wait when the button is expected to appear.+ const isModel = questionOverrides.type === "model";+ const isArchived = questionOverrides.archived === true;+ if (!isModel && !isArchived) {+ await screen.findByTestId("sharing-menu-button");+ }}-export const openMenu = () => {- return userEvent.click(screen.getByTestId("sharing-menu-button"));+export const openMenu = async () => {+ await userEvent.click(screen.getByTestId("sharing-menu-button"));};diff --git a/frontend/src/metabase/query_builder/containers/QueryBuilder.beforeunload-events.unit.spec.tsx b/frontend/src/metabase/query_builder/containers/QueryBuilder.beforeunload-events.unit.spec.tsxindex 76b49bc0424..be32bf0deb3 100644--- a/frontend/src/metabase/query_builder/containers/QueryBuilder.beforeunload-events.unit.spec.tsx+++ b/frontend/src/metabase/query_builder/containers/QueryBuilder.beforeunload-events.unit.spec.tsx@@ -3,6 +3,7 @@ import userEvent from "@testing-library/user-event";import { callMockEvent } from "__support__/events";import { setupLastDownloadFormatEndpoints } from "__support__/server-mocks";import { screen, waitForLoaderToBeRemoved, within } from "__support__/ui";+import { mockGetBoundingClientRect } from "__support__/utils";import { BEFORE_UNLOAD_UNSAVED_MESSAGE } from "metabase/common/hooks/use-before-unload";import registerVisualizations from "metabase/visualizations/register";@@ -26,20 +27,16 @@ registerVisualizations();describe("QueryBuilder - beforeunload events", () => {const scrollBy = HTMLElement.prototype.scrollBy;- const getBoundingClientRect = HTMLElement.prototype.getBoundingClientRect;++ mockGetBoundingClientRect();beforeEach(() => {HTMLElement.prototype.scrollBy = jest.fn();- // needed for @tanstack/react-virtual, see https://github.com/TanStack/virtual/issues/29#issuecomment-657519522- HTMLElement.prototype.getBoundingClientRect = jest- .fn()- .mockReturnValue({ height: 1, width: 1 });setupLastDownloadFormatEndpoints();});afterEach(() => {HTMLElement.prototype.scrollBy = scrollBy;- HTMLElement.prototype.getBoundingClientRect = getBoundingClientRect;jest.resetAllMocks();});diff --git a/frontend/src/metabase/query_builder/containers/QueryBuilder.unsaved-changes-warning.unit.spec.tsx b/frontend/src/metabase/query_builder/containers/QueryBuilder.unsaved-changes-warning.unit.spec.tsxindex 67dfc88f455..514591ee2fc 100644--- a/frontend/src/metabase/query_builder/containers/QueryBuilder.unsaved-changes-warning.unit.spec.tsx+++ b/frontend/src/metabase/query_builder/containers/QueryBuilder.unsaved-changes-warning.unit.spec.tsx@@ -15,6 +15,7 @@ import {waitForLoaderToBeRemoved,within,} from "__support__/ui";+import { mockGetBoundingClientRect } from "__support__/utils";import { serializeCardForUrl } from "metabase/common/utils/card";import registerVisualizations from "metabase/visualizations/register";import {@@ -47,19 +48,15 @@ registerVisualizations();describe("QueryBuilder - unsaved changes warning", () => {const scrollBy = HTMLElement.prototype.scrollBy;- const getBoundingClientRect = HTMLElement.prototype.getBoundingClientRect;++ mockGetBoundingClientRect();beforeEach(() => {HTMLElement.prototype.scrollBy = jest.fn();- // needed for @tanstack/react-virtual, see https://github.com/TanStack/virtual/issues/29#issuecomment-657519522- HTMLElement.prototype.getBoundingClientRect = jest- .fn()- .mockReturnValue({ height: 1, width: 1 });});afterEach(() => {HTMLElement.prototype.scrollBy = scrollBy;- HTMLElement.prototype.getBoundingClientRect = getBoundingClientRect;jest.resetAllMocks();setupJestCanvasMock();diff --git a/frontend/src/metabase/querying/selectors.ts b/frontend/src/metabase/querying/selectors.tsindex ddec4c42f2e..02c57749eb0 100644--- a/frontend/src/metabase/querying/selectors.ts+++ b/frontend/src/metabase/querying/selectors.ts@@ -1,12 +1,11 @@import { createSelector } from "@reduxjs/toolkit";import _ from "underscore";-import type { State } from "metabase/redux/store";import { getMetadata } from "metabase/selectors/metadata";-import type Database from "metabase-lib/v1/metadata/Database";-export const getDatabasesList = (state: State): Database[] =>- getMetadata(state).databasesList();+export const getDatabasesList = createSelector([getMetadata], (metadata) =>+ metadata.databasesList(),+);export const getSampleDatabaseId = createSelector([getDatabasesList],diff --git a/frontend/test/__support__/mocks.js b/frontend/test/__support__/mocks.jsindex b6eec019099..187e3fc1122 100644--- a/frontend/test/__support__/mocks.js+++ b/frontend/test/__support__/mocks.js@@ -32,7 +32,18 @@ jest.mock("@uiw/react-codemirror", () => {const { forwardRef } = jest.requireActual("react");const MockEditor = forwardRef((props, ref) => {- const { indentWithTab, extensions, basicSetup, editable, ...rest } = props;+ const {+ indentWithTab,+ extensions,+ basicSetup,+ editable,+ // CodeMirror-specific callbacks that React would warn about if spread+ // onto the underlying <textarea>.+ onUpdate,+ onCreateEditor,+ onStatistics,+ ...rest+ } = props;return (// @ts-expect-error: some props types are different on CodeMirror<textareadiff --git a/frontend/test/__support__/utils.ts b/frontend/test/__support__/utils.tsindex be996d9945a..109f56072c2 100644--- a/frontend/test/__support__/utils.ts+++ b/frontend/test/__support__/utils.ts@@ -18,6 +18,46 @@ export async function delay(duration: number) {});}+const DEFAULT_BOUNDING_CLIENT_RECT: DOMRect = {+ height: 1,+ width: 1,+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ x: 0,+ y: 0,+ toJSON: () => ({}),+};++/**+ * Mocks `HTMLElement.prototype.getBoundingClientRect` for the enclosing+ * `describe` block. Registers its own `beforeEach`/`afterEach`, so it only+ * needs to be called once in the `describe` body.+ *+ * jsdom always reports a zero-sized rect, which breaks `@tanstack/react-virtual`+ * (it renders no virtualized rows). See+ * https://github.com/TanStack/virtual/issues/29#issuecomment-657519522+ *+ * The default rect has a non-zero `width`/`height` but zeroed positions, so+ * floating-ui (used by Mantine popovers) does not compute a `NaN` offset from+ * otherwise-undefined `top`/`left`.+ */+export function mockGetBoundingClientRect(rect: Partial<DOMRect> = {}) {+ const original = HTMLElement.prototype.getBoundingClientRect;++ beforeEach(() => {+ HTMLElement.prototype.getBoundingClientRect = jest.fn(() => ({+ ...DEFAULT_BOUNDING_CLIENT_RECT,+ ...rect,+ }));+ });++ afterEach(() => {+ HTMLElement.prototype.getBoundingClientRect = original;+ });+}+/** Waits for a request to have been made. It's useful to wait for a request and* then check its details separately, to make tests less flaky and to have* better failure messages (request arrived but wrong details vs request neverdiff --git a/frontend/test/jest-setup.js b/frontend/test/jest-setup.jsindex 1df1d158132..752a07a4bae 100644--- a/frontend/test/jest-setup.js+++ b/frontend/test/jest-setup.js@@ -16,6 +16,20 @@ process.on("uncaughtException", (err) =>console.error("WARNING: UNCAUGHT EXCEPTION", err),);+// Mantine 8 uses React 19's callback-ref cleanup signature, which React 18+// flags with this warning. Harmless until we upgrade to React 19.+const originalConsoleError = console.error;+console.error = (...args) => {+ const first = args[0];+ if (+ typeof first === "string" &&+ first.includes("Unexpected return value from a callback ref")+ ) {+ return;+ }+ originalConsoleError(...args);+};+if (process.env["DISABLE_LOGGING"] || process.env["DISABLE_LOGGING_FRONTEND"]) {global.console = {log: jest.fn(),