Skip to content

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

Reuse dashboard save response and make dashboard e2e saves deterministic (#76507)

Romeo Van Snick34296d19750b
diff --git a/e2e/support/helpers/e2e-dashboard-helpers.ts b/e2e/support/helpers/e2e-dashboard-helpers.ts
index 26eedae39ce..ae429581ead 100644
--- a/e2e/support/helpers/e2e-dashboard-helpers.ts
+++ b/e2e/support/helpers/e2e-dashboard-helpers.ts
@@ -58,6 +58,89 @@ export function getDashboardCardMenu(index = 0) {
return getDashboardCard(index).findByTestId("dashcard-menu");
}
+/**
+ * Wait until every dashcard in the grid has finished loading its results.
+ *
+ * Prefer this over counting card-query requests: how many queries fire after a
+ * save, filter change, or navigation is not deterministic (results can be served
+ * from cache), but the absence of loading indicators is a stable signal that the
+ * grid has settled. Pass `count` to also assert the expected number of cards is
+ * present, which guards against the check passing before the cards render.
+ *
+ * Anchors on the dashboard body being visible before checking for spinners so
+ * the absence check can't pass mid-render, before any cards have started
+ * loading. The body container renders even for empty dashboards (which show no
+ * grid), so this stays a no-op rather than hanging when there is no grid.
+ */
+export function waitForDashcardsToLoad({ count }: { count?: number } = {}) {
+ cy.log("Wait for all dashcards to finish loading");
+ if (count != null) {
+ getDashboardCards().should("have.length", count);
+ }
+ cy.findByTestId("dashboard-parameters-and-cards")
+ .should("be.visible")
+ .findAllByTestId("loading-indicator")
+ .should("not.exist");
+ waitForGridLayoutStable();
+ waitForFilterWidgetsStable();
+}
+
+/**
+ * Wait until the grid stops reflowing. react-grid-layout repositions cards when
+ * switching between edit and view mode (the "resizing and detaching elements"
+ * the old fixed sleeps compensated for), which can move a chart out from under a
+ * coordinate-based click. No-op when there are no cards to reflow (empty or
+ * text-only dashboards).
+ */
+function waitForGridLayoutStable() {
+ waitForLayoutStable(
+ "dashcard-container",
+ () => getDashboardCards(),
+ "dashcard",
+ );
+}
+
+/**
+ * Wait until the filter widgets stop re-rendering. The parameter panel re-mounts
+ * when leaving edit mode, so interacting with a widget too soon after a save can
+ * hit a detaching element and drop the click. No-op when the dashboard has no
+ * filter widgets.
+ */
+export function waitForFilterWidgetsStable() {
+ waitForLayoutStable(
+ "parameter-widget",
+ () => cy.findAllByTestId("parameter-widget"),
+ "filter widget",
+ );
+}
+
+/**
+ * Poll the first matching element's box until it is unchanged across consecutive
+ * retries, i.e. layout has settled. There's no "layout done" event to await, and
+ * this is a no-op when nothing matches so it never hangs on absent elements.
+ */
+function waitForLayoutStable(
+ testId: string,
+ getElements: () => Cypress.Chainable<JQuery<HTMLElement>>,
+ label: string,
+) {
+ cy.get("body").then(($body) => {
+ if (!$body.find(`[data-testid="${testId}"]`).length) {
+ return;
+ }
+ let previous: string | null = null;
+ getElements()
+ .first()
+ .should(($el) => {
+ const { top, left, width, height } = $el[0].getBoundingClientRect();
+ const current = [top, left, width, height].map(Math.round).join(",");
+ const settled = current === previous;
+ previous = current;
+ expect(settled, `${label} layout settled (${current})`).to.be.true;
+ });
+ });
+}
+
export function showDashboardCardActions(index = 0) {
return getDashboardCard(index).realHover({ scrollBehavior: "bottom" });
}
@@ -81,17 +164,25 @@ export function showDashcardVisualizationSettings(index = 0) {
export function editDashboard() {
cy.findByLabelText("Edit dashboard").click();
+ // The click can be dropped while the header is still re-rendering (e.g. right
+ // after a save). The Edit button only exists in view mode, so if it's still
+ // present the click didn't take — re-click it. This can't double-toggle.
+ // Use cy.document() (not cy.get("body")) so this also works when editDashboard
+ // runs inside a cy.within() block, where cy.get is scoped to the subject.
+ cy.document().then((doc) => {
+ if (doc.querySelector('[aria-label="Edit dashboard"]')) {
+ cy.findByLabelText("Edit dashboard").click();
+ }
+ });
cy.findByText("You're editing this dashboard.");
}
export function saveDashboard({
- waitMs = 1,
awaitRequest = true,
-}: { waitMs?: number; awaitRequest?: boolean } = {}) {
+}: { awaitRequest?: boolean } = {}) {
cy.intercept("PUT", "/api/dashboard/*").as(
"saveDashboard-saveDashboardCards",
);
- cy.intercept("GET", "/api/dashboard/*").as("saveDashboard-getDashboard");
cy.intercept("GET", "/api/dashboard/*/query_metadata*").as(
"saveDashboard-getDashboardMetadata",
);
@@ -101,12 +192,13 @@ export function saveDashboard({
if (awaitRequest) {
cy.wait("@saveDashboard-saveDashboardCards");
- cy.wait("@saveDashboard-getDashboard");
cy.wait("@saveDashboard-getDashboardMetadata");
}
cy.findByTestId("edit-bar").should("not.exist");
- cy.wait(waitMs); // this is stupid but necessary to due to the dashboard resizing and detaching elements
+ // Settle on a deterministic signal (all dashcards loaded) instead of sleeping
+ // for a fixed time while the grid resizes and detaches elements.
+ waitForDashcardsToLoad();
}
export function checkFilterLabelAndValue(label: string, value: string) {
diff --git a/e2e/test/scenarios/dashboard-cards/click-behavior-reproductions.cy.spec.ts b/e2e/test/scenarios/dashboard-cards/click-behavior-reproductions.cy.spec.ts
index 03f174b8ad0..c0012e9137e 100644
--- a/e2e/test/scenarios/dashboard-cards/click-behavior-reproductions.cy.spec.ts
+++ b/e2e/test/scenarios/dashboard-cards/click-behavior-reproductions.cy.spec.ts
@@ -226,7 +226,7 @@ describe("issue 64368", () => {
cy.findByTestId("click-behavior-sidebar").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
cy.log("Set dashboard filter to contain all values");
cy.findAllByTestId("parameter-widget").click();
diff --git a/e2e/test/scenarios/dashboard-cards/click-behavior.cy.spec.js b/e2e/test/scenarios/dashboard-cards/click-behavior.cy.spec.js
index a2c1ed392d0..7da0962538d 100644
--- a/e2e/test/scenarios/dashboard-cards/click-behavior.cy.spec.js
+++ b/e2e/test/scenarios/dashboard-cards/click-behavior.cy.spec.js
@@ -248,7 +248,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
cy.get("aside").findByText("No available targets").should("exist");
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
cy.intercept(
"GET",
@@ -313,7 +313,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
addTextParameter();
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
clickLineChartPoint();
cy.findAllByTestId("parameter-widget")
@@ -369,7 +369,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
addTimeParameter();
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
clickLineChartPoint();
cy.findAllByTestId("parameter-widget")
@@ -442,7 +442,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
addTextParameter();
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
clickLineChartPoint();
cy.findAllByTestId("parameter-widget")
@@ -518,7 +518,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
.should("not.exist");
cy.button("Done").should("be.enabled").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
clickLineChartPoint();
cy.get("@targetDashboardId").then((targetDashboardId) => {
@@ -571,7 +571,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
.findByLabelText("Select a dashboard tab")
.should("not.exist");
cy.get("aside").button("Done").should("be.enabled").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
clickLineChartPoint();
cy.get("@targetDashboardId").then((targetDashboardId) => {
@@ -703,7 +703,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
addTextParameter();
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
clickLineChartPoint();
@@ -794,7 +794,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
addTextWithDefaultParameter();
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
clickLineChartPoint();
cy.findAllByTestId("parameter-widget")
@@ -860,7 +860,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
addSavedQuestionDestination();
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
cy.intercept(
"GET",
@@ -905,7 +905,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
addSavedQuestionCreatedAtParameter();
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
clickLineChartPoint();
cy.findByTestId("qb-filters-panel").should(
@@ -952,7 +952,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
addSavedQuestionQuantityParameter();
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
clickLineChartPoint();
cy.wait("@dataset");
@@ -1029,7 +1029,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
});
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
H.onNextAnchorClick((anchor) => {
expect(anchor).to.have.attr("href", URL);
@@ -1080,7 +1080,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
});
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
cy.button(DASHBOARD_FILTER_TEXT.name).click();
H.dashboardParametersPopover().within(() => {
@@ -1142,7 +1142,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
addNumericParameter();
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
clickLineChartPoint();
cy.findAllByTestId("parameter-widget")
@@ -1199,7 +1199,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
.should("contain.text", COUNT_COLUMN_NAME);
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
H.editDashboard();
cy.findByTestId("edit-dashboard-parameters-widget-container")
@@ -1207,7 +1207,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
.click();
cy.get("aside").button("Remove").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
clickLineChartPoint();
cy.findAllByTestId("parameter-widget")
@@ -1262,7 +1262,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
addTimeParameter();
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
clickLineChartPoint();
cy.findAllByTestId("parameter-widget")
@@ -1381,7 +1381,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
})();
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 500 });
+ H.saveDashboard();
(function testDashboardDestinationClick() {
cy.log("it handles 'Count' column click");
@@ -1505,7 +1505,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
.should("have.text", "1 column has custom behavior");
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
getTableCell(COLUMN_INDEX.COUNT)
.should("have.text", String(POINT_COUNT))
@@ -1623,7 +1623,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
.should("have.text", "2 columns have custom behavior");
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
(function testUpdateDashboardFiltersClick() {
cy.log("it handles 'Count' column click");
@@ -2158,7 +2158,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
customizeLinkText(`Created at: {{${CREATED_AT_COLUMN_ID}}} - {{count}}`);
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
H.getDashboardCard()
.findAllByText("Created at: May 2025 - 1")
@@ -2322,7 +2322,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
H.popover().findByText(FILTER_MAPPING_COLUMN).click();
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
// test click behavior routing to same dashboard, different tab
getTableCell(1).click();
@@ -2709,7 +2709,7 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {
cy.get("aside").button("Done").click();
H.saveDashboard({ awaitRequest: false });
- cy.wait("@saveDashboard-getDashboard");
+ cy.wait("@saveDashboard-getDashboardMetadata");
clickLineChartPoint();
@@ -2927,10 +2927,7 @@ const testChangingBackToDefaultBehavior = () => {
cy.get("aside").findByText("Open the Metabase drill-through menu").click();
cy.get("aside").button("Done").click();
- H.saveDashboard({ waitMs: 250 });
- // this is necessary due to query params being reset after saving dashboard
- // with filter applied, which causes dashcard to be refetched
- cy.wait(1);
+ H.saveDashboard();
clickLineChartPoint();
assertDrillThroughMenuOpen();
diff --git a/e2e/test/scenarios/dashboard-filters-2/dashboard-filters-3-stage.cy.spec.ts b/e2e/test/scenarios/dashboard-filters-2/dashboard-filters-3-stage.cy.spec.ts
index 01162caad62..9c904bcb11d 100644
--- a/e2e/test/scenarios/dashboard-filters-2/dashboard-filters-3-stage.cy.spec.ts
+++ b/e2e/test/scenarios/dashboard-filters-2/dashboard-filters-3-stage.cy.spec.ts
@@ -412,7 +412,7 @@ describe("scenarios > dashboard > filters > query stages", () => {
.click();
});
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
H.filterWidget().eq(0).click();
H.popover().within(() => {
diff --git a/e2e/test/scenarios/dashboard-filters-2/shared/dashboard-filters-query-stages.ts b/e2e/test/scenarios/dashboard-filters-2/shared/dashboard-filters-query-stages.ts
index 77c20d1cd4b..7775e8c1d57 100644
--- a/e2e/test/scenarios/dashboard-filters-2/shared/dashboard-filters-query-stages.ts
+++ b/e2e/test/scenarios/dashboard-filters-2/shared/dashboard-filters-query-stages.ts
@@ -404,7 +404,7 @@ export function setup1stStageExplicitJoinFilter() {
getPopoverItem("Reviewer", 0).click();
});
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
}
export function apply1stStageExplicitJoinFilter() {
@@ -434,7 +434,7 @@ export function setup1stStageImplicitJoinFromSourceFilter() {
getPopoverItem("Price", 0).click();
});
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
H.filterWidget().eq(0).click();
H.popover().within(() => {
@@ -460,7 +460,7 @@ export function setup1stStageImplicitJoinFromJoinFilter() {
getPopoverItem("Category", 1).click();
});
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
H.filterWidget().eq(0).click();
H.popover().within(() => {
@@ -487,7 +487,7 @@ export function setup1stStageCustomColumnFilter() {
getPopoverItem("Net").click();
});
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
H.filterWidget().eq(0).click();
H.popover().within(() => {
@@ -515,7 +515,7 @@ export function setup1stStageAggregationFilter() {
getPopoverItem("Count").scrollIntoView().click();
});
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
H.filterWidget().eq(0).click();
H.popover().within(() => {
@@ -541,7 +541,7 @@ export function setup1stStageBreakoutFilter() {
getPopoverItem("Category", 1).scrollIntoView().click();
});
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
H.filterWidget().eq(0).click();
H.popover().within(() => {
@@ -566,7 +566,7 @@ export function setup2ndStageExplicitJoinFilter() {
getPopoverItem("Reviewer", 1).click();
});
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
H.filterWidget().eq(0).click();
H.popover()
@@ -595,7 +595,7 @@ export function setup2ndStageCustomColumnFilter() {
getPopoverItem("5 * Count").scrollIntoView().click();
});
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
}
export function apply2ndStageCustomColumnFilter() {
@@ -634,7 +634,7 @@ export function setup2ndStageAggregationFilter() {
getPopoverItem("Count").click();
});
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
}
export function apply2ndStageAggregationFilter() {
@@ -674,7 +674,7 @@ export function setup2ndStageBreakoutFilter() {
getPopoverItem("Product → Category").scrollIntoView().click();
});
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
}
function closeToasts() {
@@ -721,7 +721,7 @@ export function clickAway() {
export function goBackToDashboard() {
cy.findByLabelText("Back to Test Dashboard").click();
- cy.wait("@getDashboard");
+ cy.findByTestId("dashboard-grid").should("be.visible");
}
export function getDashboardId(): Cypress.Chainable<number> {
diff --git a/e2e/test/scenarios/dashboard-filters/temporal-unit-parameters.cy.spec.js b/e2e/test/scenarios/dashboard-filters/temporal-unit-parameters.cy.spec.js
index 9f20eef1838..dd72769b6db 100644
--- a/e2e/test/scenarios/dashboard-filters/temporal-unit-parameters.cy.spec.js
+++ b/e2e/test/scenarios/dashboard-filters/temporal-unit-parameters.cy.spec.js
@@ -531,7 +531,7 @@ describe("scenarios > dashboard > temporal unit parameters", () => {
cy.findByText(parameterDetails.name).click();
});
H.popover().findByText("UNIT").click();
- H.saveDashboard({ waitMs: 250 });
+ H.saveDashboard();
cy.log("verify click behavior with a valid temporal unit");
diff --git a/e2e/test/scenarios/dashboard/dashboard-reproductions.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard-reproductions.cy.spec.js
index c3675398357..580cbcac622 100644
--- a/e2e/test/scenarios/dashboard/dashboard-reproductions.cy.spec.js
+++ b/e2e/test/scenarios/dashboard/dashboard-reproductions.cy.spec.js
@@ -389,7 +389,7 @@ describe("issue 16559", () => {
H.sidebar().findByText("Orders, Count").click();
cy.wait("@cardQuery");
cy.button("Save").click();
- cy.wait(["@saveDashboard", "@loadDashboard"]);
+ cy.wait("@saveDashboard");
H.openDashboardInfoSidebar().within(() => {
cy.contains("button", "History").click();
diff --git a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
index 5a08091645a..f95c325e82a 100644
--- a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
+++ b/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
@@ -23,7 +23,6 @@ const { ORDERS, ORDERS_ID, PRODUCTS, PEOPLE, PEOPLE_ID } = SAMPLE_DATABASE;
// and then immediately editing it again. After saving,
// we exit the edit mode and that can happen after
// `H.editDashboard` is called for some reason
-const DASHBOARD_SAVE_WAIT_TIME = 450;
describe("scenarios > dashboard", () => {
beforeEach(() => {
@@ -1211,7 +1210,7 @@ describe("scenarios > dashboard", () => {
.eq(0);
dragOnXAxis(card(), 100);
assertPreventLeave();
- H.saveDashboard({ waitMs: DASHBOARD_SAVE_WAIT_TIME });
+ H.saveDashboard();
// remove
H.editDashboard();
@@ -1259,7 +1258,7 @@ describe("scenarios > dashboard", () => {
// can be a side effect
cy.url().should("include", "tab-1");
assertPreventLeave();
- H.saveDashboard({ waitMs: DASHBOARD_SAVE_WAIT_TIME });
+ H.saveDashboard();
// rename tab
H.editDashboard();
diff --git a/e2e/test/scenarios/dashboard/visualizer/basics.cy.spec.ts b/e2e/test/scenarios/dashboard/visualizer/basics.cy.spec.ts
index 24a1d0fff96..a0e4eef47fe 100644
--- a/e2e/test/scenarios/dashboard/visualizer/basics.cy.spec.ts
+++ b/e2e/test/scenarios/dashboard/visualizer/basics.cy.spec.ts
@@ -24,7 +24,6 @@ const DASHCARD_QUERY_WAIT_TIME = 1000;
// and then immediately editing it again. After saving,
// we exit the edit mode and that can happen after
// `H.editDashboard` is called for some reason
-const DASHBOARD_SAVE_WAIT_TIME = 450;
describe("scenarios > dashboard > visualizer > basics", () => {
beforeEach(() => {
@@ -286,7 +285,7 @@ describe("scenarios > dashboard > visualizer > basics", () => {
});
H.saveDashcardVisualizerModal();
cy.wait(DASHCARD_QUERY_WAIT_TIME);
- H.saveDashboard({ waitMs: DASHBOARD_SAVE_WAIT_TIME });
+ H.saveDashboard();
H.getDashboardCard(2).realHover();
H.getDashboardCardMenu(2).click();
@@ -344,7 +343,7 @@ describe("scenarios > dashboard > visualizer > basics", () => {
H.assertDashboardCardTitle(1, "");
// Save the dashboard
- H.saveDashboard({ waitMs: DASHBOARD_SAVE_WAIT_TIME });
+ H.saveDashboard();
// Check that the card titles are still good
H.assertDashboardCardTitle(0, "Renamed chart");
@@ -467,7 +466,7 @@ describe("scenarios > dashboard > visualizer > basics", () => {
H.saveDashcardVisualizerModal();
- H.saveDashboard({ waitMs: DASHBOARD_SAVE_WAIT_TIME });
+ H.saveDashboard();
H.getDashboardCard(0).within(() => {
cy.findByText("Original Question Title").should("exist");
@@ -500,7 +499,7 @@ describe("scenarios > dashboard > visualizer > basics", () => {
H.saveDashcardVisualizerModal();
- H.saveDashboard({ waitMs: DASHBOARD_SAVE_WAIT_TIME });
+ H.saveDashboard();
H.getDashboardCard(0).within(() => {
cy.findByText("Updated Title").should("exist");
@@ -716,7 +715,7 @@ describe("scenarios > dashboard > visualizer > basics", () => {
cy.findByText(ORDERS_COUNT_BY_CREATED_AT.name).should("exist");
cy.findByText("Created At: Month").should("exist");
});
- H.saveDashboard({ waitMs: DASHBOARD_SAVE_WAIT_TIME });
+ H.saveDashboard();
H.editDashboard();
H.showDashcardVisualizerModal(0);
diff --git a/e2e/test/scenarios/filters-reproductions/dashboard-filters-reproductions-1.cy.spec.js b/e2e/test/scenarios/filters-reproductions/dashboard-filters-reproductions-1.cy.spec.js
index 2d1496320b7..a46bf164a3e 100644
--- a/e2e/test/scenarios/filters-reproductions/dashboard-filters-reproductions-1.cy.spec.js
+++ b/e2e/test/scenarios/filters-reproductions/dashboard-filters-reproductions-1.cy.spec.js
@@ -203,18 +203,12 @@ describe("issue 8030 + 32444", () => {
// Saving exits edit mode and reloads the dashcards in view mode. How
// many post-save card queries fire is not deterministic (cached results
// may be reused), so rather than counting them we wait for the reload to
- // start and then for both cards to finish loading before re-aliasing
- // below. Otherwise a still in-flight post-save query — slow under network
- // throttling — would be captured by the new intercept on the same URL
- // and miscounted as a filter-triggered query (the test then sees 2,
- // not 1).
+ // start and then for both cards to settle before re-aliasing below.
+ // Otherwise a still in-flight post-save query would be captured by the
+ // new intercept on the same URL and miscounted as a filter-triggered
+ // query (the test then sees 2, not 1).
cy.wait("@getCardQuery");
- H.getDashboardCard(0)
- .findByTestId("loading-indicator")
- .should("not.exist");
- H.getDashboardCard(1)
- .findByTestId("loading-indicator")
- .should("not.exist");
+ H.waitForDashcardsToLoad({ count: 2 });
// Reset the intercept after save so we only count filter-triggered queries.
cy.intercept(
diff --git a/e2e/test/scenarios/visualizations-charts/visualizations-charts-reproductions.cy.spec.js b/e2e/test/scenarios/visualizations-charts/visualizations-charts-reproductions.cy.spec.js
index 0e2711b22bb..a3cf524084b 100644
--- a/e2e/test/scenarios/visualizations-charts/visualizations-charts-reproductions.cy.spec.js
+++ b/e2e/test/scenarios/visualizations-charts/visualizations-charts-reproductions.cy.spec.js
@@ -656,7 +656,6 @@ describe("issue 21665", () => {
});
H.saveDashboard();
- cy.wait("@getDashboard");
});
it("multi-series cards shouldnt cause frontend to reload (metabase#21665)", () => {
@@ -666,7 +665,8 @@ describe("issue 21665", () => {
H.visitDashboard("@dashboardId");
- cy.get("@dashboardLoaded").should("have.callCount", 3);
+ // The dashboard loads twice: once on the initial visit, once on re-visit.
+ cy.get("@dashboardLoaded").should("have.callCount", 2);
cy.findByTestId("dashcard")
.findByText(
"Some columns are missing, this card might not render correctly.",
diff --git a/frontend/src/metabase/dashboard/actions/data-fetching.ts b/frontend/src/metabase/dashboard/actions/data-fetching.ts
index 82455d45ffd..9ed38056a04 100644
--- a/frontend/src/metabase/dashboard/actions/data-fetching.ts
+++ b/frontend/src/metabase/dashboard/actions/data-fetching.ts
@@ -54,6 +54,7 @@ import type {
Card,
CardId,
DashCardId,
+ Dashboard,
DashboardCard,
DashboardId,
Dataset,
@@ -673,11 +674,22 @@ export const fetchDashboard = createAsyncThunk(
{
dashId,
queryParams,
- options: { preserveParameters = false, clearCache = true } = {},
+ options: {
+ preserveParameters = false,
+ clearCache = true,
+ prefetchedDashboard,
+ } = {},
}: {
dashId: DashboardId;
queryParams: ParameterValuesMap;
- options?: { preserveParameters?: boolean; clearCache?: boolean };
+ options?: {
+ preserveParameters?: boolean;
+ clearCache?: boolean;
+ // A fully-hydrated dashboard already in hand (e.g. the response from
+ // saving). When provided, skip the GET and use it directly so we don't
+ // re-fetch what the server just returned.
+ prefetchedDashboard?: Dashboard;
+ };
},
{ getState, dispatch, rejectWithValue },
) => {
@@ -773,6 +785,17 @@ export const fetchDashboard = createAsyncThunk(
// @ts-expect-error
result = expandInlineDashboard(dashId);
dashId = result.id = String(dashId);
+ } else if (prefetchedDashboard) {
+ // The dashboard was just handed to us (e.g. a save response), so skip
+ // the GET. We still warm the query metadata cache exactly as the normal
+ // path does (served from cache via forceRefetch: false).
+ await runRtkEndpoint(
+ { id: dashId, dashboard_load_id: dashboardLoadId },
+ dispatch,
+ dashboardApi.endpoints.getDashboardQueryMetadata,
+ { forceRefetch: false },
+ );
+ result = prefetchedDashboard;
} else {
const [response] = await Promise.all([
runRtkEndpoint(
diff --git a/frontend/src/metabase/dashboard/actions/data-fetching.unit.spec.ts b/frontend/src/metabase/dashboard/actions/data-fetching.unit.spec.ts
index 2769585d6b6..27f2da56a2c 100644
--- a/frontend/src/metabase/dashboard/actions/data-fetching.unit.spec.ts
+++ b/frontend/src/metabase/dashboard/actions/data-fetching.unit.spec.ts
@@ -305,6 +305,31 @@ describe("fetchDashboard", () => {
expect(result.type).toBe("metabase/dashboard/FETCH_DASHBOARD/fulfilled");
});
+
+ it("uses a prefetched dashboard instead of re-fetching it", async () => {
+ const dashboard = createMockDashboard({ id: 1, name: "Prefetched" });
+
+ // setup() mocks GET /api/dashboard/1, so reaching it here would succeed —
+ // the assertion below proves the prefetched path skips it entirely.
+ const store = setup({ dashboards: [dashboard] });
+
+ const result = await store.dispatch(
+ fetchDashboard({
+ dashId: 1,
+ queryParams: {},
+ options: { prefetchedDashboard: dashboard },
+ }),
+ );
+
+ expect(result.type).toBe("metabase/dashboard/FETCH_DASHBOARD/fulfilled");
+ expect(result.payload).toMatchObject({
+ dashboardId: 1,
+ dashboard: { id: 1, name: "Prefetched" },
+ });
+ expect(
+ fetchMock.callHistory.called("path:/api/dashboard/1", { method: "GET" }),
+ ).toBe(false);
+ });
});
/**
diff --git a/frontend/src/metabase/dashboard/actions/save.ts b/frontend/src/metabase/dashboard/actions/save.ts
index 8e2b4e3293d..809a6cfc8b5 100644
--- a/frontend/src/metabase/dashboard/actions/save.ts
+++ b/frontend/src/metabase/dashboard/actions/save.ts
@@ -191,7 +191,7 @@ export const updateDashboardAndCards = createThunkAction(
.filter((tab) => !tab.isRemoved)
.map(({ id, name }) => ({ id, name }));
- await runRtkEndpoint(
+ const updatedDashboard = await runRtkEndpoint(
{
...dashboard,
dashcards: dashcardsToUpdate,
@@ -212,22 +212,20 @@ export const updateDashboardAndCards = createThunkAction(
dispatch(setEditingDashboard(null));
- // make sure that we've fully cleared out any dirty state from editing (this is overkill, but simple)
- //
- // UPD 16.09.2024
- // This code is a source of race condition on slow network.
- // it fetches a dashboard without parameters and if `fetchDashboardCardData` from the lines below is slow
- // the dashboard itself is re-rendered and re-fetches data again without parameters, so later on
- // dashboard component re-fetches data and cancels correct query with parameters
- // e.g. `should pass a temporal unit with 'update dashboard filter' click behavior` from temporal-unit-parameters.cy.spec.js
- // with 3g simulation is an example of such race condition
+ // Reset the dashboard state from the save response instead of re-fetching
+ // it. Re-using the just-returned dashboard avoids an extra round-trip and
+ // the race condition where a parameter-less GET could cancel the
+ // parameterized card-data fetch below on slow networks.
await dispatch(
fetchDashboard({
dashId: dashboard.id,
queryParams: {},
- options: { preserveParameters: false },
+ options: {
+ preserveParameters: false,
+ prefetchedDashboard: updatedDashboard,
+ },
}),
- ); // disable using query parameters when saving
+ );
// There might have been changes to dashboard card-filter wiring,
// which require re-fetching card data (issue #35503). We expect
diff --git a/frontend/src/metabase/dashboard/actions/save.unit.spec.ts b/frontend/src/metabase/dashboard/actions/save.unit.spec.ts
new file mode 100644
index 00000000000..7a479359399
--- /dev/null
+++ b/frontend/src/metabase/dashboard/actions/save.unit.spec.ts
@@ -0,0 +1,121 @@
+import fetchMock from "fetch-mock";
+
+import { getStore } from "__support__/entities-store";
+import { setupDashboardQueryMetadataEndpoint } from "__support__/server-mocks";
+import { createMockEntitiesState } from "__support__/store";
+import { Api } from "metabase/api";
+import {
+ createMockDashboardState,
+ createMockSettingsState,
+ createMockStoreDashboard,
+} from "metabase/redux/store/mocks";
+import {
+ createMockCard,
+ createMockDashboard,
+ createMockDashboardCard,
+ createMockDashboardQueryMetadata,
+} from "metabase-types/api/mocks";
+import { createSampleDatabase } from "metabase-types/api/mocks/presets";
+
+import { dashboardReducers } from "../reducers";
+
+import { updateDashboardAndCards } from "./save";
+
+const NEW_DASHCARD_TEMP_ID = -1;
+const NEW_DASHCARD_REAL_ID = 99;
+const CARD_ID = 1;
+
+function setup() {
+ const database = createSampleDatabase();
+
+ // The card the user added during editing only exists locally, with a
+ // temporary negative id. The save response assigns it a real id.
+ const tempDashcard = createMockDashboardCard({
+ id: NEW_DASHCARD_TEMP_ID,
+ card_id: CARD_ID,
+ dashboard_id: 1,
+ card: createMockCard({ id: CARD_ID }),
+ });
+
+ const savedDashboard = createMockDashboard({
+ id: 1,
+ name: "Edited",
+ dashcards: [
+ createMockDashboardCard({
+ id: NEW_DASHCARD_REAL_ID,
+ card_id: CARD_ID,
+ dashboard_id: 1,
+ card: createMockCard({ id: CARD_ID }),
+ }),
+ ],
+ });
+
+ const state = {
+ dashboard: createMockDashboardState({
+ dashboardId: 1,
+ dashboards: {
+ "1": createMockStoreDashboard({
+ id: 1,
+ name: "Edited",
+ dashcards: [NEW_DASHCARD_TEMP_ID],
+ }),
+ },
+ dashcards: {
+ [NEW_DASHCARD_TEMP_ID]: tempDashcard,
+ },
+ // Differs from the current dashboard (no dashcards), so the save proceeds.
+ editingDashboard: createMockDashboard({
+ id: 1,
+ name: "Original",
+ dashcards: [],
+ }),
+ }),
+ entities: createMockEntitiesState({ databases: [database] }),
+ settings: createMockSettingsState(),
+ };
+
+ const store = getStore(
+ {
+ [Api.reducerPath]: Api.reducer,
+ dashboard: dashboardReducers,
+ entities: (state = {}) => state,
+ settings: (state = {}) => state,
+ },
+ state,
+ [Api.middleware],
+ );
+
+ fetchMock.put("path:/api/dashboard/1", savedDashboard);
+ setupDashboardQueryMetadataEndpoint(
+ savedDashboard,
+ createMockDashboardQueryMetadata({ databases: [database] }),
+ );
+ fetchMock.post(
+ `path:/api/dashboard/1/dashcard/${NEW_DASHCARD_REAL_ID}/card/${CARD_ID}/query`,
+ { data: [] },
+ );
+
+ return { store };
+}
+
+describe("updateDashboardAndCards", () => {
+ it("refreshes dashboard state from the save response without re-fetching", async () => {
+ const { store } = setup();
+
+ await store.dispatch(updateDashboardAndCards());
+
+ const { dashboards, dashcards } = store.getState().dashboard;
+
+ // The temporary dashcard id was replaced by the real one from the response.
+ expect(dashboards["1"]?.dashcards).toEqual([NEW_DASHCARD_REAL_ID]);
+ expect(dashcards[NEW_DASHCARD_REAL_ID]).toBeDefined();
+
+ expect(
+ fetchMock.callHistory.called("path:/api/dashboard/1", { method: "PUT" }),
+ ).toBe(true);
+ // The state is rebuilt from the PUT response, so no GET is issued.
+ expect(
+ fetchMock.callHistory.called("path:/api/dashboard/1", { method: "GET" }),
+ ).toBe(false);
+ });
+});