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
Fail unit tests on React act warnings (#83063)
Romeo Van Snick53749afee129
diff --git a/enterprise/frontend/src/embedding/data-picker/DataSelector/tests/DataSelector.unit.spec.tsx b/enterprise/frontend/src/embedding/data-picker/DataSelector/tests/DataSelector.unit.spec.tsxindex b3436a38da3..ce0918dcbe7 100644--- a/enterprise/frontend/src/embedding/data-picker/DataSelector/tests/DataSelector.unit.spec.tsx+++ b/enterprise/frontend/src/embedding/data-picker/DataSelector/tests/DataSelector.unit.spec.tsx@@ -4,7 +4,7 @@ import type { ComponentProps } from "react";import { createMockState } from "__support__/state";import { createMockEntitiesState } from "__support__/store";import { getIcon, render, screen } from "__support__/ui";-import { delay } from "__support__/utils";+import { delay, waitForRequestsToSettle } from "__support__/utils";import { getEntityLookups } from "metabase/querying/common/components/DataSelector";import { checkNotNull } from "metabase/utils/types";import { createMockDatabase, createMockTable } from "metabase-types/api/mocks";@@ -376,7 +376,7 @@ describe("DataSelector", () => {expect(getIcon("chevrondown")).toBeInTheDocument();});- it("should open database picker with correct database selected", () => {+ it("should open database picker with correct database selected", async () => {render(<DataSelectorsteps={["DATABASE"]}@@ -389,7 +389,7 @@ describe("DataSelector", () => {);expect(- screen.getByRole("heading", { name: "Sample Database" }),+ await screen.findByRole("heading", { name: "Sample Database" }),).toBeInTheDocument();});@@ -441,7 +441,7 @@ describe("DataSelector", () => {expect(screen.getByText("Orders")).toBeInTheDocument();});- it("shows an empty state without any databases", () => {+ it("shows an empty state without any databases", async () => {render(<DataSelectorsteps={["DATABASE", "SCHEMA", "TABLE"]}@@ -450,6 +450,7 @@ describe("DataSelector", () => {isOpen={true}/>,);+ await waitForRequestsToSettle();expect(screen.getByText("To pick some data, you'll need to add some first"),diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsxindex cd709e60327..170559ca72c 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx@@ -1,7 +1,7 @@import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";-import { act, screen, waitFor, within } from "__support__/ui";+import { screen, waitFor, within } from "__support__/ui";import type { SetupOpts } from "metabase/admin/performance/components/test-utils";import {setupStrategyEditorForDatabases as baseSetup,@@ -38,8 +38,11 @@ function setup(opts: SetupOpts = {}) {}describe("StrategyEditorForDatabases", () => {- beforeEach(() => {+ beforeEach(async () => {setup();+ // Let the initial data load settle, so a request does not resolve mid-test+ // and rerender outside act().+ await screen.findByLabelText(/Edit default policy/);});it("lets user override root strategy on enterprise instance", async () => {@@ -202,10 +205,8 @@ describe("StrategyEditorForDatabases", () => {expect((await screen.findAllByRole("spinbutton")).length).toBe(2);- await act(async () => {- await changeInput(/minimum query duration/i, 1, 5);- await changeInput(/multiplier/i, 10, 3);- });+ await changeInput(/minimum query duration/i, 1, 5);+ await changeInput(/multiplier/i, 10, 3);await userEvent.click(await screen.findByTestId("strategy-form-submit-button"),@@ -255,31 +256,6 @@ describe("StrategyEditorForDatabases", () => {).toBeInTheDocument();});- it("can abbreviate a 'Schedule' strategy", () => {- const strategy: ScheduleStrategy = {- type: "schedule",- schedule: "0 0 * * * ?",- refresh_automatically: false,- };- const result = getShortStrategyLabel(strategy);- expect(result).toBe("Scheduled: hourly");- });-- it.each([- [CacheDurationUnit.Hours, "Duration: 5h"],- [CacheDurationUnit.Minutes, "Duration: 5m"],- [CacheDurationUnit.Seconds, "Duration: 5s"],- [CacheDurationUnit.Days, "Duration: 5d"],- ])("can abbreviate a 'Duration' strategy with unit %s", (unit, expected) => {- const strategy: DurationStrategy = {- type: "duration",- duration: 5,- unit,- refresh_automatically: false,- };- expect(getShortStrategyLabel(strategy)).toBe(expected);- });-it("does not silently save default values when saving right after switching strategies", async () => {// Database 4 inherits the default policyawait userEvent.click(@@ -371,6 +347,33 @@ describe("StrategyEditorForDatabases", () => {});});+describe("getShortStrategyLabel", () => {+ it("can abbreviate a 'Schedule' strategy", () => {+ const strategy: ScheduleStrategy = {+ type: "schedule",+ schedule: "0 0 * * * ?",+ refresh_automatically: false,+ };+ const result = getShortStrategyLabel(strategy);+ expect(result).toBe("Scheduled: hourly");+ });++ it.each([+ [CacheDurationUnit.Hours, "Duration: 5h"],+ [CacheDurationUnit.Minutes, "Duration: 5m"],+ [CacheDurationUnit.Seconds, "Duration: 5s"],+ [CacheDurationUnit.Days, "Duration: 5d"],+ ])("can abbreviate a 'Duration' strategy with unit %s", (unit, expected) => {+ const strategy: DurationStrategy = {+ type: "duration",+ duration: 5,+ unit,+ refresh_automatically: false,+ };+ expect(getShortStrategyLabel(strategy)).toBe(expected);+ });+});+describe("StrategyEditorForDatabases (table behaviors)", () => {it("keeps the default policy row pinned at the top", async () => {setup();diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsxindex 1a5a0726843..15f62f665f1 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx@@ -66,10 +66,12 @@ describe("DataAppView", () => {expect(screen.getByText("Data app not found")).toBeInTheDocument();});- it("shows a generic error screen for an unexpected failure", () => {+ it("shows a generic error screen for an unexpected failure", async () => {setup({ error: { status: 500 } });- expect(screen.getByText("Couldn’t load this data app")).toBeInTheDocument();+ expect(+ await screen.findByText("Couldn’t load this data app"),+ ).toBeInTheDocument();});it("shows a permission error when the user cannot access the data app", () => {@@ -246,7 +248,7 @@ describe("DataAppView", () => {});}- it("shows an error instead of spinning when framing is blocked by CSP", () => {+ it("shows an error instead of spinning when framing is blocked by CSP", async () => {setupIframe();expect(screen.getByTestId("data-app-loading")).toBeInTheDocument();@@ -255,9 +257,10 @@ describe("DataAppView", () => {expect(screen.getByText("Couldn’t load this data app"),).toBeInTheDocument();+ await screen.findByText("Show error details");});- it("shows an error when the iframe never signals it loaded", () => {+ it("shows an error when the iframe never signals it loaded", async () => {jest.useFakeTimers();try {setupIframe();@@ -273,6 +276,7 @@ describe("DataAppView", () => {} finally {jest.useRealTimers();}+ await screen.findByText("Show error details");});it("does not error once the app reports ready before the timeout", () => {@@ -297,7 +301,7 @@ describe("DataAppView", () => {}});- it("keeps the first error's reason — the timeout can't overwrite the CSP one", () => {+ it("keeps the first error's reason — the timeout can't overwrite the CSP one", async () => {jest.useFakeTimers();try {setupIframe();@@ -318,6 +322,7 @@ describe("DataAppView", () => {} finally {jest.useRealTimers();}+ await screen.findByText("Show error details");});});});diff --git a/enterprise/frontend/src/metabase-enterprise/license/use-upsell-flow.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/license/use-upsell-flow.unit.spec.tsxindex 97caa7203b2..6f6c51b7c93 100644--- a/enterprise/frontend/src/metabase-enterprise/license/use-upsell-flow.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/license/use-upsell-flow.unit.spec.tsx@@ -1,3 +1,5 @@+import userEvent from "@testing-library/user-event";+import {findRequests,setupTokenActivationEndpoint,@@ -6,7 +8,7 @@ import {} from "__support__/server-mocks";import { mockSettings } from "__support__/settings";import { createMockState } from "__support__/state";-import { renderWithProviders, screen, waitFor } from "__support__/ui";+import { act, renderWithProviders, screen, waitFor } from "__support__/ui";import * as domUtils from "metabase/utils/dom";import type { User } from "metabase-types/api";import { createMockUser } from "metabase-types/api/mocks";@@ -107,7 +109,9 @@ describe("useUpsellFlow", () => {},});- screen.getByRole("button", { name: "Trigger Upsell Flow" }).click();+ await userEvent.click(+ screen.getByRole("button", { name: "Trigger Upsell Flow" }),+ );const encodedUrl = `return_url=${encodeURIComponent(window.location.href)}`;const userDetailsPart =@@ -126,22 +130,26 @@ describe("useUpsellFlow", () => {location: "branding-upsell-admin-screen",});- screen.getByRole("button", { name: "Trigger Upsell Flow" }).click();+ await userEvent.click(+ screen.getByRole("button", { name: "Trigger Upsell Flow" }),+ );jest.spyOn(domUtils, "reload").mockImplementation(() => undefined);- window.dispatchEvent(- new MessageEvent("message", {- origin: "https://test-store.metabase.com",- data: {- type: "license-token-created",- source: "metabase-store",- payload: {- licenseToken: "token-abc-123",+ act(() => {+ window.dispatchEvent(+ new MessageEvent("message", {+ origin: "https://test-store.metabase.com",+ data: {+ type: "license-token-created",+ source: "metabase-store",+ payload: {+ licenseToken: "token-abc-123",+ },},- },- }),- );+ }),+ );+ });await waitFor(async () => {const requests = await findRequests("PUT");@@ -176,20 +184,24 @@ describe("useUpsellFlow", () => {it("should display error and send message to store when token is invalid", async () => {const { mockPostMessage } = setupContainer({ tokenActivation: false });- screen.getByRole("button", { name: "Trigger Upsell Flow" }).click();- window.dispatchEvent(- new MessageEvent("message", {- source: window,- origin: "https://test-store.metabase.com",- data: {- type: "license-token-created",- source: "metabase-store",- payload: {- licenseToken: "token-abc-123",- },- },- }),+ await userEvent.click(+ screen.getByRole("button", { name: "Trigger Upsell Flow" }),);+ act(() => {+ window.dispatchEvent(+ new MessageEvent("message", {+ source: window,+ origin: "https://test-store.metabase.com",+ data: {+ type: "license-token-created",+ source: "metabase-store",+ payload: {+ licenseToken: "token-abc-123",+ },+ },+ }),+ );+ });await waitFor(() => {expect(mockPostMessage).toHaveBeenCalledWith(diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.unit.spec.tsxindex 6af0bb0506d..13156b4d38d 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.unit.spec.tsx@@ -5,7 +5,13 @@ import { setupEnterprisePlugins } from "__support__/enterprise";import { setupRemoteSyncEndpoints } from "__support__/server-mocks";import { mockSettings } from "__support__/settings";import { createMockState } from "__support__/state";-import { renderWithProviders, screen, waitFor, within } from "__support__/ui";+import {+ act,+ renderWithProviders,+ screen,+ waitFor,+ within,+} from "__support__/ui";import {createMockTokenFeatures,createMockUser,@@ -427,19 +433,21 @@ describe("GitSyncControls", () => {// Simulate the polled export task coming back in conflict (what the middleware dispatches when a// push loses the preflight->execute race). GitSyncControls observes it and toasts via useToast.- store.dispatch(- taskUpdated({- id: 77,- sync_task_type: "export",- status: "conflict",- progress: 1,- started_at: "2026-01-01T00:00:00Z",- ended_at: "2026-01-01T00:00:01Z",- last_progress_report_at: null,- error_message: null,- initiated_by: 0,- }),- );+ act(() => {+ store.dispatch(+ taskUpdated({+ id: 77,+ sync_task_type: "export",+ status: "conflict",+ progress: 1,+ started_at: "2026-01-01T00:00:00Z",+ ended_at: "2026-01-01T00:00:01Z",+ last_progress_report_at: null,+ error_message: null,+ initiated_by: 0,+ }),+ );+ });await waitFor(() => {const messages = store.getState().undo.map((u) => String(u.message));diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.unit.spec.tsxindex 678144cf8a9..fdf8d788fee 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.unit.spec.tsx@@ -2,6 +2,7 @@ import userEvent from "@testing-library/user-event";import { findRequests } from "__support__/server-mocks";import { screen, waitFor } from "__support__/ui";+import { waitForRequestsToSettle } from "__support__/utils";import { PLUGIN_TRANSFORMS } from "metabase/plugins";import { createMockCollectionItemFromCollection } from "metabase-types/api/mocks";@@ -434,13 +435,21 @@ describe("RemoteSyncSettingsForm", () => {PLUGIN_TRANSFORMS.isEnabled = false;});- it("should not display transforms toggle when transforms feature is disabled", () => {+ it("should not display transforms toggle when transforms feature is disabled", async () => {setup({remoteSyncEnabled: true,remoteSyncType: "read-write",remoteSyncUrl: "https://github.com/test/repo.git",});+ await waitFor(() => {+ expect(screen.getByLabelText("Read-write")).toBeChecked();+ });++ // The branch dropdown only starts loading once the read-write form is on+ // screen, so its request has to be flushed after that wait, not before.+ await waitForRequestsToSettle();+expect(screen.queryByLabelText("Sync Transforms"),).not.toBeInTheDocument();diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.unit.spec.tsindex 068edfacd41..d6ff3c12c2a 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.unit.spec.ts@@ -1,7 +1,7 @@import fetchMock from "fetch-mock";import { setupPropertiesEndpoints } from "__support__/server-mocks";-import { renderHookWithProviders, waitFor } from "__support__/ui";+import { act, renderHookWithProviders, waitFor } from "__support__/ui";import type { RemoteSyncDependencyErrorResponse } from "metabase-types/api";import { createMockSettings } from "metabase-types/api/mocks";@@ -58,13 +58,15 @@ describe("useRemoteSyncSubmit", () => {expect(result.current.unsyncedDependenciesError).toBeUndefined();- await result.current- .handleSubmit({- [TYPE_KEY]: "read-write",- [URL_KEY]: "https://github.com/test/repo.git",- [COLLECTIONS_KEY]: { 14: true },- })- .catch(() => undefined);+ await act(() =>+ result.current+ .handleSubmit({+ [TYPE_KEY]: "read-write",+ [URL_KEY]: "https://github.com/test/repo.git",+ [COLLECTIONS_KEY]: { 14: true },+ })+ .catch(() => undefined),+ );await waitFor(() => {expect(result.current.unsyncedDependenciesError).toEqual(diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsxindex f3fb3237bf2..cbcf5dc12d6 100644--- a/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsx@@ -1,3 +1,4 @@+import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";import { setupCollectionsEndpoints } from "__support__/server-mocks";@@ -90,7 +91,7 @@ describe("MainNavSharedCollections > new shared collection modal", () => {fetchMock.get("path:/api/collection/1", MOCK_TENANT_COLLECTIONS[0]);const addButton = screen.getByRole("button", { name: /add/i });- addButton.click();+ await userEvent.click(addButton);expect(await screen.findByText("New shared collection"),diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.unit.spec.tsxindex 34bb3a0afdb..eb007e6b235 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.unit.spec.tsx@@ -38,8 +38,10 @@ function setup({describe("PythonEditorBody", () => {describe("view mode (not editing)", () => {- it("should not render run button when not in edit mode", () => {+ it("should not render run button when not in edit mode", async () => {setup({ isEditMode: false });+ // The editor loads lazily, so assert absence only once it is up.+ await screen.findByTestId("python-editor");expect(screen.queryByTestId("run-button")).not.toBeInTheDocument();});diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonTransformEditor.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonTransformEditor.unit.spec.tsxindex 64d8f0e0aed..fdf250f9d59 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonTransformEditor.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonTransformEditor.unit.spec.tsx@@ -102,8 +102,10 @@ describe("PythonTransformEditor", () => {});describe("view mode (not editing)", () => {- it("should not render the data picker sidebar when not in edit mode", () => {+ it("should not render the data picker sidebar when not in edit mode", async () => {setup({ isEditMode: false });+ // The editor loads lazily, so assert absence only once it has rendered.+ await screen.findByTestId("python-transform-top-bar");expect(screen.queryByTestId("python-data-picker"),).not.toBeInTheDocument();diff --git a/frontend/src/metabase/admin/datamodel/components/SegmentItem.unit.spec.tsx b/frontend/src/metabase/admin/datamodel/components/SegmentItem.unit.spec.tsxindex e5304ffbf59..9dc45f0a9e5 100644--- a/frontend/src/metabase/admin/datamodel/components/SegmentItem.unit.spec.tsx+++ b/frontend/src/metabase/admin/datamodel/components/SegmentItem.unit.spec.tsx@@ -8,7 +8,7 @@ import {} from "__support__/server-mocks";import { mockSettings } from "__support__/settings";import { createMockState } from "__support__/state";-import { renderWithProviders, screen } from "__support__/ui";+import { act, renderWithProviders, screen } from "__support__/ui";import type { EnterpriseSettings } from "metabase-types/api";import {createMockDatabase,@@ -112,6 +112,8 @@ describe("SegmentItem", () => {expect(screen.queryByText("Retire Segment")).not.toBeInTheDocument();expect(screen.queryByText("Edit Segment")).not.toBeInTheDocument();- resolveTable();+ await act(async () => {+ resolveTable();+ });});});diff --git a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.unit.spec.tsx b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.unit.spec.tsxindex 03156d2feb3..edb1ab9948e 100644--- a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.unit.spec.tsx+++ b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.unit.spec.tsx@@ -49,7 +49,9 @@ describe("StrategyEditorForDatabases (OSS)", () => {await selectCacheStrategy(/Don.t cache/i);expect(screen.queryByRole("spinbutton")).not.toBeInTheDocument();- (await screen.findByTestId("strategy-form-submit-button")).click();+ await userEvent.click(+ await screen.findByTestId("strategy-form-submit-button"),+ );});it("does not regard form as dirty when a default value is entered into an input (metabase#42974)", async () => {diff --git a/frontend/src/metabase/admin/permissions/test/DatabasesPermissionsPage/DatabasesPermissionsPage.unit.spec.tsx b/frontend/src/metabase/admin/permissions/test/DatabasesPermissionsPage/DatabasesPermissionsPage.unit.spec.tsxindex 84b584f99a8..e54c5450168 100644--- a/frontend/src/metabase/admin/permissions/test/DatabasesPermissionsPage/DatabasesPermissionsPage.unit.spec.tsx+++ b/frontend/src/metabase/admin/permissions/test/DatabasesPermissionsPage/DatabasesPermissionsPage.unit.spec.tsx@@ -11,6 +11,7 @@ import { mockSettings } from "__support__/settings";import {renderWithProviders,screen,+ waitFor,waitForLoaderToBeRemoved,within,} from "__support__/ui";@@ -84,6 +85,11 @@ const setup = async ({if (shouldWaitForLoader) {await waitForLoaderToBeRemoved();+ } else {+ // The page is still loading on purpose here, so there is nothing to wait+ // on. Flush the updates it is about to make, which the caller cannot do+ // once this has returned.+ await waitFor(() => {});}return { mockEventListener, databaseMetadata };diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.unit.spec.tsxindex 3f251f12d5c..2cc075bb92a 100644--- a/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.unit.spec.tsx+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.unit.spec.tsx@@ -165,7 +165,7 @@ describe("GeneralSettingsPage", () => {const nameInput = await screen.findByDisplayValue("Metabased");await userEvent.clear(nameInput);await userEvent.type(nameInput, "Metabasey");- blur();+ await blur();await screen.findByDisplayValue("Metabasey");const emailInput = await screen.findByDisplayValue("[email protected]");@@ -174,7 +174,7 @@ describe("GeneralSettingsPage", () => {});await userEvent.clear(emailInput);await userEvent.type(emailInput, "[email protected]");- blur();+ await blur();await screen.findByDisplayValue("[email protected]");await waitFor(async () => {diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/LocalizationSettingsPage.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/LocalizationSettingsPage.unit.spec.tsxindex 65fb223fb23..15b6a6e618a 100644--- a/frontend/src/metabase/admin/settings/components/SettingsPages/LocalizationSettingsPage.unit.spec.tsx+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/LocalizationSettingsPage.unit.spec.tsx@@ -79,17 +79,17 @@ describe("LocalizationSettingsPage", () => {await userEvent.clear(timezoneInput);await userEvent.type(timezoneInput, "Mount");await userEvent.click(await screen.findByText("US/Mountain"));- blur();+ await blur();const startOfWeekInput = screen.getByLabelText("First day of the week");await userEvent.click(startOfWeekInput);await userEvent.click(await screen.findByText("Tuesday"));- blur();+ await blur();const currencyInput = screen.getByLabelText("Unit of currency");await userEvent.click(currencyInput);await userEvent.click(await screen.findByText("New Zealand Dollar"));- blur();+ await blur();await waitFor(async () => {const puts = await findRequests("PUT");diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.unit.spec.tsxindex c67c0d6b4ea..c45604c1d35 100644--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.unit.spec.tsx+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.unit.spec.tsx@@ -506,6 +506,12 @@ describe("CollectionItemsTable", () => {event_detail: "search",target_id: collection.id,});++ // The last debounce fires a third search, and its response rerenders the+ // table after this test would otherwise have finished.+ await waitFor(() => {+ expect(getSearchCalls()).toHaveLength(3);+ });});it("clears the search and restores the unfiltered list", async () => {diff --git a/frontend/src/metabase/common/components/ModalRoute.unit.spec.tsx b/frontend/src/metabase/common/components/ModalRoute.unit.spec.tsxindex 5fff187aff6..257ad584627 100644--- a/frontend/src/metabase/common/components/ModalRoute.unit.spec.tsx+++ b/frontend/src/metabase/common/components/ModalRoute.unit.spec.tsx@@ -1,6 +1,6 @@import userEvent from "@testing-library/user-event";-import { renderRoutes, renderWithProviders, screen } from "__support__/ui";+import { act, renderRoutes, renderWithProviders, screen } from "__support__/ui";import { Outlet, Route } from "metabase/router";import {@@ -206,7 +206,9 @@ describe("lazyModalRoute", () => {{ initialRoute: "/collection/5" },);- router?.navigate("/collection/5/archive");+ act(() => {+ router?.navigate("/collection/5/archive");+ });expect(screen.getByText("Collection page")).toBeInTheDocument();expect(screen.queryByText("Modal for 5")).not.toBeInTheDocument();diff --git a/frontend/src/metabase/dashboard/components/DashCard/Dashcard.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashCard/Dashcard.unit.spec.tsxindex 0c96d5cd4d6..8850ddba552 100644--- a/frontend/src/metabase/dashboard/components/DashCard/Dashcard.unit.spec.tsx+++ b/frontend/src/metabase/dashboard/components/DashCard/Dashcard.unit.spec.tsx@@ -17,6 +17,7 @@ import {renderWithProviders,screen,waitFor,+ waitForLoaderToBeRemoved,within,} from "__support__/ui";import {@@ -216,9 +217,11 @@ describe("DashCard", () => {jest.useRealTimers();});- it("should show a dashcard title", () => {+ it("should show a dashcard title", async () => {setup();- expect(screen.getByText("My Card")).toBeVisible();+ expect(await screen.findByText("My Card")).toBeVisible();+ // The visualization loads lazily, so let it finish before the test ends.+ await waitForLoaderToBeRemoved();});it("should show card's description in a tooltip", async () => {diff --git a/frontend/src/metabase/dashboard/components/DashboardInfoSidebar/DashboardPublicLinkPopover/DashboardPublicLinkPopover.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashboardInfoSidebar/DashboardPublicLinkPopover/DashboardPublicLinkPopover.unit.spec.tsxindex 10435537bb5..084f410b44b 100644--- a/frontend/src/metabase/dashboard/components/DashboardInfoSidebar/DashboardPublicLinkPopover/DashboardPublicLinkPopover.unit.spec.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardInfoSidebar/DashboardPublicLinkPopover/DashboardPublicLinkPopover.unit.spec.tsx@@ -78,8 +78,9 @@ describe("DashboardPublicLinkPopover", () => {).toBeInTheDocument();});- it("should not display extensions for the public link", () => {+ it("should not display extensions for the public link", async () => {setup();+ await screen.findByDisplayValue(`${SITE_URL}/public/dashboard/mock-uuid`);expect(screen.queryByTestId("extension-option")).not.toBeInTheDocument();});@@ -112,8 +113,9 @@ describe("DashboardPublicLinkPopover", () => {).toHaveLength(1);});- it("should not show non-admins the option to remove a public link", () => {+ it("should not show non-admins the option to remove a public link", async () => {setup({ isAdmin: false });+ await screen.findByDisplayValue(`${SITE_URL}/public/dashboard/mock-uuid`);expect(screen.queryByText("Remove public link")).not.toBeInTheDocument();});diff --git a/frontend/src/metabase/dashboard/components/ParameterSidebar/ParameterSidebar.unit.spec.tsx b/frontend/src/metabase/dashboard/components/ParameterSidebar/ParameterSidebar.unit.spec.tsxindex cd9aa2f146c..179ee678c63 100644--- a/frontend/src/metabase/dashboard/components/ParameterSidebar/ParameterSidebar.unit.spec.tsx+++ b/frontend/src/metabase/dashboard/components/ParameterSidebar/ParameterSidebar.unit.spec.tsx@@ -3,6 +3,7 @@ import fetchMock from "fetch-mock";import { useState } from "react";import { act, renderWithProviders, screen, waitFor } from "__support__/ui";+import { waitForRequestsToSettle } from "__support__/utils";import { MockDashboardContext } from "metabase/dashboard/context/mock-context";import { createMockUiParameter } from "metabase-lib/v1/parameters/mock";import type { UiParameter } from "metabase-lib/v1/parameters/types";@@ -146,6 +147,10 @@ describe("ParameterSidebar", () => {labelInput.blur();});expect(labelInput).toHaveValue("Bar");++ // `MoveParameterMenu` loads the dashboard's tabs, which lands after these+ // assertions with nothing visible to wait on.+ await waitForRequestsToSettle();});it("if the parameter updates, the label should update (metabase#34611)", async () => {diff --git a/frontend/src/metabase/data-studio/data-model/pages/DataModel/DataModel.unit.spec.tsx b/frontend/src/metabase/data-studio/data-model/pages/DataModel/DataModel.unit.spec.tsxindex 5306e598e69..1bbc7275c28 100644--- a/frontend/src/metabase/data-studio/data-model/pages/DataModel/DataModel.unit.spec.tsx+++ b/frontend/src/metabase/data-studio/data-model/pages/DataModel/DataModel.unit.spec.tsx@@ -16,6 +16,7 @@ import {setupUsersEndpoints,} from "__support__/server-mocks";import {+ act,mockGetBoundingClientRect,renderWithProviders,screen,@@ -329,7 +330,7 @@ describe("DataModel", () => {describe("no schema database", () => {it("should select the first database and skip schema selection by default", async () => {- setup({ databases: [SAMPLE_DB_NO_SCHEMA] });+ await setup({ databases: [SAMPLE_DB_NO_SCHEMA] });await waitFor(async () => {expect(@@ -790,7 +791,9 @@ describe("DataModel", () => {await waitForLoaderToBeRemoved();expect(screen.getByText("Sample Database")).toBeInTheDocument();- router?.back();+ act(() => {+ router?.back();+ });await waitFor(() => {expect(diff --git a/frontend/src/metabase/data-studio/segments/pages/SegmentDetailPage/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/data-studio/segments/pages/SegmentDetailPage/tests/enterprise.unit.spec.tsxindex 885bdaa64c7..1f5ac65e1dc 100644--- a/frontend/src/metabase/data-studio/segments/pages/SegmentDetailPage/tests/enterprise.unit.spec.tsx+++ b/frontend/src/metabase/data-studio/segments/pages/SegmentDetailPage/tests/enterprise.unit.spec.tsx@@ -7,13 +7,14 @@ import { TEST_TABLE, setup } from "./setup";describe("SegmentDetailPage", () => {describe("readonly state", () => {describe("when remote sync is read-only and table is published", () => {- beforeEach(() => {+ beforeEach(async () => {setup({remoteSyncType: "read-only",enterprisePlugins: ["remote_sync"],tokenFeatures: { remote_sync: true },table: { ...TEST_TABLE, is_published: true },});+ await screen.findByDisplayValue("High Value Orders");});it("has readonly segment name input", async () => {diff --git a/frontend/src/metabase/detail-view/components/DetailViewSidesheet/DetailViewSidesheet.unit.spec.tsx b/frontend/src/metabase/detail-view/components/DetailViewSidesheet/DetailViewSidesheet.unit.spec.tsxindex d16066359cc..524234237d9 100644--- a/frontend/src/metabase/detail-view/components/DetailViewSidesheet/DetailViewSidesheet.unit.spec.tsx+++ b/frontend/src/metabase/detail-view/components/DetailViewSidesheet/DetailViewSidesheet.unit.spec.tsx@@ -5,7 +5,7 @@ import {setupDatabasesEndpoints,} from "__support__/server-mocks";import { renderWithProviders, screen } from "__support__/ui";-import { getNextId } from "__support__/utils";+import { getNextId, waitForRequestsToSettle } from "__support__/utils";import { getQuestionVirtualTableId } from "metabase-lib/v1/metadata/utils/saved-questions";import {createMockColumn,@@ -82,8 +82,11 @@ function setup({}describe("DetailViewSidesheet", () => {- it("navigates rows with arrow keys when keyboard navigation is enabled", () => {+ it("navigates rows with arrow keys when keyboard navigation is enabled", async () => {const { onNextClick, onPreviousClick } = setup();+ // `ActionExecuteModal` initialises its values state after this render,+ // with nothing observable to wait on, so flush that update here.+ await waitForRequestsToSettle();fireEvent.keyDown(document.documentElement, { key: "ArrowUp" });expect(onPreviousClick).toHaveBeenCalledTimes(1);@@ -92,8 +95,9 @@ describe("DetailViewSidesheet", () => {expect(onNextClick).toHaveBeenCalledTimes(1);});- it("does not navigate rows with arrow keys when keyboard navigation is disabled", () => {+ it("does not navigate rows with arrow keys when keyboard navigation is disabled", async () => {const { onNextClick, onPreviousClick } = setup({ showNav: false });+ await waitForRequestsToSettle();fireEvent.keyDown(document.documentElement, { key: "ArrowUp" });expect(onPreviousClick).not.toHaveBeenCalled();diff --git a/frontend/src/metabase/embedding/components/EmbedModal/StaticEmbedSetupPane/tests/common.unit.spec.tsx b/frontend/src/metabase/embedding/components/EmbedModal/StaticEmbedSetupPane/tests/common.unit.spec.tsxindex fabd392f335..97adf5cf460 100644--- a/frontend/src/metabase/embedding/components/EmbedModal/StaticEmbedSetupPane/tests/common.unit.spec.tsx+++ b/frontend/src/metabase/embedding/components/EmbedModal/StaticEmbedSetupPane/tests/common.unit.spec.tsx@@ -84,7 +84,9 @@ describe("Static Embed Setup phase", () => {activeTab: "Overview",});- expect(screen.getByText("Setting up a static embed")).toBeVisible();+ expect(+ await screen.findByText("Setting up a static embed"),+ ).toBeVisible();expect(screen.getByText(@@ -124,7 +126,7 @@ describe("Static Embed Setup phase", () => {});expect(- screen.getByText(+ await screen.findByText("You can also hide or lock any of the dashboard’s parameters.",),).toBeVisible();diff --git a/frontend/src/metabase/embedding/components/EmbedModal/StaticEmbedSetupPane/tests/premium.unit.spec.tsx b/frontend/src/metabase/embedding/components/EmbedModal/StaticEmbedSetupPane/tests/premium.unit.spec.tsxindex 4d5117d8e15..208f0619931 100644--- a/frontend/src/metabase/embedding/components/EmbedModal/StaticEmbedSetupPane/tests/premium.unit.spec.tsx+++ b/frontend/src/metabase/embedding/components/EmbedModal/StaticEmbedSetupPane/tests/premium.unit.spec.tsx@@ -24,8 +24,9 @@ describe("Static Embed Setup phase - EE, with token", () => {enterprisePlugins: ["whitelabel"],tokenFeatures: createMockTokenFeatures({ whitelabel: true }),});-- expect(screen.getByText("Setting up a static embed")).toBeVisible();+ expect(+ await screen.findByText("Setting up a static embed"),+ ).toBeVisible();const link = screen.getByRole("link", {name: "documentation",diff --git a/frontend/src/metabase/embedding/components/PublicLinkPopover/PublicLinkPopover.unit.spec.tsx b/frontend/src/metabase/embedding/components/PublicLinkPopover/PublicLinkPopover.unit.spec.tsxindex 593be957c3c..ab5877ec799 100644--- a/frontend/src/metabase/embedding/components/PublicLinkPopover/PublicLinkPopover.unit.spec.tsx+++ b/frontend/src/metabase/embedding/components/PublicLinkPopover/PublicLinkPopover.unit.spec.tsx@@ -2,7 +2,7 @@ import userEvent from "@testing-library/user-event";import { useState } from "react";import { createMockState } from "__support__/state";-import { renderWithProviders, screen } from "__support__/ui";+import { renderWithProviders, screen, waitFor } from "__support__/ui";import type { ExportFormat } from "metabase-types/api";import { createMockUser } from "metabase-types/api/mocks";@@ -134,8 +134,9 @@ describe("PublicLinkPopover", () => {).toBeInTheDocument();});- it("should not render `Remove public link` for non-admins", () => {+ it("should not render `Remove public link` for non-admins", async () => {setup({ isAdmin: false });+ await screen.findByDisplayValue("sample-public-link");expect(screen.queryByText("Remove public link")).not.toBeInTheDocument();});@@ -154,14 +155,15 @@ describe("PublicLinkPopover", () => {});describe("when creating public links", () => {- it("should call createPublicLink when uuid is null and isOpen is true", () => {+ it("should call createPublicLink when uuid is null and isOpen is true", async () => {const { createPublicLink } = setup({ hasUUID: false });- expect(createPublicLink).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(createPublicLink).toHaveBeenCalledTimes(1));});- it("should not call createPublicLink when isOpen is false", () => {+ it("should not call createPublicLink when isOpen is false", async () => {const { createPublicLink } = setup({ isOpen: false, hasUUID: false });+ await screen.findByTestId("target");expect(createPublicLink).not.toHaveBeenCalled();});diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsxindex dd94886a34d..68927f51ca4 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsx@@ -5,6 +5,7 @@ import {setupCardQueryMetadataEndpoint,} from "__support__/server-mocks";import { fireEvent, screen, waitFor } from "__support__/ui";+import { waitForRequestsToSettle } from "__support__/utils";import * as Analytics from "metabase/analytics";import { PLUGIN_EMBEDDING_IFRAME_SDK_SETUP } from "metabase/plugins";import {@@ -18,18 +19,20 @@ import {import { setup } from "./test-setup";describe("Embed flow > initial setup", () => {- it("shows the embed experience step as the first step", () => {+ it("shows the embed experience step as the first step", async () => {setup();expect(- screen.getByText("Select your embed experience"),+ await screen.findByText("Select your embed experience"),).toBeInTheDocument();});- it("selects the dashboard experience by default", () => {+ it("selects the dashboard experience by default", async () => {setup();- const dashboardRadio = screen.getByRole("radio", { name: /Dashboard/ });+ const dashboardRadio = await screen.findByRole("radio", {+ name: /Dashboard/,+ });expect(dashboardRadio).toBeChecked();});});@@ -47,37 +50,43 @@ describe("Embed flow > enabling embedding from the Guest option", () => {PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.isEnabled = () => false;});- it("states the modular embedding terms on EE with a license", () => {+ it("states the modular embedding terms on EE with a license", async () => {guestSetup({hasLicense: true,modularEmbeddingEnabled: false,showModularEmbedTerms: true,});+ await waitForRequestsToSettle();+expect(screen.getByTestId("enable-embedding-card")).toHaveTextContent("To continue, enable modular embedding and agree to the usage conditions.",);});- it("only asks to enable on EE with a license once the terms are accepted", () => {+ it("only asks to enable on EE with a license once the terms are accepted", async () => {guestSetup({hasLicense: true,modularEmbeddingEnabled: false,showModularEmbedTerms: false,});+ await waitForRequestsToSettle();+expect(screen.getByTestId("enable-embedding-card")).toHaveTextContent("Enable modular embedding to get started.",);});- it("states the guest embedding terms on EE without a license", () => {+ it("states the guest embedding terms on EE without a license", async () => {guestSetup({hasLicense: false,modularEmbeddingEnabled: false,showStaticEmbedTerms: true,});+ await waitForRequestsToSettle();+expect(screen.getByTestId("enable-embedding-card")).toHaveTextContent("To continue, enable embedding and agree to the usage conditions.",);@@ -387,10 +396,10 @@ describe("Embed flow > forward and backward navigation", () => {).toBeInTheDocument();});- it("renders the SSO radio above the Guest radio in the authentication card", () => {+ it("renders the SSO radio above the Guest radio in the authentication card", async () => {setup({ modularEmbeddingEnabled: true });- const radios = screen.getAllByRole("radio");+ const radios = await screen.findAllByRole("radio");const ssoIndex = radios.findIndex((r) => r.getAttribute("value") === "sso");const guestIndex = radios.findIndex((r) => r.getAttribute("value") === "guest-embed",@@ -401,14 +410,14 @@ describe("Embed flow > forward and backward navigation", () => {expect(ssoIndex).toBeLessThan(guestIndex);});- it("selects Guest when initialState.isGuest is true, even with SSO configured", () => {+ it("selects Guest when initialState.isGuest is true, even with SSO configured", async () => {setup({modularEmbeddingEnabled: true,jwtReady: true,initialState: { isGuest: true, useExistingUserSession: true },});- expect(screen.getByDisplayValue("guest-embed")).toBeChecked();+ expect(await screen.findByDisplayValue("guest-embed")).toBeChecked();expect(screen.getByDisplayValue("sso")).not.toBeChecked();});@@ -416,10 +425,10 @@ describe("Embed flow > forward and backward navigation", () => {const warningText =/This embed will only work for local testing\. To get production ready code, configure/;- it("shows a warning on the authentication card when SSO is selected but not configured", () => {+ it("shows a warning on the authentication card when SSO is selected but not configured", async () => {setup({ modularEmbeddingEnabled: true, jwtReady: false });- expect(screen.getByDisplayValue("sso")).toBeChecked();+ expect(await screen.findByDisplayValue("sso")).toBeChecked();expect(screen.getByText("Authentication")).toBeInTheDocument();expect(screen.getByText(warningText)).toBeInTheDocument();});@@ -432,9 +441,13 @@ describe("Embed flow > forward and backward navigation", () => {expect(screen.queryByText(warningText)).not.toBeInTheDocument();});- it("hides the warning when SSO is configured", () => {+ it("hides the warning when SSO is configured", async () => {setup({ modularEmbeddingEnabled: true, jwtReady: true });+ // The card has to be on screen before the absence of its warning means+ // anything.+ await screen.findAllByRole("radio");+expect(screen.queryByText(warningText)).not.toBeInTheDocument();});@@ -462,10 +475,10 @@ describe("Embed flow > forward and backward navigation", () => {});});- it("disables next and back buttons when simple embedding is disabled", () => {+ it("disables next and back buttons when simple embedding is disabled", async () => {setup({ modularEmbeddingEnabled: false });- expect(screen.getByRole("button", { name: "Next" })).toBeDisabled();+ expect(await screen.findByRole("button", { name: "Next" })).toBeDisabled();expect(screen.queryByRole("button", { name: "Back" }),).not.toBeInTheDocument();@@ -492,7 +505,7 @@ describe("Embed flow > forward and backward navigation", () => {});// Starts at the "select embed options" step.- expect(screen.getByText("Behavior")).toBeInTheDocument();+ expect(await screen.findByText("Behavior")).toBeInTheDocument();expect(screen.getByText("Appearance")).toBeInTheDocument();expect(@@ -502,7 +515,7 @@ describe("Embed flow > forward and backward navigation", () => {});describe("Embed flow > Pro feature upsell indicators", () => {- it("disables Pro checkboxes for OSS users (question)", () => {+ it("disables Pro checkboxes for OSS users (question)", async () => {const mockDatabase = createMockDatabase();const mockCard = createMockCard({ id: 456 });@@ -524,7 +537,7 @@ describe("Embed flow > Pro feature upsell indicators", () => {// All Pro-gated checkboxes should be disabledexpect(- screen.getByRole("checkbox", {+ await screen.findByRole("checkbox", {name: "Allow people to drill through on data points",}),).toBeDisabled();diff --git a/frontend/src/metabase/embedding/settings/EmbeddingToggle/EmbeddingToggle.unit.spec.tsx b/frontend/src/metabase/embedding/settings/EmbeddingToggle/EmbeddingToggle.unit.spec.tsxindex cc290aab2e9..c5c71ff5018 100644--- a/frontend/src/metabase/embedding/settings/EmbeddingToggle/EmbeddingToggle.unit.spec.tsx+++ b/frontend/src/metabase/embedding/settings/EmbeddingToggle/EmbeddingToggle.unit.spec.tsx@@ -72,8 +72,8 @@ describe("EmbeddingToggle", () => {expect(screen.getByText("Enabled")).toBeInTheDocument();});- it("should render a switch in the 'off' position when value is false", () => {- setup({ value: false });+ it("should render a switch in the 'off' position when value is false", async () => {+ await setup({ value: false });const switchElement = screen.getByRole("switch");expect(switchElement).toBeInTheDocument();expect(switchElement).not.toBeChecked();@@ -85,7 +85,7 @@ describe("EmbeddingToggle", () => {it("should send a PUT request with value=true when setting is off", async () => {await setup({ value: false });- expect(screen.getByRole("switch")).not.toBeChecked();+ expect(await screen.findByRole("switch")).not.toBeChecked();await userEvent.click(screen.getByRole("switch"));const puts = await findRequests("PUT");diff --git a/frontend/src/metabase/embedding/setup-guide/components/SetupPermissionsAndTenantsPage/MoveDashboardStepContent.unit.spec.tsx b/frontend/src/metabase/embedding/setup-guide/components/SetupPermissionsAndTenantsPage/MoveDashboardStepContent.unit.spec.tsxindex d70d3dfb215..1ea816e1f9a 100644--- a/frontend/src/metabase/embedding/setup-guide/components/SetupPermissionsAndTenantsPage/MoveDashboardStepContent.unit.spec.tsx+++ b/frontend/src/metabase/embedding/setup-guide/components/SetupPermissionsAndTenantsPage/MoveDashboardStepContent.unit.spec.tsx@@ -3,6 +3,7 @@ import fetchMock from "fetch-mock";import { setupCollectionTreeEndpoint } from "__support__/server-mocks";import { renderWithProviders, screen, waitFor } from "__support__/ui";+import { waitForRequestsToSettle } from "__support__/utils";import {createMockCollection,createMockCollectionItem,@@ -123,6 +124,9 @@ describe("MoveDashboardStepContent", () => {await waitFor(() => {expect(onCompleted).toHaveBeenCalled();});+ // Completing the step leaves work behind that this test cannot see, so+ // flush it rather than letting it land in the next test.+ await waitForRequestsToSettle();});it("creates a sample dashboard when Create button is clicked", async () => {@@ -171,5 +175,8 @@ describe("MoveDashboardStepContent", () => {await waitFor(() => {expect(onCompleted).toHaveBeenCalled();});+ // Completing the step leaves work behind that this test cannot see, so+ // flush it rather than letting it land in the next test.+ await waitForRequestsToSettle();});});diff --git a/frontend/src/metabase/embedding/themes/hooks/use-embedding-theme-editor.unit.spec.tsx b/frontend/src/metabase/embedding/themes/hooks/use-embedding-theme-editor.unit.spec.tsxindex 1d2b95a8734..2e161c039f7 100644--- a/frontend/src/metabase/embedding/themes/hooks/use-embedding-theme-editor.unit.spec.tsx+++ b/frontend/src/metabase/embedding/themes/hooks/use-embedding-theme-editor.unit.spec.tsx@@ -43,7 +43,6 @@ function setup(themeId: ThemeEditorId = 1, applicationColors?: ColorSettings) {: undefined;return renderHookWithProviders(() => useEmbeddingThemeEditor(themeId), {- withUndos: true,withRouter: true,storeInitialState,});@@ -490,7 +489,7 @@ describe("useEmbeddingThemeEditor", () => {expect(result.current.currentTheme).not.toBeNull();});- const saved = await result.current.handleSave();+ const saved = await act(() => result.current.handleSave());expect(saved?.id).toBe(42);expect(fetchMock.callHistory.calls("path:/api/embed-theme")).toHaveLength(diff --git a/frontend/src/metabase/metabot/tests/fork.unit.spec.ts b/frontend/src/metabase/metabot/tests/fork.unit.spec.tsindex 31a3892169c..b8baeb3418a 100644--- a/frontend/src/metabase/metabot/tests/fork.unit.spec.ts+++ b/frontend/src/metabase/metabot/tests/fork.unit.spec.ts@@ -7,7 +7,7 @@ import {createMockMetabotTextMessage,createMockMetabotTextPart,} from "__support__/server-mocks";-import { screen, waitFor, within } from "__support__/ui";+import { act, screen, waitFor, within } from "__support__/ui";import { forkConversation } from "metabase/metabot/state";import * as Urls from "metabase/urls";@@ -123,13 +123,15 @@ describe("metabot > fork", () => {});mockForkEndpoint(forkedConversation);- await store.dispatch(- forkConversation({- agentId: "ask",- conversationId: "original-convo-id",- messageId: "msg_test_favorite",- }),- );+ await act(async () => {+ await store.dispatch(+ forkConversation({+ agentId: "ask",+ conversationId: "original-convo-id",+ messageId: "msg_test_favorite",+ }),+ );+ });await waitFor(() =>expect(router?.location.pathname).toBe(diff --git a/frontend/src/metabase/metabot/tests/message.unit.spec.tsx b/frontend/src/metabase/metabot/tests/message.unit.spec.tsxindex c5eb21b73c8..ed5efe1b709 100644--- a/frontend/src/metabase/metabot/tests/message.unit.spec.tsx+++ b/frontend/src/metabase/metabot/tests/message.unit.spec.tsx@@ -53,7 +53,7 @@ describe("metabot > message", () => {await enterChatMessage("Who is your favorite?", false);expect(await input()).toHaveTextContent("Who is your favorite?");- (await sendMessageButton()).click();+ await userEvent.click(await sendMessageButton());expect(await screen.findByText("You, but don't tell anyone."),diff --git a/frontend/src/metabase/metabot/tests/multi-convo.unit.spec.tsx b/frontend/src/metabase/metabot/tests/multi-convo.unit.spec.tsxindex 001d2cd84b0..4ed09a40485 100644--- a/frontend/src/metabase/metabot/tests/multi-convo.unit.spec.tsx+++ b/frontend/src/metabase/metabot/tests/multi-convo.unit.spec.tsx@@ -102,7 +102,9 @@ describe("multi-convo support", () => {message: "test1",conversationId: conversationIdForAgent(store, "test_1"),} as const;- await store.dispatch(submitInput(msg1));+ await act(async () => {+ await store.dispatch(submitInput(msg1));+ });mockAgentEndpoint({events: [@@ -151,13 +153,15 @@ describe("multi-convo support", () => {{ type: "data-conversation-title", data: "T" },],});- await store.dispatch(- submitInput({- ...input,- message: "test",- conversationId: conversationIdForAgent(store, "test_1"),- }),- );+ await act(async () => {+ await store.dispatch(+ submitInput({+ ...input,+ message: "test",+ conversationId: conversationIdForAgent(store, "test_1"),+ }),+ );+ });expect(convoForAgent(store, "test_1").messages).toHaveLength(2);await act(() => hook.current.startNewConversation({ agentId: "test_1" }));@@ -197,12 +201,14 @@ describe("multi-convo support", () => {});const { store } = setup({ agentIds: ["test_1"] });const conversationId = conversationIdForAgent(store, "test_1");- store.dispatch(- metabotActions.setIsPollingForTitle({- conversationId,- isPollingForTitle: true,- }),- );+ act(() => {+ store.dispatch(+ metabotActions.setIsPollingForTitle({+ conversationId,+ isPollingForTitle: true,+ }),+ );+ });await sendMessage(store, "test_1");@@ -250,12 +256,14 @@ describe("multi-convo support", () => {});const { store } = setup({ agentIds: ["test_1"] });const conversationId = conversationIdForAgent(store, "test_1");- store.dispatch(- metabotActions.setIsPollingForTitle({- conversationId: "a-conversation-the-agent-has-left",- isPollingForTitle: true,- }),- );+ act(() => {+ store.dispatch(+ metabotActions.setIsPollingForTitle({+ conversationId: "a-conversation-the-agent-has-left",+ isPollingForTitle: true,+ }),+ );+ });await sendMessage(store, "test_1");diff --git a/frontend/src/metabase/metabot/tests/utils.tsx b/frontend/src/metabase/metabot/tests/utils.tsxindex 15f061b54d8..8c858bd5285 100644--- a/frontend/src/metabase/metabot/tests/utils.tsx+++ b/frontend/src/metabase/metabot/tests/utils.tsx@@ -189,6 +189,9 @@ export const enterChatMessage = async (message: string, send = true) => {if (send) {await userEvent.type(await input(), "{Enter}");}+ // The editor picks up these DOM changes through a MutationObserver, which+ // React cannot see as part of this call, so flush the state it sets.+ await waitFor(() => {});};export const sendMessageButton = () =>screen.findByTestId("metabot-send-message");diff --git a/frontend/src/metabase/metadata/hooks/use-table-update-handlers.unit.spec.tsx b/frontend/src/metabase/metadata/hooks/use-table-update-handlers.unit.spec.tsxindex d8ba240734c..aca7ef00a75 100644--- a/frontend/src/metabase/metadata/hooks/use-table-update-handlers.unit.spec.tsx+++ b/frontend/src/metabase/metadata/hooks/use-table-update-handlers.unit.spec.tsx@@ -2,6 +2,7 @@ import fetchMock from "fetch-mock";import { setupTableEndpoints } from "__support__/server-mocks";import {+ act,renderHookWithProviders,screen,waitFor,@@ -43,8 +44,10 @@ describe("useTableUpdateHandlers", () => {response: { status: 500 },});- await result.current.handleCustomFieldOrderChange(- (ORDERS_TABLE.fields ?? []).map(getRawTableFieldId).reverse(),+ await act(() =>+ result.current.handleCustomFieldOrderChange(+ (ORDERS_TABLE.fields ?? []).map(getRawTableFieldId).reverse(),+ ),);await waitFor(() => {diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.unit.spec.tsx b/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.unit.spec.tsxindex 43eb143db73..f921d432b85 100644--- a/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.unit.spec.tsx+++ b/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.unit.spec.tsx@@ -12,6 +12,7 @@ import {setupUnauthorizedFieldValuesEndpoints,} from "__support__/server-mocks";import {+ act,mockGetBoundingClientRect,renderWithProviders,screen,@@ -275,14 +276,11 @@ describe("DataModelV1", () => {describe("no schema database", () => {it("should select the first database and skip schema selection by default", async () => {- setup({ databases: [SAMPLE_DB_NO_SCHEMA] });-- await waitFor(async () => {- expect(- await findTablePickerDatabase(SAMPLE_DB_NO_SCHEMA.name),- ).toBeInTheDocument();- });+ await setup({ databases: [SAMPLE_DB_NO_SCHEMA] });+ expect(+ await findTablePickerDatabase(SAMPLE_DB_NO_SCHEMA.name),+ ).toBeInTheDocument();expect(await findTablePickerTable(ORDERS_TABLE_NO_SCHEMA.display_name),).toBeInTheDocument();@@ -688,7 +686,9 @@ describe("DataModelV1", () => {await waitForLoaderToBeRemoved();expect(screen.getByText("Sample Database")).toBeInTheDocument();- router?.back();+ act(() => {+ router?.back();+ });await waitFor(() => {expect(diff --git a/frontend/src/metabase/nav/components/WhatsNewNotification/WhatsNewNotification.unit.spec.tsx b/frontend/src/metabase/nav/components/WhatsNewNotification/WhatsNewNotification.unit.spec.tsxindex 653adad1f96..53224397a8a 100644--- a/frontend/src/metabase/nav/components/WhatsNewNotification/WhatsNewNotification.unit.spec.tsx+++ b/frontend/src/metabase/nav/components/WhatsNewNotification/WhatsNewNotification.unit.spec.tsx@@ -1,3 +1,4 @@+import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";import { setupEnterprisePlugins } from "__support__/enterprise";@@ -154,7 +155,7 @@ describe("WhatsNewNotification", () => {const dismissButton = await screen.findByRole("button", {name: /close/i,}); // Use the icon name if no specific label- dismissButton.click();+ await userEvent.click(dismissButton);await waitFor(() => {expect(fetchMock.callHistory.called(LAST_ACK_SETTINGS_URL)).toBe(true);diff --git a/frontend/src/metabase/query_builder/components/view/ViewFooter/ViewFooterCopyWidget.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/ViewFooter/ViewFooterCopyWidget.unit.spec.tsxindex 844135a0d5b..262632c7d16 100644--- a/frontend/src/metabase/query_builder/components/view/ViewFooter/ViewFooterCopyWidget.unit.spec.tsx+++ b/frontend/src/metabase/query_builder/components/view/ViewFooter/ViewFooterCopyWidget.unit.spec.tsx@@ -99,7 +99,7 @@ describe("ViewFooterCopyWidget", () => {setup({ card: TABLE_CARD, result: TABLE_RESULT });await userEvent.click(- screen.getByLabelText("Copy these results to clipboard"),+ await screen.findByLabelText("Copy these results to clipboard"),);await waitFor(() => expect(write).toHaveBeenCalledTimes(1));diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionActions/QuestionMoreActionsMenu/tests/QuestionMoreActionsMenu.enterprise.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionActions/QuestionMoreActionsMenu/tests/QuestionMoreActionsMenu.enterprise.unit.spec.tsxindex b229c1292b4..c3daffb94c8 100644--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionActions/QuestionMoreActionsMenu/tests/QuestionMoreActionsMenu.enterprise.unit.spec.tsx+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionActions/QuestionMoreActionsMenu/tests/QuestionMoreActionsMenu.enterprise.unit.spec.tsx@@ -13,7 +13,7 @@ describe("QuestionMoreActionsMenu > Enterprise", () => {isEnterprise: true,});await openMenu();- expect(screen.getByText("Create an alert")).toBeInTheDocument();+ expect(await screen.findByText("Create an alert")).toBeInTheDocument();});describe("alerts permission disabled", () => {@@ -25,6 +25,9 @@ describe("QuestionMoreActionsMenu > Enterprise", () => {isEnterprise: true,});await openMenu();++ await screen.findByRole("menu");+expect(screen.queryByText("Create an alert")).not.toBeInTheDocument();});});@@ -39,7 +42,9 @@ describe("QuestionMoreActionsMenu > Enterprise", () => {isEnterprise: true,});await openMenu();- expect(screen.getByText("Verify this question")).toBeInTheDocument();+ expect(+ await screen.findByText("Verify this question"),+ ).toBeInTheDocument();});it('should show "Remove verification" for admin users on verified questions', async () => {@@ -53,7 +58,9 @@ describe("QuestionMoreActionsMenu > Enterprise", () => {],});await openMenu();- expect(screen.getByText("Remove verification")).toBeInTheDocument();+ expect(+ await screen.findByText("Remove verification"),+ ).toBeInTheDocument();});it('should not show "Verify this question" for non-admin users', async () => {@@ -64,6 +71,9 @@ describe("QuestionMoreActionsMenu > Enterprise", () => {isEnterprise: true,});await openMenu();++ await screen.findByRole("menu");+expect(screen.queryByText("Verify this question"),).not.toBeInTheDocument();diff --git a/frontend/src/metabase/query_builder/containers/QueryBuilder.timeline-events.unit.spec.tsx b/frontend/src/metabase/query_builder/containers/QueryBuilder.timeline-events.unit.spec.tsxindex 2c16c48f07d..0da2e73d126 100644--- a/frontend/src/metabase/query_builder/containers/QueryBuilder.timeline-events.unit.spec.tsx+++ b/frontend/src/metabase/query_builder/containers/QueryBuilder.timeline-events.unit.spec.tsx@@ -324,7 +324,12 @@ describe("QueryBuilder > timeline events", () => {getQuestion(store.getState()),).setCollectionId(checkNotNull(DESTINATION_COLLECTION.entity_id));- const savePromise = store.dispatch(apiCreateQuestion(question));+ // The save cannot be awaited yet, because the card POST must be inspected+ // while the timelines request is still in flight.+ let savePromise!: Promise<unknown>;+ act(() => {+ savePromise = store.dispatch(apiCreateQuestion(question));+ });await waitFor(() => {expect(fetchMock.callHistory.called("path:/api/timeline")).toBe(true);diff --git a/frontend/src/metabase/querying/action-creator/tests/ActionCreator-QueryActions.unit.spec.ts b/frontend/src/metabase/querying/action-creator/tests/ActionCreator-QueryActions.unit.spec.tsindex b72d8f67829..9fdec67dc6b 100644--- a/frontend/src/metabase/querying/action-creator/tests/ActionCreator-QueryActions.unit.spec.ts+++ b/frontend/src/metabase/querying/action-creator/tests/ActionCreator-QueryActions.unit.spec.ts@@ -182,7 +182,7 @@ describe("ActionCreator > Query Actions", () => {screen.queryByRole("button", { name: "Update" }),).not.toBeInTheDocument();- screen.getByLabelText("Action settings").click();+ await userEvent.click(screen.getByLabelText("Action settings"));expect(await screen.findByLabelText("Success message")).toBeDisabled();});@@ -202,7 +202,7 @@ describe("ActionCreator > Query Actions", () => {screen.queryByRole("button", { name: "Update" }),).not.toBeInTheDocument();- screen.getByLabelText("Action settings").click();+ await userEvent.click(screen.getByLabelText("Action settings"));expect(await screen.findByLabelText("Success message")).toBeDisabled();});diff --git a/frontend/src/metabase/querying/common/components/AggregationPicker/AggregationPicker.unit.spec.tsx b/frontend/src/metabase/querying/common/components/AggregationPicker/AggregationPicker.unit.spec.tsxindex 5892bc041f9..a0ae67349fc 100644--- a/frontend/src/metabase/querying/common/components/AggregationPicker/AggregationPicker.unit.spec.tsx+++ b/frontend/src/metabase/querying/common/components/AggregationPicker/AggregationPicker.unit.spec.tsx@@ -370,7 +370,7 @@ describe("AggregationPicker", () => {it("should open the editor when a named expression with operator is used", async () => {setup({ query: createQueryWithInlineExpressionWithOperator() });- expect(screen.getByText("Custom Expression")).toBeInTheDocument();+ expect(await screen.findByText("Custom Expression")).toBeInTheDocument();expect(screen.getByDisplayValue("My count")).toBeInTheDocument();});@@ -395,13 +395,13 @@ describe("AggregationPicker", () => {expect(screen.queryByText("Custom Expression")).not.toBeInTheDocument();});- it("should open the editor even if `allowCustomExpressions` prop is false if expression is used", () => {+ it("should open the editor even if `allowCustomExpressions` prop is false if expression is used", async () => {setup({query: createQueryWithInlineExpression(),allowCustomExpressions: false,});- expect(screen.getByText("Custom Expression")).toBeInTheDocument();+ expect(await screen.findByText("Custom Expression")).toBeInTheDocument();expect(screen.getByDisplayValue("Avg Q")).toBeInTheDocument();});});diff --git a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/CurrentDatePicker/CurrentDatePicker.unit.spec.tsx b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/CurrentDatePicker/CurrentDatePicker.unit.spec.tsxindex 5fde67b9c42..037ba0221e8 100644--- a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/CurrentDatePicker/CurrentDatePicker.unit.spec.tsx+++ b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/CurrentDatePicker/CurrentDatePicker.unit.spec.tsx@@ -1,7 +1,7 @@import _userEvent from "@testing-library/user-event";import { createMockSettingsState } from "__support__/state";-import { renderWithProviders, screen } from "__support__/ui";+import { act, renderWithProviders, screen } from "__support__/ui";import { DATE_PICKER_UNITS } from "metabase/querying/common/constants";import type {DatePickerUnit,@@ -102,7 +102,12 @@ describe("CurrentDatePicker", () => {it("should select the focused interval on Enter", async () => {const { onChange } = setup();- screen.getByRole("radio", { name: "Month" }).focus();+ // Focusing the chip opens its tooltip, so the state that opens it has to+ // be set inside act().+ act(() => {+ screen.getByRole("radio", { name: "Month" }).focus();+ });+await userEvent.keyboard("{Enter}");expect(onChange).toHaveBeenCalledWith(CURRENT_MONTH_VALUE);diff --git a/frontend/src/metabase/querying/common/components/QueryColumnPicker/QueryColumnPicker.unit.spec.tsx b/frontend/src/metabase/querying/common/components/QueryColumnPicker/QueryColumnPicker.unit.spec.tsxindex c54e01b0d8b..0e6dcc73451 100644--- a/frontend/src/metabase/querying/common/components/QueryColumnPicker/QueryColumnPicker.unit.spec.tsx+++ b/frontend/src/metabase/querying/common/components/QueryColumnPicker/QueryColumnPicker.unit.spec.tsx@@ -175,10 +175,10 @@ describe("QueryColumnPicker", () => {});});- it("should allow searching using displayName (#39622)", () => {+ it("should allow searching using displayName (#39622)", async () => {setup();- screen.getByText("User").click();+ await userEvent.click(screen.getByText("User"));fireEvent.change(screen.getByTestId("list-search-field"), {target: { value: "Birth Date" },});diff --git a/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.unit.spec.tsx b/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.unit.spec.tsxindex fae25b72a25..de05b073197 100644--- a/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.unit.spec.tsx+++ b/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.unit.spec.tsx@@ -11,6 +11,7 @@ import {waitFor,within,} from "__support__/ui";+import { waitForRequestsToSettle } from "__support__/utils";import * as Browser from "metabase/utils/browser";import * as Lib from "metabase-lib";import { createMetadataProvider } from "metabase-lib/test-helpers";@@ -138,11 +139,14 @@ describe("CodemirrorEditor", () => {expect(getDiffControls().previousLine).toHaveTextContent("LIMIT 10");});- it("keeps the editor configuration and styles stable when callbacks change", () => {+ it("keeps the editor configuration and styles stable when callbacks change", async () => {const { rerender, onRejectProposed } = setup({text: ORIGINAL,proposedText: PROPOSED,});++ await waitForRequestsToSettle();+const styleRuleCount = () =>Array.from(document.styleSheets).reduce((count, sheet) => count + sheet.cssRules.length,@@ -180,10 +184,13 @@ describe("CodemirrorEditor", () => {expect(onAcceptProposed).toHaveBeenCalledTimes(1);});- it("Should render the natie query's text", () => {+ it("Should render the natie query's text", async () => {const text = "SELECT 1;";setup({ text });++ await waitForRequestsToSettle();+expect(screen.getByRole("textbox")).toHaveTextContent(text);});@@ -215,13 +222,15 @@ describe("CodemirrorEditor", () => {},])("resolves the proposal with the $platform shortcuts",- ({ isWindows, hint, modifiers }) => {+ async ({ isWindows, hint, modifiers }) => {jest.spyOn(Browser, "isWindows").mockReturnValue(isWindows);const { onAcceptProposed, onRejectProposed, onRunQuery } = setup({text: "SELECT 1",proposedText: "SELECT 2",});+ await waitForRequestsToSettle();+expect(screen.getByRole("button", { name: /Accept/ })).toHaveTextContent(`Accept${hint}Y`,);@@ -246,12 +255,14 @@ describe("CodemirrorEditor", () => {},);- it("runs the query with Ctrl+Enter while reviewing a proposal", () => {+ it("runs the query with Ctrl+Enter while reviewing a proposal", async () => {const { onRunQuery } = setup({text: "SELECT 1",proposedText: "SELECT 2",});+ await waitForRequestsToSettle();+fireEvent.keyDown(screen.getByRole("textbox"), {key: "Enter",ctrlKey: true,@@ -260,9 +271,11 @@ describe("CodemirrorEditor", () => {expect(onRunQuery).toHaveBeenCalledTimes(1);});- it("keeps read-only proposals read-only", () => {+ it("keeps read-only proposals read-only", async () => {setup({ text: "SELECT 1", proposedText: "SELECT 2", readOnly: true });+ await waitForRequestsToSettle();+expect(screen.queryByRole("button", { name: /Accept/ }),).not.toBeInTheDocument();diff --git a/frontend/src/metabase/querying/filters/components/FilterPicker/FilterValuePicker/FilterValuePicker.unit.spec.tsx b/frontend/src/metabase/querying/filters/components/FilterPicker/FilterValuePicker/FilterValuePicker.unit.spec.tsxindex cc0bd9dbc72..cee077d9860 100644--- a/frontend/src/metabase/querying/filters/components/FilterPicker/FilterValuePicker/FilterValuePicker.unit.spec.tsx+++ b/frontend/src/metabase/querying/filters/components/FilterPicker/FilterValuePicker/FilterValuePicker.unit.spec.tsx@@ -7,7 +7,6 @@ import {setupRemappedFieldValueEndpoint,} from "__support__/server-mocks";import {- act,createMockClipboardData,renderWithProviders,screen,@@ -807,11 +806,12 @@ describe("StringFilterValuePicker", () => {const input = screen.getByRole("combobox", { name: "Filter value" });await userEvent.type(input, "[email protected]");- // blurring commits the typed value; wrap it so the resulting state- // updates in MultiAutocomplete are flushed inside act()- act(() => {- input.blur();- });++ // Clicking away commits the typed value, the way MultiAutocomplete's+ // own spec blurs it. The input clears once the commit lands.+ await userEvent.click(document.body);+ await waitFor(() => expect(input).toHaveValue(""));+expect(onChange).toHaveBeenLastCalledWith(["[email protected]"]);});diff --git a/frontend/src/metabase/querying/notebook/components/NotebookStep/NotebookStep.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/NotebookStep/NotebookStep.unit.spec.tsxindex fef5e90c055..57ee93fb0eb 100644--- a/frontend/src/metabase/querying/notebook/components/NotebookStep/NotebookStep.unit.spec.tsx+++ b/frontend/src/metabase/querying/notebook/components/NotebookStep/NotebookStep.unit.spec.tsx@@ -69,12 +69,12 @@ const STEP_TYPES: NotebookStepType[] = [];describe("NotebookStep", () => {- test.each(STEP_TYPES)(`renders a %s step correctly`, (type) => {+ test.each(STEP_TYPES)(`renders a %s step correctly`, async (type) => {const step = createMockNotebookStep({ type });const testId = `step-${type}-${step.stageIndex}-${step.itemIndex}`;setup({ step });- expect(screen.getByTestId(testId)).toBeInTheDocument();+ expect(await screen.findByTestId(testId)).toBeInTheDocument();expect(screen.getByRole("button", { name: "Remove step" }),).toBeInTheDocument();diff --git a/frontend/src/metabase/router/lazy-route.unit.spec.tsx b/frontend/src/metabase/router/lazy-route.unit.spec.tsxindex b412dc50f9e..f0d2f96ea22 100644--- a/frontend/src/metabase/router/lazy-route.unit.spec.tsx+++ b/frontend/src/metabase/router/lazy-route.unit.spec.tsx@@ -1,4 +1,4 @@-import { render, renderRoutes, screen } from "__support__/ui";+import { act, render, renderRoutes, screen } from "__support__/ui";import {type NavigateFunction,type RouteObject,@@ -37,7 +37,9 @@ describe("a lazy route", () => {seen.push(pathname),);- router?.navigate("/split");+ act(() => {+ router?.navigate("/split");+ });expect(router?.location.pathname).toBe("/");expect(seen).toEqual([]);@@ -52,7 +54,9 @@ describe("a lazy route", () => {it("keeps the previous page mounted while the module loads", async () => {const { router } = renderRoutes(makeRoutes(), { initialRoute: "/" });- router?.navigate("/split");+ act(() => {+ router?.navigate("/split");+ });expect(screen.getByTestId("home")).toBeInTheDocument();expect(await screen.findByTestId("split")).toBeInTheDocument();@@ -84,8 +88,12 @@ describe("a lazy route", () => {it("drops a pending navigation if another one lands first", async () => {const { router } = renderRoutes(makeRoutes(), { initialRoute: "/" });- router?.navigate("/split");- router?.navigate("/");+ act(() => {+ router?.navigate("/split");+ });+ act(() => {+ router?.navigate("/");+ });await new Promise((resolve) => setTimeout(resolve, 50));@@ -102,7 +110,9 @@ describe("a lazy route", () => {it("reports the window to a caller navigating in the same tick", async () => {const { navigate } = setupCapturingNavigate();- navigate?.("/split");+ act(() => {+ navigate?.("/split");+ });expect(getIsNavigationPending()).toBe(true);expect(await screen.findByTestId("split")).toBeInTheDocument();@@ -117,7 +127,9 @@ describe("a lazy route", () => {it("reports no window for a navigation that commits during the call", () => {const { navigate } = setupCapturingNavigate();- navigate?.("/plain");+ act(() => {+ navigate?.("/plain");+ });expect(getIsNavigationPending()).toBe(false);});@@ -140,7 +152,9 @@ describe("a lazy route", () => {await load();- router?.navigate("/split");+ act(() => {+ router?.navigate("/split");+ });expect(router?.location.pathname).toBe("/");expect(await screen.findByTestId("split")).toBeInTheDocument();@@ -152,13 +166,19 @@ describe("a lazy route", () => {it("is synchronous again on the second visit", async () => {const { router } = renderRoutes(makeRoutes(), { initialRoute: "/" });- router?.navigate("/split");+ act(() => {+ router?.navigate("/split");+ });expect(await screen.findByTestId("split")).toBeInTheDocument();- router?.navigate("/");+ act(() => {+ router?.navigate("/");+ });expect(await screen.findByTestId("home")).toBeInTheDocument();- router?.navigate("/split");+ act(() => {+ router?.navigate("/split");+ });expect(router?.location.pathname).toBe("/split");});diff --git a/frontend/src/metabase/router/route-leave-scope.unit.spec.tsx b/frontend/src/metabase/router/route-leave-scope.unit.spec.tsxindex d0a5627eb9a..26db9e40eef 100644--- a/frontend/src/metabase/router/route-leave-scope.unit.spec.tsx+++ b/frontend/src/metabase/router/route-leave-scope.unit.spec.tsx@@ -1,4 +1,4 @@-import { renderWithProviders, screen } from "__support__/ui";+import { act, renderWithProviders, screen } from "__support__/ui";import {Outlet,Route,@@ -46,7 +46,9 @@ describe("route-scoped leave hook", () => {});expect(await screen.findByTestId("a")).toBeInTheDocument();- navigate("/section/b");+ act(() => {+ navigate("/section/b");+ });expect(await screen.findByTestId("b")).toBeInTheDocument();expect(screen.getByTestId("location")).toHaveTextContent("/section/b");@@ -59,7 +61,9 @@ describe("route-scoped leave hook", () => {});expect(await screen.findByTestId("a")).toBeInTheDocument();- navigate("/other");+ act(() => {+ navigate("/other");+ });await new Promise((resolve) => setTimeout(resolve, 30));expect(screen.queryByTestId("other")).not.toBeInTheDocument();diff --git a/frontend/src/metabase/router/router-engine.unit.spec.tsx b/frontend/src/metabase/router/router-engine.unit.spec.tsxindex 1c05505606a..080b353f6ea 100644--- a/frontend/src/metabase/router/router-engine.unit.spec.tsx+++ b/frontend/src/metabase/router/router-engine.unit.spec.tsx@@ -1,6 +1,6 @@import userEvent from "@testing-library/user-event";-import { renderWithProviders, screen } from "__support__/ui";+import { act, renderWithProviders, screen } from "__support__/ui";import {Outlet,Route,@@ -79,7 +79,9 @@ describe("v7 engine (facade over real react-router v7)", () => {it("resolves a relative navigate() from the root", async () => {setup("/things/42");- navigate({ pathname: "other" });+ act(() => {+ navigate({ pathname: "other" });+ });expect(await screen.findByTestId("other")).toBeInTheDocument();});diff --git a/frontend/src/metabase/router/router-listen.unit.spec.tsx b/frontend/src/metabase/router/router-listen.unit.spec.tsxindex c09c3ab6a87..6c9ab2528da 100644--- a/frontend/src/metabase/router/router-listen.unit.spec.tsx+++ b/frontend/src/metabase/router/router-listen.unit.spec.tsx@@ -1,6 +1,6 @@import { useEffect, useState } from "react";-import { renderWithProviders, screen } from "__support__/ui";+import { act, renderWithProviders, screen } from "__support__/ui";import { Outlet, Route, navigate, subscribeLocation } from "metabase/router";// `subscribeLocation` fires a callback on every location change and returns an@@ -37,7 +37,9 @@ describe("subscribeLocation", () => {await screen.findByTestId("seen");- navigate("/other");+ act(() => {+ navigate("/other");+ });await screen.findByText("other");expect(screen.getByTestId("seen")).toHaveTextContent("/other");diff --git a/frontend/src/metabase/status/components/StatusListing/StatusListing.unit.spec.tsx b/frontend/src/metabase/status/components/StatusListing/StatusListing.unit.spec.tsxindex 3c8095db65f..3ff6111892b 100644--- a/frontend/src/metabase/status/components/StatusListing/StatusListing.unit.spec.tsx+++ b/frontend/src/metabase/status/components/StatusListing/StatusListing.unit.spec.tsx@@ -9,6 +9,7 @@ import {createMockUpload,} from "__support__/state";import { renderWithProviders, screen } from "__support__/ui";+import { waitForRequestsToSettle } from "__support__/utils";import type { DownloadsState } from "metabase/redux/store";import type { FileUploadState } from "metabase/redux/store/upload";import type { Database } from "metabase-types/api";@@ -87,11 +88,14 @@ describe("StatusListing", () => {expect(screen.queryByText("Syncing…")).not.toBeInTheDocument();});- it("should give an alert if a user navigates away from the page during an upload", () => {+ it("should give an alert if a user navigates away from the page during an upload", async () => {const mockEventListener = jest.spyOn(window, "addEventListener");const mockUpload = createMockUpload();setup({ isAdmin: true, upload: { [mockUpload.id]: mockUpload } });+ // The listing finishes loading with no change these tests can observe,+ // so flush that update rather than leaving it for the next test.+ await waitForRequestsToSettle();const mockEvent = callMockEvent(mockEventListener, "beforeunload");expect(mockEvent.returnValue).toEqual(@@ -100,10 +104,13 @@ describe("StatusListing", () => {expect(mockEvent.preventDefault).toHaveBeenCalled();});- it("should not give an alert if a user navigates away from the page while no uploads are in progress", () => {+ it("should not give an alert if a user navigates away from the page while no uploads are in progress", async () => {const mockEventListener = jest.spyOn(window, "addEventListener");setup({ isAdmin: true });+ // The listing finishes loading with no change these tests can observe,+ // so flush that update rather than leaving it for the next test.+ await waitForRequestsToSettle();const mockEvent = callMockEvent(mockEventListener, "beforeunload");expect(mockEvent.returnValue).toBeUndefined();diff --git a/frontend/src/metabase/transforms/components/ErrorSection/ErrorSection.unit.spec.tsx b/frontend/src/metabase/transforms/components/ErrorSection/ErrorSection.unit.spec.tsxindex 047966968c8..30015740cce 100644--- a/frontend/src/metabase/transforms/components/ErrorSection/ErrorSection.unit.spec.tsx+++ b/frontend/src/metabase/transforms/components/ErrorSection/ErrorSection.unit.spec.tsx@@ -13,14 +13,14 @@ function setup({ run = createMockTransformRun() }: SetupOpts = {}) {}describe("ErrorSection", () => {- it("should render the error title and message", () => {+ it("should render the error title and message", async () => {const run = createMockTransformRun({status: "failed",message: 'relation "abc" does not exist',});setup({ run });- expect(screen.getByText("Error")).toBeInTheDocument();+ expect(await screen.findByText("Error")).toBeInTheDocument();expect(screen.getByRole("region", { name: "Error" })).toBeInTheDocument();});diff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunSidebar/RunSidebar.unit.spec.tsx b/frontend/src/metabase/transforms/pages/RunListPage/RunSidebar/RunSidebar.unit.spec.tsxindex 6ddf0c7bd15..f5d6f966782 100644--- a/frontend/src/metabase/transforms/pages/RunListPage/RunSidebar/RunSidebar.unit.spec.tsx+++ b/frontend/src/metabase/transforms/pages/RunListPage/RunSidebar/RunSidebar.unit.spec.tsx@@ -55,14 +55,16 @@ describe("RunSidebar", () => {expect(screen.getByText("Success")).toBeInTheDocument();});- it("should render the error section when message is present", () => {+ it("should render the error section when message is present", async () => {const run = createMockTransformRun({status: "failed",message: "Something went wrong",});setup({ run });- expect(screen.getByRole("region", { name: "Error" })).toBeInTheDocument();+ expect(+ await screen.findByRole("region", { name: "Error" }),+ ).toBeInTheDocument();});it("should not render the error section when message is null", () => {diff --git a/frontend/src/metabase/transforms/pages/TransformSettingsPage/TransformSettingsSection/TransformSettingsSection.unit.spec.tsx b/frontend/src/metabase/transforms/pages/TransformSettingsPage/TransformSettingsSection/TransformSettingsSection.unit.spec.tsxindex 433383d6041..70c653e9d1c 100644--- a/frontend/src/metabase/transforms/pages/TransformSettingsPage/TransformSettingsSection/TransformSettingsSection.unit.spec.tsx+++ b/frontend/src/metabase/transforms/pages/TransformSettingsPage/TransformSettingsSection/TransformSettingsSection.unit.spec.tsx@@ -90,8 +90,9 @@ describe("TransformSettingsSection", () => {});describe("when remote sync is read-only", () => {- beforeEach(() => {+ beforeEach(async () => {setup({ remoteSyncReadOnly: true });+ await screen.findByRole("switch", { name: /Only process new data/ });});it("does not show the change target button", () => {diff --git a/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useTreeTableInstance.ts b/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useTreeTableInstance.tsindex 5cb0c96312d..2a21d6683e2 100644--- a/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useTreeTableInstance.ts+++ b/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useTreeTableInstance.ts@@ -216,6 +216,9 @@ export function useTreeTableInstance<TData extends TreeNodeData>(getFilteredRowModel: getFilteredRowModel(),filterFromLeafRows: true,globalFilterFn: effectiveFilterFn,+ // This table does not paginate, and the reset is queued rather than run+ // with the change that triggers it, which lands a state update on its own.+ autoResetPageIndex: false,initialState,});diff --git a/frontend/src/metabase/ui/components/overlays/Tooltip/Tooltip.config.tsx b/frontend/src/metabase/ui/components/overlays/Tooltip/Tooltip.config.tsxindex 0aa0ea82245..02f0b7e3fb0 100644--- a/frontend/src/metabase/ui/components/overlays/Tooltip/Tooltip.config.tsx+++ b/frontend/src/metabase/ui/components/overlays/Tooltip/Tooltip.config.tsx@@ -4,6 +4,8 @@ import {getDefaultZIndex,} from "@mantine/core";+import { isTest } from "metabase/env";+import { PORTAL_CONTAINER_ID } from "../PortalContainer/constants";import TooltipStyles from "./Tooltip.module.css";@@ -30,7 +32,10 @@ export const tooltipOverrides: MantineThemeOverride["components"] = {},transitionProps: {transition: "fade",- duration: 200,+ // Mantine drives a non-zero duration with two animation frames and a+ // timeout, which land state updates after a test has finished. At 0 it+ // sets the status synchronously instead.+ duration: isTest ? 0 : 200,},events: {hover: true,diff --git a/frontend/src/metabase/utils/react-to-html.unit.spec.tsx b/frontend/src/metabase/utils/react-to-html.unit.spec.tsxindex 491cbe9510c..5cdd77fcd12 100644--- a/frontend/src/metabase/utils/react-to-html.unit.spec.tsx+++ b/frontend/src/metabase/utils/react-to-html.unit.spec.tsx@@ -1,9 +1,16 @@+import { act } from "__support__/ui";+import { reactNodeToHtmlString } from "./react-to-html";describe("reactNodeToHtmlString", () => {it("should render a html string given a react node", () => {const node = <div>Hello, world!</div>;- const html = reactNodeToHtmlString(node);+ // The helper renders through `createRoot` and `flushSync`, so the render+ // it performs belongs inside act().+ let html = "";+ act(() => {+ html = reactNodeToHtmlString(node);+ });expect(html).toBe("<div>Hello, world!</div>");});diff --git a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.unit.spec.tsx b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.unit.spec.tsxindex e8677622a88..a10c2386a35 100644--- a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.unit.spec.tsx+++ b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.unit.spec.tsx@@ -273,10 +273,10 @@ function setup(}describe("ObjectDetailPanel", () => {- it("renders an object detail component", () => {+ it("renders an object detail component", async () => {setup({ question: mockQuestion });- expect(screen.getByText(/Product/i)).toBeInTheDocument();+ expect(await screen.findByText(/Product/i)).toBeInTheDocument();expect(screen.getByText(checkNotNull(testDataset.rows[0][2]).toString()),).toBeInTheDocument();@@ -344,10 +344,14 @@ describe("ObjectDetailPanel", () => {});describe("renders actions menu", () => {- beforeEach(() => {+ beforeEach(async () => {setupDatabasesEndpoints([databaseWithActionsEnabled]);setupActionsEndpoints(actions);setup({ question: mockDataset });+ // `ActionExecuteModal` initialises its values state after this render.+ // Nothing observable changes when it does, and it issues no request to+ // wait on, so flush that update rather than leaving it for the next test.+ await waitForRequestsToSettle();});it("should not show implicit create action", async () => {@@ -494,7 +498,7 @@ describe("ObjectDetailPanel", () => {const action = await findActionInActionMenu(implicitDeleteAction);expect(action).toBeInTheDocument();- action?.click();+ await userEvent.click(checkNotNull(action));const modal = await screen.findByTestId("delete-object-modal");expect(modal).toBeInTheDocument();diff --git a/frontend/src/metabase/visualizations/components/Visualization/Visualization-object.unit.spec.tsx b/frontend/src/metabase/visualizations/components/Visualization/Visualization-object.unit.spec.tsxindex 407fafc6036..c6c7847d8a0 100644--- a/frontend/src/metabase/visualizations/components/Visualization/Visualization-object.unit.spec.tsx+++ b/frontend/src/metabase/visualizations/components/Visualization/Visualization-object.unit.spec.tsx@@ -57,12 +57,12 @@ function setup({}describe("visualization - object", () => {- it("render fields with 'visibility_type' set as 'details-only'", () => {+ it("render fields with 'visibility_type' set as 'details-only'", async () => {const rows = [["John", "John Smith Jr"]];setup({ rows, longNameVisibility: "details-only" });- expect(screen.getByText("Long name")).toBeInTheDocument();+ expect(await screen.findByText("Long name")).toBeInTheDocument();expect(screen.getByText("John Smith Jr")).toBeInTheDocument();});});diff --git a/frontend/src/metabase/visualizations/components/settings/ColorRangeSelector/ColorRangeSelector.unit.spec.tsx b/frontend/src/metabase/visualizations/components/settings/ColorRangeSelector/ColorRangeSelector.unit.spec.tsxindex 6400c65fed1..07ef43546cc 100644--- a/frontend/src/metabase/visualizations/components/settings/ColorRangeSelector/ColorRangeSelector.unit.spec.tsx+++ b/frontend/src/metabase/visualizations/components/settings/ColorRangeSelector/ColorRangeSelector.unit.spec.tsx@@ -1,3 +1,4 @@+import userEvent from "@testing-library/user-event";import Color from "color";import { render, screen } from "__support__/ui";@@ -45,33 +46,37 @@ describe("ColorRangeSelector", () => {it("should call `onChange` upon clicking a color", async () => {const { onChange } = setup();- screen.getByRole("button").click();+ await userEvent.click(screen.getByRole("button"));expect(await screen.findByRole("dialog")).toBeInTheDocument();- (await screen.findByLabelText(color("core-summarize"))).click();+ await userEvent.click(+ await screen.findByLabelText(color("core-summarize")),+ );expect(onChange).toHaveBeenCalled();- screen.getByLabelText(color("core-filter")).click();+ await userEvent.click(screen.getByLabelText(color("core-filter")));expect(onChange).toHaveBeenCalled();});it("should call `onChange` upon clicking a non-initial range", async () => {const { onChange } = setup();- screen.getByRole("button").click();+ await userEvent.click(screen.getByRole("button"));expect(await screen.findByRole("dialog")).toBeInTheDocument();- (await screen.findByLabelText(getColorRangeLabel(DEFAULT_VALUE))).click();+ await userEvent.click(+ await screen.findByLabelText(getColorRangeLabel(DEFAULT_VALUE)),+ );expect(onChange).not.toHaveBeenCalled();- (- await screen.findByLabelText(getColorRangeLabel(WHITE_COLOR_RANGE))- ).click();+ await userEvent.click(+ await screen.findByLabelText(getColorRangeLabel(WHITE_COLOR_RANGE)),+ );expect(onChange).toHaveBeenCalled();- (- await screen.findByLabelText(getColorRangeLabel(WARNING_COLOR_RANGE))- ).click();+ await userEvent.click(+ await screen.findByLabelText(getColorRangeLabel(WARNING_COLOR_RANGE)),+ );expect(onChange).toHaveBeenCalled();});});diff --git a/frontend/test/jest-setup-env.js b/frontend/test/jest-setup-env.jsindex 93e784b9721..7f44a2ad23c 100644--- a/frontend/test/jest-setup-env.js+++ b/frontend/test/jest-setup-env.js@@ -15,12 +15,14 @@ const fetchMock = fetchMockModule;// A passing wait is not affected, and no test relies on the timeout to pass.configure({ asyncUtilTimeout: 10000 });-const REACT_KEY_WARNING_PATTERNS = [+const FAILING_REACT_WARNING_PATTERNS = [/Each child in a list should have a unique "key" prop/,/Encountered two children with the same key/,+ /was not wrapped in act\(/,+ /not configured to support act\(/,];-const reactKeyWarnings = [];+const reactWarnings = [];const originalConsoleError = console.error;// Throwing here would land inside React's render, where an error boundary can@@ -29,25 +31,15 @@ console.error = (...args) => {originalConsoleError(...args);const [template] = args;- const isReactKeyWarning =+ const isFailingReactWarning =typeof template === "string" &&- REACT_KEY_WARNING_PATTERNS.some((pattern) => pattern.test(template));+ FAILING_REACT_WARNING_PATTERNS.some((pattern) => pattern.test(template));- if (isReactKeyWarning) {- reactKeyWarnings.push(format(...args));+ if (isFailingReactWarning) {+ reactWarnings.push(format(...args));}};-afterEach(() => {- const warnings = reactKeyWarnings.splice(0);-- if (warnings.length > 0) {- throw new Error(- `Test completed with React key warnings:\n${warnings.join("\n")}`,- );- }-});-// jsdom has no layout, so popover positioning computes nothing useful while// costing getComputedStyle calls and an extra re-render per position update.jest.mock("@floating-ui/dom", () => ({@@ -115,6 +107,12 @@ afterEach(async () => {fetchMock.removeRoutes();fetchMock.callHistory.clear();+ // Unmount effects and the flush above both render, so the warnings are read+ // once that work is done and this test still owns them. Draining before the+ // throw below keeps a test that fails for another reason from reporting its+ // warnings against the next one.+ const warnings = reactWarnings.splice(0);+if (unmatched.length > 0) {const errors = unmatched.map((call) => `Unmocked ${call.options.method} request to: ${call.url}`,@@ -123,4 +121,13 @@ afterEach(async () => {`Test completed with unmocked routes:\n${errors.join("\n")}`,);}++ if (warnings.length > 0) {+ throw new Error(+ `Test completed with React warnings:\n${warnings.join("\n")}\n` ++ "A warning can come from work that an earlier test left pending. If this " ++ "test passes on its own, look at the test before it for a render or a " ++ "request that nothing awaits.",+ );+ }});