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
Harden tests against XHR vs fetch timing differences (#74897)
Romeo Van Snick41d9fa501df2
diff --git a/e2e/test/scenarios/admin-2/settings.cy.spec.js b/e2e/test/scenarios/admin-2/settings.cy.spec.jsindex 54be7fb1b68..54a0d63daaf 100644--- a/e2e/test/scenarios/admin-2/settings.cy.spec.js+++ b/e2e/test/scenarios/admin-2/settings.cy.spec.js@@ -988,7 +988,12 @@ describe("scenarios > admin > settings > map settings", () => {it("should show an informative error when adding a calid URL that contains GeoJSON that does not use lat/lng coordinates", () => {//intercept call to api/geojson and return projected.geojson. Call to load file actually happens in the BEcy.fixture("../../e2e/support/assets/projected.geojson").then((data) => {- cy.intercept("GET", "/api/geojson*", data);+ // The real endpoint responds with JSON; the fixture loads as a string, so+ // set the content type explicitly or the client returns it unparsed.+ cy.intercept("GET", "/api/geojson*", {+ headers: { "content-type": "application/json" },+ body: data,+ });});cy.visit("/admin/settings/maps");diff --git a/e2e/test/scenarios/admin/performance/caching.cy.spec.ts b/e2e/test/scenarios/admin/performance/caching.cy.spec.tsindex 9b77164015f..e79297db8fc 100644--- a/e2e/test/scenarios/admin/performance/caching.cy.spec.ts+++ b/e2e/test/scenarios/admin/performance/caching.cy.spec.ts@@ -132,7 +132,11 @@ describe("scenarios > admin > performance > caching", () => {cy.findByRole("switch").parent("label").click();cy.findByRole("switch").should("be.checked");});+ // After saving, the form reloads its config; wait for that reload before+ // re-opening so the assertion doesn't race a stale (pre-save) render.+ cy.intercept("GET", "/api/cache?model=*&id=*").as("reloadCacheConfig");saveCacheStrategyForm();+ cy.wait("@reloadCacheConfig");cy.findByLabelText("When to get new results").click();preemptiveCachingSwitch().findByRole("switch").should("be.checked");diff --git a/e2e/test/scenarios/admin/remote-sync.cy.spec.ts b/e2e/test/scenarios/admin/remote-sync.cy.spec.tsindex cc18d758aee..6b889ffc696 100644--- a/e2e/test/scenarios/admin/remote-sync.cy.spec.ts+++ b/e2e/test/scenarios/admin/remote-sync.cy.spec.ts@@ -945,6 +945,15 @@ describe("Remote Sync", () => {H.DataStudio.Transforms.visit();H.getPullOption().should("not.be.disabled").click();+ cy.log(+ "wait for the conflict modal to finish rendering before interacting",+ );+ H.modal()+ .findByRole("heading", {+ name: /Your local data will be overwritten by the remote branch/,+ })+ .should("be.visible");+cy.log("choose the new branch option and push");cy.findByLabelText(/Create a new branch and push changes there/).should("be.visible")diff --git a/e2e/test/scenarios/native/snippets.cy.spec.js b/e2e/test/scenarios/native/snippets.cy.spec.jsindex 3e1ce92a100..dd5ba738a4c 100644--- a/e2e/test/scenarios/native/snippets.cy.spec.js+++ b/e2e/test/scenarios/native/snippets.cy.spec.js@@ -294,12 +294,14 @@ describe("scenarios > question > snippets (EE)", () => {// check that everything is in the right spotcy.wait("@updateList");- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage- cy.findByText("snippet 1").should("not.exist");++ cy.findAllByText("snippet 1").should("have.length", 0);// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usagecy.findByText("my favorite snippets").click();- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage- cy.findByText("snippet 1");+ // The list re-renders while the move's refetch settles; assert on the settled+ // count so a transient duplicate/empty frame doesn't hard-fail `findByText`.++ cy.findAllByText("snippet 1").should("have.length", 1);cy.log("via collection picker (metabase#44930");@@ -321,9 +323,9 @@ describe("scenarios > question > snippets (EE)", () => {H.modal().findByRole("button", { name: "Save" }).click();cy.findByTestId("sidebar-right").within(() => {- cy.findByText("snippet 1").should("not.exist");+ cy.findAllByText("snippet 1").should("have.length", 0);cy.findByText("my special snippets").click();- cy.findByText("snippet 1").should("exist");+ cy.findAllByText("snippet 1").should("have.length", 1);});});diff --git a/frontend/src/metabase/admin/settings/components/ApiKeys/ManageApiKeys.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/ApiKeys/ManageApiKeys.unit.spec.tsxindex 3819bf66c75..341f23f0045 100644--- a/frontend/src/metabase/admin/settings/components/ApiKeys/ManageApiKeys.unit.spec.tsx+++ b/frontend/src/metabase/admin/settings/components/ApiKeys/ManageApiKeys.unit.spec.tsx@@ -138,7 +138,7 @@ describe("ManageApiKeys", () => {it("should regenerate an API key", async () => {await setup();const REGEN_URL = "path:/api/api-key/1/regenerate";- fetchMock.put(REGEN_URL, 200);+ fetchMock.put(REGEN_URL, { unmasked_key: "mb_regenerated" });await userEvent.click(within(@@ -157,10 +157,8 @@ describe("ManageApiKeys", () => {await screen.findByText("Copy and save the API key");expect(- await fetchMock.callHistory- .lastCall(REGEN_URL, { method: "PUT" })- ?.request?.json(),- ).toEqual({});+ fetchMock.callHistory.called(REGEN_URL, { method: "PUT" }),+ ).toBeTruthy();await waitFor(() => {expect(fetchMock.callHistory.calls("path:/api/api-key", { method: "GET" }),diff --git a/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/MoveDashboardStepContent.unit.spec.tsx b/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/MoveDashboardStepContent.unit.spec.tsxindex 0f736f79409..3d45a06ddaf 100644--- a/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/MoveDashboardStepContent.unit.spec.tsx+++ b/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/MoveDashboardStepContent.unit.spec.tsx@@ -90,7 +90,12 @@ describe("MoveDashboardStepContent", () => {});it("moves dashboard to shared collection when Move button is clicked", async () => {- fetchMock.put("path:/api/dashboard/200", 200);+ fetchMock.put("path:/api/dashboard/200", {+ id: 200,+ name: "A look at Invoices",+ collection_id: 42,+ dashcards: [],+ });const { onCompleted } = setup({ hasXrayDashboard: true });@@ -124,7 +129,12 @@ describe("MoveDashboardStepContent", () => {collection_id: 42,dashcards: [],});- fetchMock.put("path:/api/dashboard/999", 200);+ fetchMock.put("path:/api/dashboard/999", {+ id: 999,+ name: "Sample dashboard",+ collection_id: 42,+ dashcards: [],+ });const { onCompleted } = setup({ hasXrayDashboard: false });diff --git a/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.unit.spec.tsx b/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.unit.spec.tsxindex f2fc88c3a82..37e4a478a6e 100644--- a/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.unit.spec.tsx@@ -3,10 +3,11 @@ import userEvent from "@testing-library/user-event";import { setupEnterprisePlugins } from "__support__/enterprise";import { setupUserMetabotPermissionsEndpoint } from "__support__/server-mocks";import { mockSettings } from "__support__/settings";-import { renderWithProviders, screen, waitFor } from "__support__/ui";+import { renderWithProviders, screen } from "__support__/ui";import { mockStreamedEndpoint } from "metabase/api/ai-streaming/test-utils";import { MetabotProvider } from "metabase/metabot/context";import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";+import { lastReqBody } from "metabase/metabot/tests/utils";import { createMockState } from "metabase/redux/store/mocks";import { AIQuestionAnalysisButton } from "./AIQuestionAnalysisButton";@@ -81,9 +82,7 @@ describe("AIQuestionAnalysisButton", () => {await screen.findByRole("button", { name: "Explain this chart" }),);- await waitFor(() => expect(agentSpy).toHaveBeenCalled());- const lastCall = agentSpy.mock.lastCall;- const body = JSON.parse(lastCall?.[1]?.body as string);+ const body = await lastReqBody(agentSpy);expect(body.message).toBe("Analyze this chart");});diff --git a/frontend/src/metabase/metabot/tests/history.unit.spec.tsx b/frontend/src/metabase/metabot/tests/history.unit.spec.tsxindex 9abc261deec..23b6be5e9f2 100644--- a/frontend/src/metabase/metabot/tests/history.unit.spec.tsx+++ b/frontend/src/metabase/metabot/tests/history.unit.spec.tsx@@ -61,8 +61,7 @@ describe("metabot > history", () => {hideMetabot(store.dispatch);showMetabot(store.dispatch);await enterChatMessage("Hi!");- const lastCall = agentSpy.mock.lastCall;- const reqBody = JSON.parse(String(lastCall?.[1]?.body));+ const reqBody = await lastReqBody(agentSpy);const sentHistory = reqBody.history;expect(sentHistory).not.toEqual([]);});diff --git a/frontend/src/metabase/metabot/tests/utils.tsx b/frontend/src/metabase/metabot/tests/utils.tsxindex 6324fb6dc83..4a23426d828 100644--- a/frontend/src/metabase/metabot/tests/utils.tsx+++ b/frontend/src/metabase/metabot/tests/utils.tsx@@ -130,7 +130,15 @@ export const lastReqBody = async (agentSpy: ReturnType<typeof mockAgentEndpoint>,) => {await waitFor(() => expect(agentSpy).toHaveBeenCalled());- return JSON.parse(agentSpy.mock.lastCall?.[1]?.body as string);+ // Today the client calls `fetch(url, init)`, so the body is on `init`. A+ // follow-up switches it to `fetch(new Request(url, init))`, moving the body+ // onto the Request. Read whichever shape is present so this works either way.+ const [first, init] = agentSpy.mock.lastCall ?? [];+ const body =+ typeof first === "string"+ ? (init?.body as string)+ : await (first as Request).clone().text();+ return JSON.parse(body);};// Common mock response fixturesdiff --git a/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.unit.spec.tsx b/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.unit.spec.tsxindex 977675d0f50..ece6088f459 100644--- a/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.unit.spec.tsx+++ b/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.unit.spec.tsx@@ -713,19 +713,12 @@ describe("DataModelV1", () => {screen.getByRole("button", { name: "Re-scan table" }),);- const calls = fetchMock.callHistory.calls(- `path:/api/table/${ORDERS_TABLE.id}/rescan_values`,- {- method: "POST",- },- );-await waitFor(() => {- expect(calls.length).toBeGreaterThan(0);+ const path = `path:/api/table/${ORDERS_TABLE.id}/rescan_values`;+ expect(+ fetchMock.callHistory.called(path, { method: "POST" }),+ ).toBeTruthy();});-- const lastCall = calls[calls.length - 1];- expect(JSON.parse(lastCall.options.body as string)).toEqual({});});it("should allow to discard field values", async () => {@@ -744,19 +737,12 @@ describe("DataModelV1", () => {}),);- const calls = fetchMock.callHistory.calls(- `path:/api/table/${ORDERS_TABLE.id}/discard_values`,- {- method: "POST",- },- );-await waitFor(() => {- expect(calls.length).toBeGreaterThan(0);+ const path = `path:/api/table/${ORDERS_TABLE.id}/discard_values`;+ expect(+ fetchMock.callHistory.called(path, { method: "POST" }),+ ).toBeTruthy();});-- const lastCall = calls[calls.length - 1];- expect(JSON.parse(lastCall.options.body as string)).toEqual({});});});diff --git a/frontend/src/metabase/redux/uploads.unit.spec.js b/frontend/src/metabase/redux/uploads.unit.spec.jsindex 01e9e413f4e..91645c50858 100644--- a/frontend/src/metabase/redux/uploads.unit.spec.js+++ b/frontend/src/metabase/redux/uploads.unit.spec.js@@ -22,7 +22,10 @@ const mockUploadCSV = (valid = true) => {fetchMock.post("path:/api/upload/csv",valid- ? "3"+ ? new Response(JSON.stringify(3), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }): {throws: { data: { message: "It's dead Jim" } },},@@ -33,7 +36,10 @@ const mockAppendCSV = (valid = true) => {fetchMock.post("glob:*/api/table/*/append-csv",valid- ? "3"+ ? new Response(JSON.stringify(3), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }): {throws: { data: { message: "It's dead Jim" } },},@@ -44,7 +50,10 @@ const mockReplaceCSV = (valid = true) => {fetchMock.post("glob:*/api/table/*/replace-csv",valid- ? "3"+ ? new Response(JSON.stringify(3), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }): {throws: { data: { message: "It's dead Jim" } },},diff --git a/frontend/test/__support__/server-mocks/dataset.ts b/frontend/test/__support__/server-mocks/dataset.tsindex 6aba4edb25b..136ff84010e 100644--- a/frontend/test/__support__/server-mocks/dataset.ts+++ b/frontend/test/__support__/server-mocks/dataset.ts@@ -39,7 +39,10 @@ export function setupCardDataset(fetchMock.post("path:/api/dataset",- new Response(JSON.stringify(createMockDataset(dataset)), { status }),+ new Response(JSON.stringify(createMockDataset(dataset)), {+ status,+ headers: { "Content-Type": "application/json" },+ }),{name: "dataset-post",},diff --git a/frontend/test/__support__/server-mocks/table.ts b/frontend/test/__support__/server-mocks/table.tsindex 00a4512daca..147fdf8fa50 100644--- a/frontend/test/__support__/server-mocks/table.ts+++ b/frontend/test/__support__/server-mocks/table.ts@@ -113,6 +113,7 @@ export function setupDeleteUploadManagementDeleteEndpoint(failureId?: number) {: // fetch-mock doesn't like returning true directlynew Response(JSON.stringify(true), {status: 200,+ headers: { "Content-Type": "application/json" },});});}diff --git a/frontend/test/__support__/server-mocks/user-key-value.ts b/frontend/test/__support__/server-mocks/user-key-value.tsindex c2eca3ebbe0..46bc94618a4 100644--- a/frontend/test/__support__/server-mocks/user-key-value.ts+++ b/frontend/test/__support__/server-mocks/user-key-value.ts@@ -16,6 +16,7 @@ export const setupUserKeyValueEndpoints = ({`path:/api/user-key-value/namespace/${namespace}/key/${key}`,new Response(JSON.stringify(value), {status: 200,+ headers: { "Content-Type": "application/json" },}),{name: getName,