Skip to content

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

Compile jest imports lazily (#82998)

Romeo Van Snickee4510a467fb
diff --git a/bun.lock b/bun.lock
index 13b4dc14bab..ad7d5132eba 100644
--- a/bun.lock
+++ b/bun.lock
@@ -294,6 +294,7 @@
"inquirer-file-selector": "^0.2.1",
"jest": "^30.0.0",
"jest-canvas-mock": "2.5.2",
+ "jest-circus": "30.2.0",
"jest-environment-jsdom": "^30.0.0",
"jest-junit": "^16.0.0",
"jest-watch-typeahead": "^3.0.0",
@@ -4899,7 +4900,7 @@
"strip-ansi-cjs": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
- "strip-bom": ["[email protected]", "", {}, "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM="],
+ "strip-bom": ["[email protected]", "", {}, "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w=="],
"strip-final-newline": ["[email protected]", "", {}, "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA=="],
@@ -5945,8 +5946,6 @@
"deep-equal/which-typed-array": ["[email protected]", "", { "dependencies": { "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.7", "for-each": "^0.3.3", "gopd": "^1.0.1", "has-tostringtag": "^1.0.2" } }, "sha512-oV0jmFtUky6CXfkqehVvBP/LSWJ2sy4vWMioiENyJLePrBO/yKyV9OyJySfAKosh+RYkIl5zJCNZ8/4JncrpdA=="],
- "default-require-extensions/strip-bom": ["[email protected]", "", {}, "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w=="],
-
"define-data-property/es-define-property": ["[email protected]", "", { "dependencies": { "get-intrinsic": "^1.2.4" } }, "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ=="],
"define-data-property/gopd": ["[email protected]", "", { "dependencies": { "get-intrinsic": "^1.1.3" } }, "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA=="],
@@ -6277,8 +6276,6 @@
"jest-runtime/slash": ["[email protected]", "", {}, "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q=="],
- "jest-runtime/strip-bom": ["[email protected]", "", {}, "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w=="],
-
"jest-snapshot/pretty-format": ["[email protected]", "", { "dependencies": { "@jest/schemas": "30.0.5", "ansi-styles": "^5.2.0", "react-is": "^18.3.1" } }, "sha512-9uBdv/B4EefsuAL+pWqueZyZS2Ba+LxfFeQ9DN14HU4bN8bhaxKdkpjpB6fs9+pSjIBu+FXQHImEg8j/Lw0+vA=="],
"jest-snapshot/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
@@ -6779,6 +6776,8 @@
"transliteration/yargs": ["[email protected]", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="],
+ "tsconfig-paths/strip-bom": ["[email protected]", "", {}, "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM="],
+
"tsconfig-paths-webpack-plugin/tapable": ["[email protected]", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="],
"tsx/get-tsconfig": ["[email protected]", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-k9PN+cFBmaLWtVz29SkUoqU5O0slLuHJXt/2P+tMVFT+phsSGXGkp9t3rQIqdz0e+06EHNGs3oM6ZX1s2zHxRg=="],
diff --git a/enterprise/frontend/src/embedding-sdk-ee/notifications/QuestionAlertsButton.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-ee/notifications/QuestionAlertsButton.unit.spec.tsx
index 65389a4275b..dede01ddac5 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/notifications/QuestionAlertsButton.unit.spec.tsx
+++ b/enterprise/frontend/src/embedding-sdk-ee/notifications/QuestionAlertsButton.unit.spec.tsx
@@ -6,6 +6,7 @@ import {
} from "__support__/server-mocks";
import { createMockState } from "__support__/state";
import { createMockSettingsState } from "__support__/state/settings";
+import { waitForRequestsToSettle } from "__support__/utils";
import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui";
import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";
import {
@@ -119,17 +120,13 @@ describe("QuestionAlertsButton", () => {
// would 403 as soon as it was clicked.
setup({ isDataApp: true });
- // Give the probe the same window the first test needs to make it, and assert it never
- // arrives. Asserting straight after render would pass either way, since nothing has
- // resolved yet at that point.
- await expect(
- waitFor(async () => {
- expect(await getFormInputRequests()).toHaveLength(1);
- }),
- ).rejects.toThrow();
+ // The data-app check is synchronous, so nothing can issue the request later.
+ // Settle any fetch that did start before asserting none was the probe.
+ await waitForRequestsToSettle();
expect(
screen.queryByRole("button", { name: "Alerts" }),
).not.toBeInTheDocument();
+ expect(await getFormInputRequests()).toHaveLength(0);
});
});
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterBanner/SecurityCenterBanner.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterBanner/SecurityCenterBanner.unit.spec.tsx
index e1038b7fdcb..5bc2f33c573 100644
--- a/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterBanner/SecurityCenterBanner.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterBanner/SecurityCenterBanner.unit.spec.tsx
@@ -4,6 +4,7 @@ import { setupNotificationChannelsEndpoints } from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { createMockState } from "__support__/state";
import { renderWithProviders, screen } from "__support__/ui";
+import { waitForRequestsToSettle } from "__support__/utils";
import { Route } from "metabase/router";
import type { Advisory } from "metabase-types/api";
import {
@@ -61,28 +62,28 @@ describe("SecurityCenterBanner", () => {
it("does not render when there is no active advisory", async () => {
setup();
- await screen.findByText(() => false).catch(() => {});
+ await waitForRequestsToSettle();
expect(screen.queryByTestId("app-banner")).not.toBeInTheDocument();
});
it("does not render when email is configured", async () => {
setup({ emailConfigured: true });
- await screen.findByText(() => false).catch(() => {});
+ await waitForRequestsToSettle();
expect(screen.queryByTestId("app-banner")).not.toBeInTheDocument();
});
it("does not render when slack is configured", async () => {
setup({ slackConfigured: true });
- await screen.findByText(() => false).catch(() => {});
+ await waitForRequestsToSettle();
expect(screen.queryByTestId("app-banner")).not.toBeInTheDocument();
});
it("does not render for non-pro-self-hosted plans", async () => {
setup({ isProSelfHosted: false });
- await screen.findByText(() => false).catch(() => {});
+ await waitForRequestsToSettle();
expect(screen.queryByTestId("app-banner")).not.toBeInTheDocument();
});
diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.unit.spec.tsx
index 2627b9b0902..613021ea06e 100644
--- a/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.unit.spec.tsx
@@ -846,7 +846,8 @@ describe("useGetPathFromValue", () => {
],
});
- // doing this manually here to get a delay
+ // Delayed by hand, so the loading state stays observable for longer than
+ // waitFor's 50ms polling interval.
fetchMock.get(
`path:/api/collection/${parentCollection.id}/items`,
() => {
@@ -860,7 +861,7 @@ describe("useGetPathFromValue", () => {
],
};
},
- { name: `collection-${parentCollection.id}-items`, delay: 50 },
+ { name: `collection-${parentCollection.id}-items`, delay: 300 },
);
setupCollectionItemsEndpoint({
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.unit.spec.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.unit.spec.ts
index 82f0ebf2e9a..001cf55cb66 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.unit.spec.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.unit.spec.ts
@@ -27,10 +27,14 @@ describe("embed.js script tag for sdk iframe embedding", () => {
let consoleErrorSpy: jest.SpyInstance;
beforeEach(() => {
- jest.resetModules();
delete window.metabaseConfig;
- // eslint-disable-next-line @typescript-eslint/no-require-imports -- require after jest.resetModules
- require("./embed"); // we do things when the script is loaded
+ // The script does things when it is loaded, so load a fresh copy per test.
+ // Isolating it keeps the shared modules, such as fetch-mock, on the same
+ // instance the setup files hold.
+ jest.isolateModules(() => {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports -- a fresh copy per test
+ require("./embed");
+ });
document.body.innerHTML = "";
consoleErrorSpy = jest.spyOn(console, "error").mockImplementation(() => {});
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.ts
index cd53041f145..4594577c850 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
@@ -90,7 +90,7 @@ async function baseSetup({
// call methods on it in tests where the snippet endpoint is mocked.
const dispatch = jest.fn((action) => action);
await initializeQB(location, params)(dispatch, getState);
- jest.runAllTimers();
+ jest.runOnlyPendingTimers();
const actions = dispatch.mock.calls.find(
(call) => call[0]?.type === sharedQB.INITIALIZE_QB,
@@ -733,13 +733,13 @@ describe("QB Actions > initializeQB", () => {
// Second init runs to completion, superseding the first
await startInitializeDB(secondCard, dispatch, getState);
- jest.runAllTimers();
+ jest.runOnlyPendingTimers();
// Unblock the first init; it should bail out once it sees the version
// has been superseded.
resolveFirstLoad(firstCard);
await firstInit;
- jest.runAllTimers();
+ jest.runOnlyPendingTimers();
const initActions = dispatch.mock.calls.filter(
(call) => call[0]?.type === sharedQB.INITIALIZE_QB,
@@ -784,11 +784,11 @@ describe("QB Actions > initializeQB", () => {
await Promise.resolve();
await startInitializeDB(secondCard, dispatch, getState);
- jest.runAllTimers();
+ jest.runOnlyPendingTimers();
resolveFirstLoad(firstCard);
await firstInit;
- jest.runAllTimers();
+ jest.runOnlyPendingTimers();
const archiveError = setErrorPage(
expect.objectContaining({ data: { error_code: "archived" } }),
diff --git a/frontend/src/metabase/ui/components/data-display/Accordion/Accordion.config.tsx b/frontend/src/metabase/ui/components/data-display/Accordion/Accordion.config.tsx
index 82701362c0e..07febff2443 100644
--- a/frontend/src/metabase/ui/components/data-display/Accordion/Accordion.config.tsx
+++ b/frontend/src/metabase/ui/components/data-display/Accordion/Accordion.config.tsx
@@ -1,3 +1,4 @@
+import type { AccordionProps, MantineThemeComponent } from "@mantine/core";
import { Accordion } from "@mantine/core";
import { Icon } from "../../icons";
@@ -6,23 +7,33 @@ import AccordionStyles from "./Accordion.module.css";
const CHEVRON_SIZE = 12;
+/**
+ * A function, so that the theme holds no React element. Mantine deep-merges a
+ * nested provider's theme into its parent's, and a React element keeps a
+ * reference to the fiber that rendered it, which turns that merge into a walk
+ * over the fiber tree.
+ */
+const getDefaultProps = (): Partial<AccordionProps> => ({
+ variant: "separated",
+ radius: "sm",
+ chevron: <Icon name="chevrondown" size={CHEVRON_SIZE} aria-hidden />,
+ chevronSize: CHEVRON_SIZE,
+});
+
export const accordionOverrides = {
- Accordion: Accordion.extend({
- defaultProps: {
- variant: "separated",
- radius: "sm",
- chevron: <Icon name="chevrondown" size={CHEVRON_SIZE} aria-hidden />,
- chevronSize: CHEVRON_SIZE,
- },
- classNames: {
- root: AccordionStyles.root,
- control: AccordionStyles.control,
- label: AccordionStyles.label,
- icon: AccordionStyles.icon,
- item: AccordionStyles.item,
- content: AccordionStyles.content,
- chevron: AccordionStyles.chevron,
- panel: AccordionStyles.panel,
- },
- }),
+ Accordion: {
+ ...Accordion.extend({
+ classNames: {
+ root: AccordionStyles.root,
+ control: AccordionStyles.control,
+ label: AccordionStyles.label,
+ icon: AccordionStyles.icon,
+ item: AccordionStyles.item,
+ content: AccordionStyles.content,
+ chevron: AccordionStyles.chevron,
+ panel: AccordionStyles.panel,
+ },
+ }),
+ defaultProps: getDefaultProps,
+ } satisfies MantineThemeComponent,
};
diff --git a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.unit.spec.tsx b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.unit.spec.tsx
index d0e3885645d..e8677622a88 100644
--- a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.unit.spec.tsx
+++ b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.unit.spec.tsx
@@ -9,7 +9,7 @@ import {
} from "__support__/server-mocks";
import { testDataset } from "__support__/testDataset";
import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
-import { getNextId } from "__support__/utils";
+import { getNextId, waitForRequestsToSettle } from "__support__/utils";
import { checkNotNull } from "metabase/utils/types";
import type { WritebackAction } from "metabase-types/api";
import {
@@ -396,8 +396,7 @@ describe("ObjectDetailPanel", () => {
setupActionsEndpoints(actionsFromDatabaseWithDisabledActions);
setup({ question: mockDataset });
- const actionsMenu = await findActionsMenu();
- expect(actionsMenu).toBeUndefined();
+ await expectNoActionsMenu();
});
it("should not render actions menu for non-model questions", async () => {
@@ -405,8 +404,7 @@ describe("ObjectDetailPanel", () => {
setupActionsEndpoints(actions);
setup({ question: mockQuestion });
- const actionsMenu = await findActionsMenu();
- expect(actionsMenu).toBeUndefined();
+ await expectNoActionsMenu();
});
it(`should not render actions menu when "showControls" is "false"`, async () => {
@@ -414,8 +412,7 @@ describe("ObjectDetailPanel", () => {
setupActionsEndpoints(actions);
setup({ question: mockDataset, showControls: false });
- const actionsMenu = await findActionsMenu();
- expect(actionsMenu).toBeUndefined();
+ await expectNoActionsMenu();
});
it("should render actions menu when user has write permission", async () => {
@@ -423,8 +420,7 @@ describe("ObjectDetailPanel", () => {
setupActionsEndpoints(actions);
setup({ question: mockDataset });
- const actionsMenu = await findActionsMenu();
- expect(actionsMenu).toBeInTheDocument();
+ expect(await screen.findByTestId("actions-menu")).toBeInTheDocument();
});
it("should not render actions menu when user has no write permission", async () => {
@@ -432,8 +428,7 @@ describe("ObjectDetailPanel", () => {
setupActionsEndpoints(actions);
setup({ question: mockDatasetNoWritePermission });
- const actionsMenu = await findActionsMenu();
- expect(actionsMenu).toBeUndefined();
+ await expectNoActionsMenu();
});
/**
@@ -446,8 +441,7 @@ describe("ObjectDetailPanel", () => {
setupActionsEndpoints(actions);
setup({ question: mockDatasetWithClauses });
- const actionsMenu = await findActionsMenu();
- expect(actionsMenu).toBeUndefined();
+ await expectNoActionsMenu();
});
it("should not render actions menu when model's source table does not have a primary key", async () => {
@@ -455,8 +449,7 @@ describe("ObjectDetailPanel", () => {
setupActionsEndpoints(actions);
setup({ question: mockDatasetNoPk });
- const actionsMenu = await findActionsMenu();
- expect(actionsMenu).toBeUndefined();
+ await expectNoActionsMenu();
});
it("should not render actions menu when model's source table has multiple primary keys", async () => {
@@ -464,8 +457,7 @@ describe("ObjectDetailPanel", () => {
setupActionsEndpoints(actions);
setup({ question: mockDatasetMultiplePks });
- const actionsMenu = await findActionsMenu();
- expect(actionsMenu).toBeUndefined();
+ await expectNoActionsMenu();
});
it("should show update object modal on update action click", async () => {
@@ -560,13 +552,11 @@ async function findActionInActionMenu({ name }: Pick<WritebackAction, "name">) {
}
/**
- * There is no loading indicator in ObjectDetail component, so there is no easy way
- * to wait for relevant API requests to finish. This function relies on DOM changes instead.
+ * The menu appears once the actions and databases requests resolve, so settle
+ * them before asserting it is absent.
*/
-async function findActionsMenu() {
- try {
- return await screen.findByTestId("actions-menu");
- } catch (error) {
- return undefined;
- }
+async function expectNoActionsMenu() {
+ await screen.findByTestId("object-detail");
+ await waitForRequestsToSettle();
+ expect(screen.queryByTestId("actions-menu")).not.toBeInTheDocument();
}
diff --git a/frontend/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsx
index 83dabd85e2d..785771ceecf 100644
--- a/frontend/test/__support__/ui.tsx
+++ b/frontend/test/__support__/ui.tsx
@@ -574,14 +574,9 @@ export function getBrokenUpTextMatcher(textToFind: string): MatcherFunction {
* @see https://metaboat.slack.com/archives/C505ZNNH4/p1684753502335459?thread_ts=1684751522.480859&cid=C505ZNNH4
*/
export const waitForLoaderToBeRemoved = async () => {
- await waitFor(
- () => {
- expect(screen.queryByTestId("loading-indicator")).not.toBeInTheDocument();
- // default timeout is 1s, but sometimes it's not enough and leads to flakiness,
- // 3s should be enough
- },
- { timeout: 3000 },
- );
+ await waitFor(() => {
+ expect(screen.queryByTestId("loading-indicator")).not.toBeInTheDocument();
+ });
};
/**
diff --git a/frontend/test/__support__/utils.ts b/frontend/test/__support__/utils.ts
index 6169b1e1f08..d9905a778f8 100644
--- a/frontend/test/__support__/utils.ts
+++ b/frontend/test/__support__/utils.ts
@@ -1,4 +1,4 @@
-import type { CallLog } from "fetch-mock";
+import fetchMock, { type CallLog } from "fetch-mock";
import { act, waitFor } from "./ui";
@@ -90,3 +90,14 @@ export const waitForRequest = async (requestFn: () => CallLog | undefined) => {
throw error;
}
};
+
+/**
+ * Resolves every mocked request that has started and lets the state updates
+ * they cause reach the DOM. Use it before asserting that something did not
+ * render, where there is nothing to wait for.
+ */
+export const waitForRequestsToSettle = async () => {
+ await act(() => fetchMock.callHistory.flush(true));
+ // RTK Query commits the results on the next task.
+ await act(() => new Promise((resolve) => setTimeout(resolve, 0)));
+};
diff --git a/frontend/test/i18n-import-time.unit.spec.ts b/frontend/test/i18n-import-time.unit.spec.ts
index 63caca41941..870d95857ad 100644
--- a/frontend/test/i18n-import-time.unit.spec.ts
+++ b/frontend/test/i18n-import-time.unit.spec.ts
@@ -96,16 +96,10 @@ const UNIMPORTABLE = new Set<string>([
// Build tooling: node scripts and bundler configs, not app code.
"enterprise/frontend/src/custom-viz/scripts/check-package-versions.ts",
"enterprise/frontend/src/custom-viz/src/cli.ts",
- "enterprise/frontend/src/custom-viz/src/pack.ts",
"enterprise/frontend/src/custom-viz/src/templates.ts",
"enterprise/frontend/src/custom-viz/src/templates/vite.config.ts",
"enterprise/frontend/src/custom-viz/vite.config.ts",
"enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx",
- "enterprise/frontend/src/embedding-sdk-package/data-app-dev.config.ts",
- "enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/build-config.ts",
- "enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/app-bundle.ts",
- "enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.ts",
- "enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.ts",
// Storybook data that reads a geojson asset webpack resolves.
"frontend/src/metabase/static-viz/components/StaticChoropleth/stories-data.ts",
diff --git a/frontend/test/jest-setup-eager.js b/frontend/test/jest-setup-eager.js
new file mode 100644
index 00000000000..3069c257983
--- /dev/null
+++ b/frontend/test/jest-setup-eager.js
@@ -0,0 +1,18 @@
+// Jest compiles imports lazily (see jest.base.conf.js), so a module runs the
+// first time a test reads one of its bindings. The modules below must run
+// before any test instead, so import them here, at the top level.
+
+// They register jest hooks when they run, and jest rejects a hook registered
+// once the run has started.
+import "@testing-library/react";
+import "@testing-library/user-event";
+
+// leaflet-draw reads `window.L`, which leaflet sets when it runs. The app
+// imports leaflet-draw before leaflet and relies on leaflet having run
+// earlier, which no longer happens on its own.
+import "leaflet";
+
+// It snapshots `window.MetabaseBootstrap` when it runs. Specs expect the
+// bootstrap from `metabase-bootstrap.js`, not the one the core `beforeEach`
+// merges mock settings into.
+import "metabase/utils/settings";
diff --git a/frontend/test/jest-setup-env.js b/frontend/test/jest-setup-env.js
index b4c43a3f25b..8ed40e55be0 100644
--- a/frontend/test/jest-setup-env.js
+++ b/frontend/test/jest-setup-env.js
@@ -1,8 +1,19 @@
import { format } from "util";
import "@testing-library/jest-dom";
-import { cleanup } from "@testing-library/react";
-import fetchMock from "fetch-mock";
+import * as testingLibrary from "@testing-library/react";
+import fetchMockModule from "fetch-mock";
+
+// Imports compile to lazy requires (see jest.base.conf.js). Resolve these at
+// the top level, so a spec that calls jest.resetModules() cannot make the
+// hooks below load a fresh copy once the run has started.
+const { cleanup, configure } = testingLibrary;
+const fetchMock = fetchMockModule;
+
+// The first render of a heavy component in a worker loads its modules inside
+// the waitFor window: 1.5s to 2.5s on a cold worker here, more on a CI runner.
+// A passing wait is not affected, and no test relies on the timeout to pass.
+configure({ asyncUtilTimeout: 10000 });
const REACT_KEY_WARNING_PATTERNS = [
/Each child in a list should have a unique "key" prop/,
diff --git a/frontend/test/jest-test-runner.js b/frontend/test/jest-test-runner.js
new file mode 100644
index 00000000000..d183dd51f56
--- /dev/null
+++ b/frontend/test/jest-test-runner.js
@@ -0,0 +1,12 @@
+const runCircus = require("jest-circus/runner").default;
+
+/**
+ * Imports load lazily (see jest.base.conf.js), so a module can load between a
+ * hook and its test, or after a test ends, when async rendering settles. Jest
+ * treats a load in those gaps as an import outside the test and throws. Keep
+ * the flag up for the whole file.
+ */
+module.exports = (globalConfig, config, environment, runtime, ...rest) => {
+ runtime.leaveTestCode = () => {};
+ return runCircus(globalConfig, config, environment, runtime, ...rest);
+};
diff --git a/jest.base.conf.js b/jest.base.conf.js
index 02723e3ccee..c663907064e 100644
--- a/jest.base.conf.js
+++ b/jest.base.conf.js
@@ -28,6 +28,10 @@ const swcJestTransform = [
},
module: {
type: "commonjs",
+ // A test file loads only the modules its tests touch, not its full import
+ // graph. Modules that must run before the tests start are listed in
+ // frontend/test/jest-setup-eager.js.
+ lazy: true,
},
sourceMaps: "inline",
minify: false,
@@ -110,7 +114,10 @@ const baseConfig = {
"<rootDir>/frontend/test/metabase-bootstrap.js",
"<rootDir>/frontend/test/register-visualizations.js",
],
- setupFilesAfterEnv: ["<rootDir>/frontend/test/jest-setup-env.js"],
+ setupFilesAfterEnv: [
+ "<rootDir>/frontend/test/jest-setup-eager.js",
+ "<rootDir>/frontend/test/jest-setup-env.js",
+ ],
globals: {
ga: {},
},
@@ -130,6 +137,7 @@ const baseConfig = {
"/frontend/test/",
],
testEnvironment: "jest-environment-jsdom",
+ testRunner: "<rootDir>/frontend/test/jest-test-runner.js",
};
// eslint-disable-next-line import/no-commonjs
diff --git a/package.json b/package.json
index e9bc20ee80a..5b855d393b4 100644
--- a/package.json
+++ b/package.json
@@ -303,6 +303,7 @@
"inquirer-file-selector": "^0.2.1",
"jest": "^30.0.0",
"jest-canvas-mock": "2.5.2",
+ "jest-circus": "30.2.0",
"jest-environment-jsdom": "^30.0.0",
"jest-junit": "^16.0.0",
"jest-watch-typeahead": "^3.0.0",