Skip to content

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

Fix metrics explorer e2e flakes (#75564)

Andersond07294ea214a
diff --git a/e2e/support/config.js b/e2e/support/config.js
index d4e0fc3745c..0cebabf6b35 100644
--- a/e2e/support/config.js
+++ b/e2e/support/config.js
@@ -126,9 +126,11 @@ const defaultConfig = {
********************************************************************/
on("before:browser:launch", (browser = {}, launchOptions) => {
- // Open dev tools in Chrome by default
if (browser.name === "chrome" || browser.name === "chromium") {
- launchOptions.args.push("--auto-open-devtools-for-tabs");
+ // Open dev tools in Chrome by default when in headed mode
+ if (browser.isHeaded) {
+ launchOptions.args.push("--auto-open-devtools-for-tabs");
+ }
launchOptions.args.push("--blink-settings=preferredColorScheme=1");
}
diff --git a/e2e/support/helpers/e2e-metrics-viewer-helpers.ts b/e2e/support/helpers/e2e-metrics-viewer-helpers.ts
index 36283e1cbbe..3c22b913259 100644
--- a/e2e/support/helpers/e2e-metrics-viewer-helpers.ts
+++ b/e2e/support/helpers/e2e-metrics-viewer-helpers.ts
@@ -11,7 +11,6 @@ export const MetricsViewer = {
cy.get(
"[data-testid='metrics-viewer-pill'], [data-testid='metrics-viewer-expression-pill']",
),
- searchResults: () => cy.findByTestId("mini-picker"),
breakoutLegend: () => cy.findByTestId("metrics-viewer-breakout-legend"),
getFilterButton: () => cy.findByRole("button", { name: /Filter/ }),
getAllFilterPills: () => cy.findAllByTestId("metrics-viewer-filter-pill"),
diff --git a/e2e/support/helpers/e2e-visual-tests-helpers.js b/e2e/support/helpers/e2e-visual-tests-helpers.js
index 44adeea480f..f45a949a94d 100644
--- a/e2e/support/helpers/e2e-visual-tests-helpers.js
+++ b/e2e/support/helpers/e2e-visual-tests-helpers.js
@@ -11,11 +11,11 @@ import {
import { isFixedPositionElementVisible } from "./e2e-element-visibility-helpers";
export function ensureChartIsActive() {
- cy.findByTestId("debounced-frame-root").should(
- "not.have.css",
- "pointer-events",
- "none",
- );
+ cy.findAllByTestId("debounced-frame-root").each(($el) => {
+ cy.wrap($el).should("not.have.css", "pointer-events", "none");
+ });
+ cy.wait(500); // Let DebouncedFrame transitions settle
+ ensureEchartsContainerHasSvg();
}
export function echartsContainer() {
@@ -92,10 +92,13 @@ export function chartPathsWithFillColors(colors) {
const CIRCLE_PATH = "M1 0A1 1 0 1 1 1 -0.0001";
const DIAMOND_PATH = "M0 -1L1 0L0 1L-1 0Z";
+
+export function cartesianChartCircles() {
+ return echartsContainer().find(`path[d="${CIRCLE_PATH}"]`);
+}
+
export function cartesianChartCircle() {
- return echartsContainer()
- .find(`path[d="${CIRCLE_PATH}"]`)
- .should("be.visible");
+ return cartesianChartCircles().should("be.visible");
}
export function cartesianChartCircleWithColor(color) {
@@ -285,6 +288,6 @@ export const BoxPlot = {
export function applyBrush(left, right) {
echartsContainer()
.trigger("mousedown", left, 100)
- .trigger("mousemove", left, 100)
+ .trigger("mousemove", right, 100)
.trigger("mouseup", right, 100);
}
diff --git a/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts b/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts
index f49c4f31f9e..5a0e4ec72fa 100644
--- a/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts
+++ b/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts
@@ -9,7 +9,6 @@ import {
ORDERS_MODEL_ID,
} from "e2e/support/cypress_sample_instance_data";
import type { StructuredQuestionDetails } from "e2e/support/helpers";
-import { createLibraryWithTable } from "e2e/support/test-library-data";
const { ORDERS_ID, ORDERS, PRODUCTS_ID, PRODUCTS, ACCOUNTS_ID, FEEDBACK_ID } =
SAMPLE_DATABASE;
@@ -127,49 +126,54 @@ const ALL_MODELS = [
];
const SNAPSHOT_NAME = "metrics-explorer-snapshot";
-
-const getMetricSearchResultMatcher = (name: string) => {
- if (name === "Count of orders") {
- return /Count of orders(?!\s+over\s+time)/;
- }
-
- return name;
-};
+const INPUT_PLACEHOLDER_TEXT = "Search for metrics...";
// ============================================================================
// Test Helpers
// ============================================================================
-const selectMetricSearchResult = (name: string) => {
- H.MetricsViewer.searchResults()
- .contains('[role="menuitem"]', getMetricSearchResultMatcher(name))
- .click();
-};
-
-/**
- * Add a metric or measure to the explorer via the search panel
- */
-const addMetric = (name: string, runExpression: boolean = true) => {
- // for some reason `type` clicks in the middle of the input first
- H.MetricsViewer.searchInput().type(`{end}, ${name}`, {
- waitForAnimations: true,
- });
- selectMetricSearchResult(name);
-
- if (runExpression) {
- runFormula();
+type InputToken =
+ | { nameOrPath: string | string[] }
+ | "+"
+ | "-"
+ | "*"
+ | "/"
+ | ",";
+
+const selectEntityPickerItem = (path: string | string[]) => {
+ if (typeof path === "string") {
+ // Escape special regex characters and match exact text
+ const escapedPath = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ H.miniPicker()
+ .findAllByRole("menuitem")
+ .contains(new RegExp(`^${escapedPath}$`))
+ .click();
+ } else {
+ H.miniPickerBrowseAll().click();
+ H.pickEntity({ path });
}
};
-const addMetricMath = (
- expression: ({ metricName: string } | string)[],
- runExpression: boolean = true,
+
+const addMetricInputSequence = (
+ sequence: InputToken[],
+ {
+ runExpression = true,
+ clearInput = false,
+ skipRunCompletionWait = false,
+ } = {},
) => {
H.MetricsViewer.searchInput().then(($input) => {
- const text = $input.text().trim();
+ if (clearInput) {
+ cy.wrap($input).clear({ waitForAnimations: true });
+ return;
+ }
+
+ const currentText = $input.text().trim();
+
if (
- text.length > 0 &&
- !/[,+*/(-]$/.test(text) &&
- (typeof expression[0] !== "string" || !/[,+*/(-]$/.test(expression[0]))
+ currentText !== INPUT_PLACEHOLDER_TEXT &&
+ currentText !== "" &&
+ typeof sequence[0] !== "string"
) {
cy.wrap($input).type("{end}, ", {
waitForAnimations: true,
@@ -177,25 +181,57 @@ const addMetricMath = (
}
});
- for (const item of expression) {
- if (typeof item === "string") {
- const text = /^[+*/-]$/.test(item) ? ` ${item} ` : item;
- H.MetricsViewer.searchInput().type(`{end}${text}`, {
+ for (let i = 0; i < sequence.length; i++) {
+ const item = sequence[i];
+
+ if (typeof item !== "object") {
+ H.MetricsViewer.searchInput().type(`{end}${item}`, {
waitForAnimations: true,
});
} else {
- H.MetricsViewer.searchInput().type(`{end}${item.metricName}`, {
- waitForAnimations: true,
- });
- selectMetricSearchResult(item.metricName);
+ selectEntityPickerItem(item.nameOrPath);
}
}
+
if (runExpression) {
runFormula();
+ if (!skipRunCompletionWait) {
+ // It is expected that the elements below do not exist after the expression ran successfully
+ cy.findByTestId("metrics-viewer-search-input").should("not.exist");
+ cy.findByTestId("run-expression-button").should("not.exist");
+ cy.findByTestId("loading-indicator").should("not.exist");
+ }
}
};
+/**
+ * Add a metric or measure to the explorer via the search panel
+ */
+const addMetric = (
+ nameOrPath: string | string[],
+ {
+ runExpression = true,
+ clearInput = false,
+ skipRunCompletionWait = false,
+ } = {},
+) => {
+ addMetricInputSequence([{ nameOrPath }], {
+ runExpression,
+ clearInput,
+ skipRunCompletionWait,
+ });
+};
+
const runFormula = () => {
+ cy.log("Make sure mini picker is closed before clicking Run");
+ H.MetricsViewer.runButton().should("be.visible");
+ cy.get("body").then(($body) => {
+ if ($body.find('[data-testid="mini-picker"]').length > 0) {
+ cy.realPress("Escape");
+ cy.get('[data-testid="mini-picker"]').should("not.exist");
+ }
+ });
+
H.MetricsViewer.runButton().should("not.be.disabled").click();
};
@@ -208,12 +244,12 @@ const runFormulaWithKeyboard = () => {
* Select a breakout dimension
*/
const selectBreakout = (
- cardname: string,
+ cardName: string,
dimensionName: string,
index = 0,
binning?: string,
) => {
- H.MetricsViewer.searchBarPills().contains(cardname).click();
+ H.MetricsViewer.searchBarPills().contains(cardName).click();
H.popover().findByText("Add a series breakout").click();
const breakout = H.popover()
.findAllByText(dimensionName)
@@ -227,6 +263,7 @@ const selectBreakout = (
} else {
breakout.click();
}
+ cy.wait("@dataset");
};
/**
@@ -262,7 +299,7 @@ const openExpressionRename = (pillIndex: number) => {
*/
const selectDimensionBreakout = (
dimensionName: string,
- { seeAll = false }: { seeAll?: boolean } = {},
+ { seeAll = false, waitForDataset = true } = {},
) => {
H.MetricsViewer.openDimensionPickerSidebar();
if (seeAll) {
@@ -274,6 +311,10 @@ const selectDimensionBreakout = (
.findByRole("button", { name: dimensionName })
.click();
H.MetricsViewer.closeDimensionPickerSidebar();
+
+ if (waitForDataset) {
+ cy.wait("@dataset");
+ }
};
const showColumnLabels = () => {
@@ -317,13 +358,13 @@ const waitForSerializedDimensionBreakout = () => {
};
const addOrdersProductsExpression = () => {
- addMetricMath(
+ addMetricInputSequence(
[
- { metricName: "Count of orders" },
+ { nameOrPath: "Count of orders" },
"+",
- { metricName: "Count of products" },
+ { nameOrPath: "Count of products" },
],
- false,
+ { runExpression: false },
);
runFormulaWithKeyboard();
cy.wait("@dataset");
@@ -432,6 +473,13 @@ const assertLegendColorsMatchPill = (pillIndex: number) => {
});
};
+const testMeasurePath = [
+ "Databases",
+ "Sample Database",
+ "Orders",
+ "Test Measure",
+];
+
describe("scenarios > metrics > explorer", () => {
before(() => {
H.restore();
@@ -440,6 +488,7 @@ describe("scenarios > metrics > explorer", () => {
createTestMeasure();
H.snapshot(SNAPSHOT_NAME);
});
+
beforeEach(() => {
H.restore(SNAPSHOT_NAME as any);
cy.signInAsAdmin();
@@ -447,6 +496,7 @@ describe("scenarios > metrics > explorer", () => {
interceptDatasetQuery();
cy.intercept("GET", "/api/metric/*").as("getMetric");
cy.intercept("GET", "/api/measure/*").as("getMeasure");
+ cy.intercept("GET", "/api/search*").as("search");
H.resetSnowplow();
H.enableTracking();
});
@@ -455,10 +505,6 @@ describe("scenarios > metrics > explorer", () => {
H.expectNoBadSnowplowEvents();
});
- // ============================================================================
- // Entry Points
- // ============================================================================
-
describe("Entry points", () => {
it("should show empty state on first load", () => {
H.MetricsViewer.goToViewer();
@@ -505,16 +551,11 @@ describe("scenarios > metrics > explorer", () => {
});
});
- // ============================================================================
- // Adding Metrics and Measures
- // ============================================================================
-
describe("Adding metrics and measures", () => {
it("should add multiple metrics", () => {
H.MetricsViewer.goToViewer();
addMetric("Count of products");
- cy.wait("@dataset");
H.expectUnstructuredSnowplowEvent({
event: "metrics_viewer_metric_added",
@@ -522,14 +563,13 @@ describe("scenarios > metrics > explorer", () => {
});
addMetric("Count of orders");
- cy.wait("@dataset");
verifyMetricCount(2);
cy.log("allows duplicates");
addMetric("Count of products");
cy.log("Should allow me to add measures");
- addMetric("Test Measure");
+ addMetricInputSequence([{ nameOrPath: testMeasurePath }]);
H.expectUnstructuredSnowplowEvent({
event: "metrics_viewer_metric_added",
event_detail: "measure",
@@ -539,63 +579,27 @@ describe("scenarios > metrics > explorer", () => {
H.MetricsViewer.searchInput().type("{end}xyznonexistent", {
waitForAnimations: true,
});
- H.MetricsViewer.searchResults().should(
- "contain.text",
- "No search results",
- );
+ H.miniPicker().should("contain.text", "No search results");
});
- it("should add metrics and measures from the entity picker", () => {
- H.activateToken("pro-self-hosted").then(() => {
- return createLibraryWithTable();
- });
+ it("should disable tables without measures when browsing database measures", () => {
H.MetricsViewer.goToViewer();
- cy.log("Add a metric from the entity picker");
- H.MetricsViewer.searchInput().type("Count", { waitForAnimations: true });
- H.MetricsViewer.searchResults().findByText("Browse all").click();
- cy.findByTestId("nested-item-picker").should("be.visible");
- H.pickEntity({ path: ["Our analytics", "Count of orders"] });
- cy.findByTestId("metrics-viewer-search-input").should(
- "contain.text",
- "Count of orders",
- );
-
- cy.log("Add a measure from the entity picker");
- H.MetricsViewer.searchInput().type("{end}, Test", {
- waitForAnimations: true,
- });
- H.MetricsViewer.searchResults().findByText("Browse all").click();
- cy.findByTestId("nested-item-picker").should("be.visible");
- H.pickEntity({ path: ["Library", "Data", "Orders", "Test Measure"] });
- cy.findByTestId("metrics-viewer-search-input").should(
- "contain.text",
- "Test Measure",
- );
-
- runFormula();
-
- verifyMetricCount(2);
-
H.MetricsViewer.searchInput().type("Sample", { waitForAnimations: true });
- H.MetricsViewer.searchResults().findByText("Browse all").click();
+ H.miniPickerBrowseAll().click();
cy.findByTestId("nested-item-picker").should("be.visible");
H.pickEntity({ path: ["Databases", "Sample Database"] });
- cy.log("People is disabled because it doesn't have measures");
H.entityPickerModalItem(2, "People").should(
"have.attr",
"data-disabled",
"true",
);
-
- cy.log("Orders is not disabled because it has measures");
H.entityPickerModalItem(2, "Orders").should(
"not.have.attr",
"data-disabled",
);
- cy.log("Can search for measures");
H.entityPickerModal().within(() => {
cy.findByPlaceholderText("Search…").type("Test");
H.entityPickerModalItem(1, "Test Measure").should("be.visible");
@@ -604,14 +608,12 @@ describe("scenarios > metrics > explorer", () => {
it("should add multiple metrics one by one using metrics dropdown", () => {
H.MetricsViewer.goToViewer();
-
- addMetric("Count of products", false);
- selectMetricSearchResult("Count of orders");
- selectMetricSearchResult("Count of orders over time");
- selectMetricSearchResult("Orders model metric");
- runFormula();
-
- cy.wait("@dataset");
+ addMetricInputSequence([
+ { nameOrPath: "Count of products" },
+ { nameOrPath: "Count of orders" },
+ { nameOrPath: "Count of orders over time" },
+ { nameOrPath: "Orders model metric" },
+ ]);
verifyMetricCount(4);
});
@@ -621,13 +623,10 @@ describe("scenarios > metrics > explorer", () => {
H.MetricsViewer.searchInput().type("Count of", {
waitForAnimations: true,
});
- H.MetricsViewer.searchResults().should(
- "contain.text",
- "No search results",
- );
+ H.miniPicker().should("contain.text", "No search results");
H.MetricsViewer.searchInput().clear().type("Test Measure");
- H.MetricsViewer.searchResults().should("contain.text", "Test Measure");
+ H.miniPicker().should("contain.text", "Test Measure");
});
it("should not show me measures that live in tables I do not have permissions to see", () => {
@@ -636,14 +635,9 @@ describe("scenarios > metrics > explorer", () => {
H.MetricsViewer.searchInput().type("Test Measure", {
waitForAnimations: true,
});
- H.MetricsViewer.searchResults().should(
- "contain.text",
- "No search results",
- );
+ H.miniPicker().should("contain.text", "No search results");
- H.MetricsViewer.searchInput().clear();
-
- addMetric("Count of orders");
+ addMetric("Count of orders", { clearInput: true });
cy.log(
"even though we can see the metric, we don't have permissions to run the query",
);
@@ -653,22 +647,14 @@ describe("scenarios > metrics > explorer", () => {
});
});
- // ============================================================================
- // Breakouts
- // ============================================================================
-
describe("Breakouts", () => {
beforeEach(() => {
- interceptDatasetQuery();
- cy.intercept("GET", "/api/metric/*").as("getMetric");
H.MetricsViewer.goToViewer();
addMetric("Count of orders");
- cy.wait("@dataset");
});
it("should add a temporal breakout dimension", () => {
selectBreakout("Count of orders", "Created At", 0, "Year");
- cy.wait("@dataset");
H.MetricsViewer.breakoutLegend().within(() => {
cy.findByRole("heading", { name: "Created At" }).should("be.visible");
const currentYear = new Date().getFullYear();
@@ -698,7 +684,6 @@ describe("scenarios > metrics > explorer", () => {
it("should add a categorical breakout dimension", () => {
selectBreakout("Count of orders", "Source");
- cy.wait("@dataset");
H.MetricsViewer.breakoutLegend()
.findByRole("heading", { name: /Source/ })
.should("be.visible");
@@ -715,7 +700,6 @@ describe("scenarios > metrics > explorer", () => {
it("should add a numeric breakout dimension with default binning", () => {
selectBreakout("Count of orders", "Total");
- cy.wait("@dataset");
H.MetricsViewer.breakoutLegend().within(() => {
cy.findByRole("heading", { name: "Total" }).should("be.visible");
@@ -742,17 +726,12 @@ describe("scenarios > metrics > explorer", () => {
cy.log(
"Expand formula editor and create expression with second metric instance",
);
- addMetricMath(
- [
- { metricName: "Count of orders" },
- "+",
- { metricName: "Count of products" },
- ],
- false,
- );
-
- addMetric("Count of orders");
- cy.wait("@dataset");
+ addMetricInputSequence([
+ { nameOrPath: "Count of orders" },
+ "+",
+ { nameOrPath: "Count of products" },
+ { nameOrPath: "Count of orders" },
+ ]);
cy.log("Should have 2 metric pills (expression pill is separate)");
H.MetricsViewer.searchBarPills().should("have.length", 3);
@@ -776,7 +755,6 @@ describe("scenarios > metrics > explorer", () => {
H.MetricsViewer.searchBarPills().eq(0).click();
H.popover().findByText("Add a series breakout").click();
H.popover().findByText("Source").click();
- cy.wait("@dataset");
cy.log("Breakout legend should be visible with Source values");
H.MetricsViewer.breakoutLegend().should("be.visible");
@@ -882,10 +860,7 @@ describe("scenarios > metrics > explorer", () => {
it("should preserve breakout state when editing formula and re-running", () => {
cy.log("Set up: two instances of Count of orders with an expression");
- cy.findByTestId("metrics-formula-input").click();
-
addMetric("Count of orders");
- cy.wait("@dataset");
H.MetricsViewer.searchBarPills().should("have.length", 2);
@@ -906,13 +881,13 @@ describe("scenarios > metrics > explorer", () => {
cy.log("Enter formula edit mode and append a new metric");
cy.findByTestId("metrics-formula-input").click();
- H.MetricsViewer.searchInput().type("Count of products", {
+ cy.findByTestId("mini-picker").should("be.visible");
+ H.MetricsViewer.searchInput().type(", Count of products", {
waitForAnimations: true,
});
- selectMetricSearchResult("Count of products");
+ selectEntityPickerItem("Count of products");
cy.wait("@getMetric");
-
- cy.findByTestId("run-expression-button").click();
+ runFormula();
cy.wait("@dataset");
cy.log("Should now have 3 metric pills");
@@ -966,12 +941,11 @@ describe("scenarios > metrics > explorer", () => {
});
it("cannot breakout a metric math expression", () => {
- addMetricMath([
- { metricName: "Count of orders" },
+ addMetricInputSequence([
+ { nameOrPath: "Count of orders" },
"+",
- { metricName: "Test Measure" },
+ { nameOrPath: testMeasurePath },
]);
- cy.wait("@dataset");
cy.log("Expression pill menu only offers Rename, no breakout options");
H.MetricsViewer.searchBarPills().eq(1).click();
@@ -986,130 +960,19 @@ describe("scenarios > metrics > explorer", () => {
});
});
- it("should show an expression dimension pill with per-metric accordion", () => {
- H.MetricsViewer.goToViewer();
- cy.log("Create expression: Count of orders + Count of products");
- addOrdersProductsExpression();
-
- cy.log(
- "Dimension pill bar should contain a selected expression dimension label",
- );
- showColumnLabels();
- H.MetricsViewer.getDimensionPillBarContainer()
- .should("be.visible")
- .and("not.contain.text", "Select dimensions");
-
- cy.log("Open the sidebar dimension picker");
- H.MetricsViewer.openDimensionPickerSidebar();
-
- cy.log(
- "All fields should show accordion sections for each metric in the expression",
- );
- H.MetricsViewer.dimensionPickerSidebar().within(() => {
- cy.findByRole("button", { name: "See all" }).click();
- cy.findByRole("heading", { name: "All fields" }).should("be.visible");
- cy.findByRole("button", { name: "Count of orders" })
- .should("be.visible")
- .and("have.attr", "aria-expanded", "true");
- cy.findByRole("button", { name: "Count of products" })
- .scrollIntoView()
- .should("be.visible")
- .and("have.attr", "aria-expanded", "false")
- .click();
- cy.findAllByRole("button", { name: "Category" }).should(
- "have.length.at.least",
- 1,
- );
- });
-
- cy.log(
- "Configure the shared Time category and select a non-default dimension",
- );
- H.MetricsViewer.dimensionPickerSidebar()
- .findByRole("button", { name: "Back" })
- .click();
- openTimeDimensionConfiguration();
- H.MetricsViewer.dimensionPickerSidebar()
- .findByLabelText("Select dimension for Count of orders")
- .click();
- cy.findByRole("option", { name: /Birth Date/ }).click();
-
- cy.wait("@dataset");
-
- cy.log("Expression dimension pill should now show 'Multiple dimensions'");
- H.MetricsViewer.getDimensionPillBarContainer().should(
- "contain.text",
- "Multiple dimensions",
- );
- });
-
- it("should preserve non-default expression dimensions after page reload", () => {
- H.MetricsViewer.goToViewer();
- cy.log(
- "Create expression with only expression entity: Count of orders + Count of products",
- );
- addOrdersProductsExpression();
- showColumnLabels();
-
- cy.log("Pick a non-default dimension for one metric in the expression");
- H.MetricsViewer.openDimensionPickerSidebar();
- openTimeDimensionConfiguration();
- H.MetricsViewer.dimensionPickerSidebar()
- .findByLabelText("Select dimension for Count of orders")
- .click();
- cy.findByRole("option", { name: /Birth Date/ }).click();
-
- cy.wait("@dataset");
-
- cy.log("Verify the pill shows 'Multiple dimensions' (non-default state)");
- H.MetricsViewer.getDimensionPillBarContainer().should(
- "contain.text",
- "Multiple dimensions",
- );
- waitForSerializedDimensionBreakout();
-
- cy.log("Reload the page and verify the dimension choice persists");
- cy.reload();
- cy.wait("@getMetric");
- cy.wait("@dataset");
-
- cy.log(
- "Verify the per-metric dimension selections are restored after reload",
- );
- H.MetricsViewer.openDimensionPickerSidebar();
- openTimeDimensionConfiguration();
- H.MetricsViewer.dimensionPickerSidebar().within(() => {
- cy.findByLabelText("Select dimension for Count of orders").should(
- "have.value",
- "Birth Date",
- );
- cy.findByLabelText("Select dimension for Count of products").should(
- "have.value",
- "Created At",
- );
- });
- });
-
- // ============================================================================
- // Expression Custom Names
- // ============================================================================
-
describe("Expression custom names", () => {
beforeEach(() => {
- interceptDatasetQuery();
H.MetricsViewer.goToViewer();
addMetric("Count of orders");
- cy.wait("@dataset");
H.MetricsViewer.getMetricVisualization().should("be.visible");
});
it("should allow setting a custom name on an expression pill", () => {
- addMetricMath([
- { metricName: "Count of orders" },
+ addMetricInputSequence([
+ { nameOrPath: "Count of orders" },
"+",
- { metricName: "Test Measure" },
+ { nameOrPath: testMeasurePath },
]);
- cy.wait("@dataset");
cy.log("Click the expression pill to open name editor");
H.MetricsViewer.searchBarPills()
@@ -1132,7 +995,6 @@ describe("scenarios > metrics > explorer", () => {
cy.log("Add breakout on the first metric to trigger the legend");
selectBreakout("Count of orders", "Source");
- cy.wait("@dataset");
cy.log("Legend should display the custom expression name");
H.MetricsViewer.breakoutLegend().within(() => {
@@ -1154,12 +1016,13 @@ describe("scenarios > metrics > explorer", () => {
});
it("should revert to formula text when custom name is cleared", () => {
- addMetricMath([
- { metricName: "Count of orders" },
+ addMetricInputSequence([
+ { nameOrPath: "Count of orders" },
"+",
- { metricName: "Test Measure" },
+ {
+ nameOrPath: testMeasurePath,
+ },
]);
- cy.wait("@dataset");
cy.log("Set a custom name");
H.MetricsViewer.searchBarPills().should("have.length", 2);
@@ -1189,7 +1052,6 @@ describe("scenarios > metrics > explorer", () => {
cy.log("Add breakout on the first metric to trigger the legend");
selectBreakout("Count of orders", "Source");
- cy.wait("@dataset");
cy.log(
"Legend should use the formula-derived name, not the old custom name",
@@ -1215,12 +1077,11 @@ describe("scenarios > metrics > explorer", () => {
});
it("should preserve custom name when re-running with the same expression", () => {
- addMetricMath([
- { metricName: "Count of orders" },
+ addMetricInputSequence([
+ { nameOrPath: "Count of orders" },
"+",
- { metricName: "Test Measure" },
+ { nameOrPath: testMeasurePath },
]);
- cy.wait("@dataset");
cy.log("Set a custom name on the expression pill");
H.MetricsViewer.searchBarPills().should("have.length", 2);
@@ -1236,7 +1097,6 @@ describe("scenarios > metrics > explorer", () => {
cy.log("Enter formula mode and re-run the expression");
addMetric("Count of products");
- cy.wait("@dataset");
cy.log("Custom name should still be preserved");
H.MetricsViewer.searchBarPills()
@@ -1256,12 +1116,11 @@ describe("scenarios > metrics > explorer", () => {
});
it("should not change expression pill color when renaming", () => {
- addMetricMath([
- { metricName: "Count of orders" },
+ addMetricInputSequence([
+ { nameOrPath: "Count of orders" },
"+",
- { metricName: "Test Measure" },
+ { nameOrPath: testMeasurePath },
]);
- cy.wait("@dataset");
cy.log("Capture the expression pill color before renaming");
const expressionPillIndex = 1;
@@ -1286,12 +1145,11 @@ describe("scenarios > metrics > explorer", () => {
});
it("should preserve custom name when the expression is edited in place but keeps at least one original metric", () => {
- addMetricMath([
- { metricName: "Count of orders" },
+ addMetricInputSequence([
+ { nameOrPath: "Count of orders" },
"+",
- { metricName: "Test Measure" },
+ { nameOrPath: testMeasurePath },
]);
- cy.wait("@dataset");
cy.log("Set a custom name on the expression pill");
H.MetricsViewer.searchBarPills().should("have.length", 2);
@@ -1319,8 +1177,7 @@ describe("scenarios > metrics > explorer", () => {
"{end}{backspace}{backspace}{backspace}{backspace}",
{ waitForAnimations: true },
);
- addMetricMath(["*", { metricName: "Count of products" }]);
- cy.wait("@dataset");
+ addMetricInputSequence(["*", { nameOrPath: "Count of products" }]);
cy.log(
"The expression now reads 'Count of orders * Count of products' " +
@@ -1338,14 +1195,14 @@ describe("scenarios > metrics > explorer", () => {
// Now names are bound to identities — the surviving expression keeps
// its own "Second Name".
cy.log("Build two separately-named expressions");
- cy.findByTestId("metrics-formula-input").click();
- H.MetricsViewer.searchInput().clear();
- addMetricMath([
- { metricName: "Count of orders" },
- "+",
- { metricName: "Test Measure" },
- ]);
- cy.wait("@dataset");
+ addMetricInputSequence(
+ [
+ { nameOrPath: "Count of orders" },
+ "+",
+ { nameOrPath: testMeasurePath },
+ ],
+ { clearInput: true },
+ );
H.MetricsViewer.searchBarPills().should("have.length", 1);
openExpressionRename(0);
@@ -1356,16 +1213,12 @@ describe("scenarios > metrics > explorer", () => {
.eq(0)
.should("contain.text", "First Name");
- cy.findByTestId("metrics-formula-input").click();
- H.MetricsViewer.searchInput().type("{end}, ", {
- waitForAnimations: true,
- });
- addMetricMath([
- { metricName: "Count of orders" },
+ addMetricInputSequence([
+ ",",
+ { nameOrPath: "Count of orders" },
"+",
- { metricName: "Test Measure" },
+ { nameOrPath: testMeasurePath },
]);
- cy.wait("@dataset");
H.MetricsViewer.searchBarPills().should("have.length", 2);
openExpressionRename(1);
@@ -1394,7 +1247,6 @@ describe("scenarios > metrics > explorer", () => {
{ waitForAnimations: true },
);
runFormula();
- cy.wait("@dataset");
cy.log(
"The surviving expression must keep its own 'Second Name' and " +
@@ -1408,277 +1260,363 @@ describe("scenarios > metrics > explorer", () => {
});
});
- // ============================================================================
- // Dimension picker sidebar
- // ============================================================================
-
describe("Dimension picker sidebar", () => {
- beforeEach(() => {
- interceptDatasetQuery();
- H.MetricsViewer.goToViewer();
- addMetric("Count of orders");
- cy.wait("@dataset");
- H.MetricsViewer.getMetricVisualization().should("be.visible");
- });
+ describe("Regular metric pills", () => {
+ beforeEach(() => {
+ H.MetricsViewer.goToViewer();
+ addMetric("Count of orders");
+ H.MetricsViewer.getMetricVisualization().should("be.visible");
+ });
- it("should open and close from the viewer controls", () => {
- H.MetricsViewer.getMetricVisualization().should("be.visible");
+ it("should open and close from the viewer controls", () => {
+ H.MetricsViewer.getMetricVisualization().should("be.visible");
+
+ H.MetricsViewer.openDimensionPickerSidebar().within(() => {
+ cy.findByRole("heading", { name: "Break out" }).should("be.visible");
+ cy.findByLabelText("Search fields").should("be.visible");
+ cy.findByRole("button", { name: "Time" }).should("be.visible");
+ cy.findByRole("button", { name: "Category" }).should("be.visible");
+ cy.findByRole("button", { name: "Totals" }).should("not.exist");
+ });
- H.MetricsViewer.openDimensionPickerSidebar().within(() => {
- cy.findByRole("heading", { name: "Break out" }).should("be.visible");
- cy.findByLabelText("Search fields").should("be.visible");
- cy.findByRole("button", { name: "Time" }).should("be.visible");
- cy.findByRole("button", { name: "Category" }).should("be.visible");
- cy.findByRole("button", { name: "Totals" }).should("not.exist");
+ H.MetricsViewer.closeDimensionPickerSidebar();
+ H.MetricsViewer.dimensionPickerSidebar().should("not.exist");
+ H.MetricsViewer.getMetricVisualization().should("be.visible");
});
- H.MetricsViewer.closeDimensionPickerSidebar();
- H.MetricsViewer.dimensionPickerSidebar().should("not.exist");
- H.MetricsViewer.getMetricVisualization().should("be.visible");
- });
+ it("should select and reopen the No breakout state from the viewer controls", () => {
+ H.MetricsViewer.openDimensionPickerSidebar().within(() => {
+ cy.findByRole("button", { name: "No breakout" })
+ .should("be.visible")
+ .and("have.attr", "aria-pressed", "false")
+ .click();
+ });
+ cy.wait("@dataset");
- it("should select and reopen the No breakout state from the viewer controls", () => {
- H.MetricsViewer.openDimensionPickerSidebar().within(() => {
- cy.findByRole("button", { name: "No breakout" })
+ H.MetricsViewer.dimensionPickerSidebar().within(() => {
+ cy.findByRole("button", { name: "No breakout" }).should(
+ "have.attr",
+ "aria-pressed",
+ "true",
+ );
+ });
+ H.MetricsViewer.assertVizType("Number");
+ H.MetricsViewer.breakoutLegend().should("not.exist");
+
+ H.MetricsViewer.closeDimensionPickerSidebar();
+ H.MetricsViewer.dimensionPickerSidebar().should("not.exist");
+
+ H.MetricsViewer.getMetricControls()
+ .findByRole("button", { name: "No breakout" })
.should("be.visible")
- .and("have.attr", "aria-pressed", "false")
.click();
- });
- cy.wait("@dataset");
- H.MetricsViewer.dimensionPickerSidebar().within(() => {
- cy.findByRole("button", { name: "No breakout" }).should(
- "have.attr",
- "aria-pressed",
- "true",
- );
+ H.MetricsViewer.dimensionPickerSidebar().within(() => {
+ cy.findByRole("heading", { name: "Break out" }).should("be.visible");
+ cy.findByRole("button", { name: "No breakout" }).should(
+ "have.attr",
+ "aria-pressed",
+ "true",
+ );
+ });
});
- H.MetricsViewer.assertVizType("Number");
- H.MetricsViewer.breakoutLegend().should("not.exist");
- H.MetricsViewer.closeDimensionPickerSidebar();
- H.MetricsViewer.dimensionPickerSidebar().should("not.exist");
+ it("should select dimension categories from the sidebar", () => {
+ addMetricInputSequence([
+ { nameOrPath: "Count of orders" },
+ "+",
+ { nameOrPath: testMeasurePath },
+ ]);
- H.MetricsViewer.getMetricControls()
- .findByRole("button", { name: "No breakout" })
- .should("be.visible")
- .click();
+ H.MetricsViewer.assertVizType("Line");
- H.MetricsViewer.dimensionPickerSidebar().within(() => {
- cy.findByRole("heading", { name: "Break out" }).should("be.visible");
- cy.findByRole("button", { name: "No breakout" }).should(
- "have.attr",
- "aria-pressed",
- "true",
- );
- });
- });
+ selectDimensionBreakout("State", { seeAll: true });
+ H.expectUnstructuredSnowplowEvent({
+ event: "metrics_viewer_dimension_selected",
+ });
+ H.MetricsViewer.assertAllVizTypes("Map", 2);
- it("should select dimension categories from the sidebar", () => {
- addMetricMath([
- { metricName: "Count of orders" },
- "+",
- { metricName: "Test Measure" },
- ]);
- cy.wait("@dataset");
+ selectDimensionBreakout("Category");
+ H.MetricsViewer.assertVizType("Bar");
- H.MetricsViewer.assertVizType("Line");
+ cy.log("should allow changing display types");
+ H.MetricsViewer.changeVizType("line");
+ H.MetricsViewer.assertVizType("Line");
+ });
- selectDimensionBreakout("State", { seeAll: true });
- cy.wait("@dataset");
- H.expectUnstructuredSnowplowEvent({
- event: "metrics_viewer_dimension_selected",
+ it("should keep all fields available while selecting dimensions from See all", () => {
+ H.MetricsViewer.openDimensionPickerSidebar().within(() => {
+ cy.findByRole("button", { name: "See all" }).click();
+ cy.findByRole("heading", { name: "All fields" }).should("be.visible");
+ cy.findByRole("button", { name: "Address" }).should("be.visible");
+ cy.findByRole("button", { name: "City" }).should("be.visible");
+ cy.findByRole("button", { name: "Address" }).click();
+ });
+ cy.wait("@dataset");
+
+ H.MetricsViewer.dimensionPickerSidebar().within(() => {
+ cy.findByRole("button", { name: "Address" })
+ .scrollIntoView()
+ .should("be.visible");
+ cy.findByRole("button", { name: "City" })
+ .scrollIntoView()
+ .should("be.visible");
+ cy.findByRole("button", { name: "City" }).click();
+ });
+ cy.wait("@dataset");
+
+ H.MetricsViewer.dimensionPickerSidebar().within(() => {
+ cy.findByRole("button", { name: "Address" })
+ .scrollIntoView()
+ .should("be.visible");
+ cy.findByRole("button", { name: "City" })
+ .scrollIntoView()
+ .should("be.visible");
+ });
});
- H.MetricsViewer.assertAllVizTypes("Map", 2);
- selectDimensionBreakout("Category");
- cy.wait("@dataset");
- H.MetricsViewer.assertVizType("Bar");
+ it("should only show shared dimensions by default for multiple metric sources", () => {
+ addMetric(["Our analytics", "Count of feedback"]);
+ verifyMetricCount(2);
- cy.log("should allow changing display types");
- H.MetricsViewer.changeVizType("line");
- H.MetricsViewer.assertVizType("Line");
- });
+ H.MetricsViewer.openDimensionPickerSidebar()
+ .should("contain.text", "Shared dimensions")
+ .and("contain.text", "Time")
+ .and("not.contain.text", "Rating");
- it("should keep all fields available while selecting dimensions from See all", () => {
- H.MetricsViewer.openDimensionPickerSidebar().within(() => {
- cy.findByRole("button", { name: "See all" }).click();
- cy.findByRole("heading", { name: "All fields" }).should("be.visible");
- cy.findByRole("button", { name: "Address" }).should("be.visible");
- cy.findByRole("button", { name: "City" }).should("be.visible");
- cy.findByRole("button", { name: "Address" }).click();
+ H.MetricsViewer.dimensionPickerSidebar()
+ .findByRole("button", { name: "See all" })
+ .click();
+
+ H.MetricsViewer.dimensionPickerSidebar().within(() => {
+ cy.findByRole("heading", { name: "All fields" }).should("be.visible");
+ cy.findAllByRole("button", { name: "Rating" }).should(
+ "have.length.at.least",
+ 1,
+ );
+ });
});
- cy.wait("@dataset");
- H.MetricsViewer.dimensionPickerSidebar().within(() => {
- cy.findByRole("button", { name: "Address" })
- .scrollIntoView()
- .should("be.visible");
- cy.findByRole("button", { name: "City" })
- .scrollIntoView()
- .should("be.visible");
- cy.findByRole("button", { name: "City" }).click();
+ it("should configure per-metric dimensions for a shared category", () => {
+ addMetric("Count of products");
+
+ H.MetricsViewer.openDimensionPickerSidebar()
+ .findByRole("button", { name: "Time" })
+ .realHover();
+
+ H.MetricsViewer.dimensionPickerSidebar()
+ .findByRole("button", { name: "Configure Time" })
+ .click();
+
+ H.MetricsViewer.dimensionPickerSidebar()
+ .findByLabelText("Select dimension for Count of orders")
+ .click();
+ cy.findByRole("option", { name: /Birth Date/ }).click();
+ cy.wait("@dataset");
+
+ H.MetricsViewer.dimensionPickerSidebar()
+ .findByLabelText("Select dimension for Count of orders")
+ .should("have.value", "Birth Date");
+ H.MetricsViewer.dimensionPickerSidebar()
+ .findByLabelText("Select dimension for Count of products")
+ .should("have.value", "Created At");
});
- cy.wait("@dataset");
- H.MetricsViewer.dimensionPickerSidebar().within(() => {
- cy.findByRole("button", { name: "Address" })
- .scrollIntoView()
- .should("be.visible");
- cy.findByRole("button", { name: "City" })
- .scrollIntoView()
- .should("be.visible");
+ it("should render column labels as static text", () => {
+ H.MetricsViewer.getMetricControls()
+ .findByLabelText("Column label options")
+ .click();
+ cy.findByRole("switch", { name: "Show column labels" }).click();
+
+ H.MetricsViewer.getDimensionPillBarContainer().within(() => {
+ cy.findByText("Created At").should("be.visible").click();
+ cy.findByRole("button").should("not.exist");
+ });
+ H.MetricsViewer.dimensionPickerSidebar().should("not.exist");
});
- });
- it("should only show shared dimensions by default for multiple metric sources", () => {
- addMetric("Count of feedback");
- cy.wait("@dataset");
- verifyMetricCount(2);
+ it("should auto-assign dimensions for a newly added metric after running the formula", () => {
+ cy.log(
+ "After adding a second metric, all dimension labels should have a selected dimension",
+ );
- H.MetricsViewer.openDimensionPickerSidebar()
- .should("contain.text", "Shared dimensions")
- .and("contain.text", "Time")
- .and("not.contain.text", "Rating");
+ addMetric("Count of products");
- H.MetricsViewer.dimensionPickerSidebar()
- .findByRole("button", { name: "See all" })
- .click();
+ H.MetricsViewer.getColumnPickerButton().should(
+ "not.contain.text",
+ "Select a dimension",
+ );
- H.MetricsViewer.dimensionPickerSidebar().within(() => {
- cy.findByRole("heading", { name: "All fields" }).should("be.visible");
- cy.findAllByRole("button", { name: "Rating" }).should(
- "have.length.at.least",
- 1,
+ selectDimensionBreakout("Category");
+ H.MetricsViewer.getColumnPickerButton().should(
+ "not.contain.text",
+ "Select a dimension",
);
});
- });
- it("should configure per-metric dimensions for a shared category", () => {
- addMetric("Count of products");
- cy.wait("@dataset");
-
- H.MetricsViewer.openDimensionPickerSidebar()
- .findByRole("button", { name: "Time" })
- .realHover();
+ it("should preserve a selected dimension after page reload", () => {
+ addMetricInputSequence([
+ { nameOrPath: "Count of orders" },
+ "+",
+ { nameOrPath: "Count of products" },
+ ]);
- H.MetricsViewer.dimensionPickerSidebar()
- .findByRole("button", { name: "Configure Time" })
- .click();
+ selectDimensionBreakout("Category");
+ H.MetricsViewer.getColumnPickerButton().should(
+ "contain.text",
+ "Category",
+ );
- H.MetricsViewer.dimensionPickerSidebar()
- .findByLabelText("Select dimension for Count of orders")
- .click();
- cy.findByRole("option", { name: /Birth Date/ }).click();
- cy.wait("@dataset");
+ cy.reload();
+ cy.wait("@dataset");
+ H.MetricsViewer.getColumnPickerButton().should(
+ "contain.text",
+ "Category",
+ );
+ });
- H.MetricsViewer.dimensionPickerSidebar()
- .findByLabelText("Select dimension for Count of orders")
- .should("have.value", "Birth Date");
- H.MetricsViewer.dimensionPickerSidebar()
- .findByLabelText("Select dimension for Count of products")
- .should("have.value", "Created At");
- });
+ it("should serialize only the selected dimension breakout in the URL", () => {
+ selectDimensionBreakout("State", { seeAll: true });
+ selectDimensionBreakout("Category");
- it("should render column labels as static text", () => {
- H.MetricsViewer.getMetricControls()
- .findByLabelText("Column label options")
- .click();
- cy.findByRole("switch", { name: "Show column labels" }).click();
+ getMetricsViewerUrlState().then((state) => {
+ expect(state.t).to.have.length(1);
+ const [breakout] = state.t ?? [];
+ if (!breakout) {
+ throw new Error("Expected one serialized dimension breakout");
+ }
+ expect(breakout).to.include({ t: "category", l: "Category" });
+ expect(state.a).to.equal(breakout.i);
+ });
- H.MetricsViewer.getDimensionPillBarContainer().within(() => {
- cy.findByText("Created At").should("be.visible").click();
- cy.findByRole("button").should("not.exist");
+ cy.reload();
+ cy.wait("@dataset");
+ H.MetricsViewer.getColumnPickerButton().should(
+ "contain.text",
+ "Category",
+ );
});
- H.MetricsViewer.dimensionPickerSidebar().should("not.exist");
});
- it("should auto-assign dimensions for a newly added metric after running the formula", () => {
- cy.log(
- "After adding a second metric, all dimension labels should have a selected dimension",
- );
+ describe("Expression pills", () => {
+ it("should show an expression dimension pill with per-metric accordion", () => {
+ H.MetricsViewer.goToViewer();
+ cy.log("Create expression: Count of orders + Count of products");
+ addOrdersProductsExpression();
- cy.findByTestId("metrics-formula-input").click();
- addMetric("Count of products");
- cy.wait("@dataset");
+ cy.log(
+ "Dimension pill bar should contain a selected expression dimension label",
+ );
+ showColumnLabels();
+ H.MetricsViewer.getDimensionPillBarContainer()
+ .should("be.visible")
+ .and("not.contain.text", "Select dimensions");
- H.MetricsViewer.getColumnPickerButton().should(
- "not.contain.text",
- "Select a dimension",
- );
+ cy.log("Open the sidebar dimension picker");
+ H.MetricsViewer.openDimensionPickerSidebar();
- selectDimensionBreakout("Category");
- cy.wait("@dataset");
- H.MetricsViewer.getColumnPickerButton().should(
- "not.contain.text",
- "Select a dimension",
- );
- });
+ cy.log(
+ "All fields should show accordion sections for each metric in the expression",
+ );
+ H.MetricsViewer.dimensionPickerSidebar().within(() => {
+ cy.findByRole("button", { name: "See all" }).click();
+ cy.findByRole("heading", { name: "All fields" }).should("be.visible");
+ cy.findByRole("button", { name: "Count of orders" })
+ .should("be.visible")
+ .and("have.attr", "aria-expanded", "true");
+ cy.findByRole("button", { name: "Count of products" })
+ .scrollIntoView()
+ .should("be.visible")
+ .and("have.attr", "aria-expanded", "false")
+ .click();
+ cy.findAllByRole("button", { name: "Category" }).should(
+ "have.length.at.least",
+ 1,
+ );
+ });
- it("should preserve a selected dimension after page reload", () => {
- addMetricMath([
- { metricName: "Count of orders" },
- "+",
- { metricName: "Count of products" },
- ]);
- cy.wait("@dataset");
+ cy.log(
+ "Configure the shared Time category and select a non-default dimension",
+ );
+ H.MetricsViewer.dimensionPickerSidebar()
+ .findByRole("button", { name: "Back" })
+ .click();
+ openTimeDimensionConfiguration();
+ H.MetricsViewer.dimensionPickerSidebar()
+ .findByLabelText("Select dimension for Count of orders")
+ .click();
+ cy.findByRole("option", { name: /Birth Date/ }).click();
- selectDimensionBreakout("Category");
- cy.wait("@dataset");
- H.MetricsViewer.getColumnPickerButton().should(
- "contain.text",
- "Category",
- );
+ cy.wait("@dataset");
- cy.reload();
- cy.wait("@dataset");
- H.MetricsViewer.getColumnPickerButton().should(
- "contain.text",
- "Category",
- );
- });
+ cy.log(
+ "Expression dimension pill should now show 'Multiple dimensions'",
+ );
+ H.MetricsViewer.getDimensionPillBarContainer().should(
+ "contain.text",
+ "Multiple dimensions",
+ );
+ });
- it("should serialize only the selected dimension breakout in the URL", () => {
- selectDimensionBreakout("State", { seeAll: true });
- cy.wait("@dataset");
+ it("should preserve non-default expression dimensions after page reload", () => {
+ H.MetricsViewer.goToViewer();
+ cy.log(
+ "Create expression with only expression entity: Count of orders + Count of products",
+ );
+ addOrdersProductsExpression();
+ showColumnLabels();
+
+ cy.log("Pick a non-default dimension for one metric in the expression");
+ H.MetricsViewer.openDimensionPickerSidebar();
+ openTimeDimensionConfiguration();
+ H.MetricsViewer.dimensionPickerSidebar()
+ .findByLabelText("Select dimension for Count of orders")
+ .click();
+ cy.findByRole("option", { name: /Birth Date/ }).click();
- selectDimensionBreakout("Category");
- cy.wait("@dataset");
+ cy.wait("@dataset");
- getMetricsViewerUrlState().then((state) => {
- expect(state.t).to.have.length(1);
- const [breakout] = state.t ?? [];
- if (!breakout) {
- throw new Error("Expected one serialized dimension breakout");
- }
- expect(breakout).to.include({ t: "category", l: "Category" });
- expect(state.a).to.equal(breakout.i);
- });
+ cy.log(
+ "Verify the pill shows 'Multiple dimensions' (non-default state)",
+ );
+ H.MetricsViewer.getDimensionPillBarContainer().should(
+ "contain.text",
+ "Multiple dimensions",
+ );
+ waitForSerializedDimensionBreakout();
- cy.reload();
- cy.wait("@dataset");
- H.MetricsViewer.getColumnPickerButton().should(
- "contain.text",
- "Category",
- );
+ cy.log("Reload the page and verify the dimension choice persists");
+ cy.reload();
+ cy.wait("@getMetric");
+ cy.wait("@dataset");
+
+ cy.log(
+ "Verify the per-metric dimension selections are restored after reload",
+ );
+ H.MetricsViewer.openDimensionPickerSidebar();
+ openTimeDimensionConfiguration();
+ H.MetricsViewer.dimensionPickerSidebar().within(() => {
+ cy.findByLabelText("Select dimension for Count of orders").should(
+ "have.value",
+ "Birth Date",
+ );
+ cy.findByLabelText("Select dimension for Count of products").should(
+ "have.value",
+ "Created At",
+ );
+ });
+ });
});
});
- // ============================================================================
- // Automatic Split View
- // ============================================================================
-
describe("Automatic split view", () => {
beforeEach(() => {
- interceptDatasetQuery();
H.MetricsViewer.goToViewer();
addMetric("Count of orders");
- cy.wait("@dataset");
});
it("should show unified view for display types that support multiple series", () => {
addMetric("Count of products");
- cy.wait("@dataset");
cy.log("line charts support multiple series, so should be unified");
H.MetricsViewer.assertVizType("Line");
@@ -1686,14 +1624,12 @@ describe("scenarios > metrics > explorer", () => {
cy.log("bar charts also support multiple series");
selectDimensionBreakout("Category");
- cy.wait("@dataset");
H.MetricsViewer.assertVizType("Bar");
H.MetricsViewer.getAllMetricVisualizations().should("have.length", 1);
});
it("should stack series into panels when the stack series button is toggled", () => {
addMetric("Count of products");
- cy.wait("@dataset");
cy.log("line chart with multiple series should show chart layout picker");
H.MetricsViewer.assertVizType("Line");
@@ -1713,7 +1649,6 @@ describe("scenarios > metrics > explorer", () => {
cy.log("button should not be visible for non-line/area/bar charts");
selectDimensionBreakout("State", { seeAll: true });
- cy.wait("@dataset");
H.MetricsViewer.assertVizType("Map");
cy.findByTestId("chart-layout-picker").should("not.exist");
});
@@ -1721,22 +1656,18 @@ describe("scenarios > metrics > explorer", () => {
it("should automatically split for display types that do not support multiple series", () => {
cy.log("with a single series, map shows one visualization");
selectDimensionBreakout("State");
- cy.wait("@dataset");
H.MetricsViewer.assertVizType("Map");
H.MetricsViewer.getAllMetricVisualizations().should("have.length", 1);
cy.log("add a breakout to create multiple series");
- selectDimensionBreakout("Time");
- cy.wait("@dataset");
+ selectDimensionBreakout("Time", { waitForDataset: false });
selectBreakout("Count of orders", "Source");
- cy.wait("@dataset");
cy.log("line supports multiple series, so should remain unified");
H.MetricsViewer.getAllMetricVisualizations().should("have.length", 1);
cy.log("map does not support multiple series, so should auto-split");
selectDimensionBreakout("State");
- cy.wait("@dataset");
H.MetricsViewer.getAllMetricVisualizations().should(
"have.length.greaterThan",
1,
@@ -1744,16 +1675,10 @@ describe("scenarios > metrics > explorer", () => {
});
});
- // ============================================================================
- // Filters
- // ============================================================================
-
describe("Filters", () => {
beforeEach(() => {
- interceptDatasetQuery();
H.MetricsViewer.goToViewer();
addMetric("Count of orders");
- cy.wait("@dataset");
});
it("should apply a categorical filter to a metric", () => {
@@ -1798,7 +1723,6 @@ describe("scenarios > metrics > explorer", () => {
.should("contain.text", "Gizmo");
selectDimensionBreakout("Category");
- cy.wait("@dataset");
H.MetricsViewer.getMetricVisualization().should(
"contain.text",
"Doohickey",
@@ -1833,7 +1757,6 @@ describe("scenarios > metrics > explorer", () => {
cy.log("remove filter");
selectDimensionBreakout("State");
- cy.wait("@dataset");
H.MetricsViewer.getAllMetricVisualizations().should("have.length", 3);
H.MetricsViewer.getAllFilterPills()
@@ -1903,7 +1826,6 @@ describe("scenarios > metrics > explorer", () => {
it("should allow me to apply filters to each metric individually", () => {
addMetric("Count of products");
selectDimensionBreakout("Category");
- cy.wait("@dataset");
H.MetricsViewer.changeVizType("line");
H.MetricsViewer.getMetricVisualizationDataPoints().should(
"have.length",
@@ -1931,7 +1853,6 @@ describe("scenarios > metrics > explorer", () => {
"Should allow me to change time granularity and range on time based dimensions",
);
selectDimensionBreakout("Time");
- cy.wait("@dataset");
H.MetricsViewer.getMetricVisualizationDataPoints().should(
"have.length",
@@ -2005,7 +1926,6 @@ describe("scenarios > metrics > explorer", () => {
it("should preserve breakout colors when a dimension filter hides some values", () => {
selectBreakout("Count of orders", "Quantity");
- cy.wait("@dataset");
const colorsBefore: Record<string, string> = {};
@@ -2078,7 +1998,6 @@ describe("scenarios > metrics > explorer", () => {
describe("Segments", () => {
beforeEach(() => {
- interceptDatasetQuery();
H.MetricsViewer.goToViewer();
});
@@ -2096,7 +2015,6 @@ describe("scenarios > metrics > explorer", () => {
});
addMetric("Count of orders");
- cy.wait("@dataset");
H.MetricsViewer.getFilterButton().click();
@@ -2137,48 +2055,43 @@ describe("scenarios > metrics > explorer", () => {
});
});
- // ============================================================================
- // Drill Through
- // ============================================================================
-
describe("Drill through", () => {
beforeEach(() => {
- interceptDatasetQuery();
H.MetricsViewer.goToViewer();
- addMetric("Count of orders");
- cy.wait("@dataset");
- //should work with metric math as well
- addMetricMath([
- { metricName: "Count of orders" },
+ addMetricInputSequence([{ nameOrPath: "Count of orders" }]);
+ addMetricInputSequence([
+ ",",
+ { nameOrPath: "Count of orders" },
"+",
- { metricName: "Test Measure" },
+ { nameOrPath: testMeasurePath },
]);
- cy.wait("@dataset");
});
it("should drill into more granular time dimensions on timeseries chart", () => {
H.MetricsViewer.getMetricControls()
.findByRole("button", { name: /by month/ })
.should("be.visible");
- // this is messy, but adding the metric math expression causes the viz to unmount and dispose the ECharts instance
- // if you click on the chart while it's being disposed, the click isn't handled properly
- cy.wait(1000);
- H.MetricsViewer.getMetricVisualization()
- .get("path[stroke='#EF8C8C']")
+ H.ensureChartIsActive();
+ H.cartesianChartCircles()
.eq(4)
- .click();
- H.popover().findByText("See this month by week").click();
+ .should("be.visible")
+ .click({ force: true });
+ H.popover()
+ .findByText("See this month by week")
+ .should("be.visible")
+ .click({ force: true });
H.MetricsViewer.getMetricControls()
.findByRole("button", { name: /by week/ })
.should("be.visible");
H.MetricsViewer.getMetricVisualizationDataPoints().should(
- "have.length",
+ "have.length.at.least",
10,
);
});
it("should allow me to do brush style time range filtering", () => {
+ H.ensureChartIsActive();
H.applyBrush(100, 250);
H.MetricsViewer.getMetricVisualization().within(() => {
cy.findByText(/June/).should("be.visible");
@@ -2199,24 +2112,24 @@ describe("scenarios > metrics > explorer", () => {
it("should not show 'No compatible dimensions' after deleting and retyping an expression with metrics in a different order (UXW-3748)", () => {
cy.log("Create expression: Count of orders + Count of products");
- addMetricMath([
- { metricName: "Count of orders" },
+ addMetricInputSequence([
+ { nameOrPath: "Count of orders" },
"+",
- { metricName: "Count of products" },
+ { nameOrPath: "Count of products" },
]);
- cy.wait("@dataset");
H.MetricsViewer.getMetricVisualization().should("be.visible");
cy.log(
"Re-enter the formula editor, delete the whole expression, retype with metrics in the opposite order",
);
- H.MetricsViewer.searchInput().clear();
- addMetricMath([
- { metricName: "Count of products" },
- "+",
- { metricName: "Count of orders" },
- ]);
- cy.wait("@dataset");
+ addMetricInputSequence(
+ [
+ { nameOrPath: "Count of products" },
+ "+",
+ { nameOrPath: "Count of orders" },
+ ],
+ { clearInput: true },
+ );
cy.log("Expression should run without 'No compatible dimensions' error");
H.MetricsViewer.getMetricVisualization().should("be.visible");
@@ -2231,7 +2144,7 @@ describe("scenarios > metrics > explorer", () => {
H.MetricsViewer.searchInput().type("{end}, Count of orders", {
waitForAnimations: true,
});
- H.MetricsViewer.searchResults()
+ H.miniPicker()
.findByText("Count of orders")
.closest("[role='menuitem']")
.click();
@@ -2274,25 +2187,24 @@ describe("scenarios > metrics > explorer", () => {
});
});
- describe("metric math", () => {
+ describe("Metric math", () => {
beforeEach(() => {
interceptDatasetQuery();
H.MetricsViewer.goToViewer();
addMetric("Count of orders");
- cy.wait("@dataset");
});
it("should apply filters and dimensions to individual metric instances within expressions", () => {
- H.MetricsViewer.searchInput().clear();
- addMetricMath([
- { metricName: "Count of orders" },
- "+",
- { metricName: "Count of orders" },
- ]);
- cy.wait("@dataset");
+ addMetricInputSequence(
+ [
+ { nameOrPath: "Count of orders" },
+ "+",
+ { nameOrPath: "Count of orders" },
+ ],
+ { clearInput: true },
+ );
selectDimensionBreakout("Category");
- cy.wait("@dataset");
H.MetricsViewer.getFilterButton().click();
H.popover().within(() => {
@@ -2373,33 +2285,31 @@ describe("scenarios > metrics > explorer", () => {
});
cy.log("Sum metric '123' with itself — both selected from dropdown");
- H.MetricsViewer.searchInput().clear();
- addMetricMath([
- { metricName: NUMERIC_METRIC_NAME },
- "+",
- { metricName: NUMERIC_METRIC_NAME },
- ]);
- cy.wait("@dataset");
+ addMetricInputSequence(
+ [
+ { nameOrPath: ["Our analytics", NUMERIC_METRIC_NAME] },
+ "+",
+ { nameOrPath: ["Our analytics", NUMERIC_METRIC_NAME] },
+ ],
+ { clearInput: true },
+ );
H.MetricsViewer.getMetricVisualization().should("be.visible");
cy.log(
"Append literal number 123 — typed without selecting from dropdown",
);
- cy.findByTestId("metrics-formula-input").click();
- H.MetricsViewer.searchInput().type(" + 123", {
- waitForAnimations: true,
- });
- runFormula();
- cy.wait("@dataset");
+ addMetricInputSequence([
+ "+",
+ { nameOrPath: ["Our analytics", NUMERIC_METRIC_NAME] },
+ ]);
+
H.MetricsViewer.getMetricVisualization().should("be.visible");
cy.log("Append metric '123' as standalone — selected from dropdown");
- H.MetricsViewer.searchInput().type(`{end}, ${NUMERIC_METRIC_NAME}`, {
- waitForAnimations: true,
- });
- selectMetricSearchResult(NUMERIC_METRIC_NAME);
- runFormula();
- cy.wait("@dataset");
+ addMetricInputSequence([
+ ",",
+ { nameOrPath: ["Our analytics", NUMERIC_METRIC_NAME] },
+ ]);
H.MetricsViewer.getAllMetricVisualizations().should("have.length", 2);
cy.log("Verify final pill layout");
@@ -2411,6 +2321,10 @@ describe("scenarios > metrics > explorer", () => {
});
describe("scenarios > metrics > explorer > BigInt filters", () => {
+ beforeEach(() => {
+ interceptDatasetQuery();
+ });
+
it("should filter on BigInt values", () => {
const DECIMAL_PK_TABLE_NAME = "decimal_pk_table";
const METRIC_NAME = "Count of decimal_pk_table";
@@ -2418,7 +2332,7 @@ describe("scenarios > metrics > explorer > BigInt filters", () => {
H.restore("postgres-writable");
cy.signInAsAdmin();
H.resetTestTable({ type: "postgres", table: DECIMAL_PK_TABLE_NAME });
- H.resyncDatabase({ dbId: WRITABLE_DB_ID });
+ H.resyncDatabase({ dbId: WRITABLE_DB_ID, tables: [DECIMAL_PK_TABLE_NAME] });
H.getTableId({ name: DECIMAL_PK_TABLE_NAME }).then((tableId) => {
const BIGINT_METRIC: StructuredQuestionDetailsWithName = {
diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useFormulaEditor.ts b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useFormulaEditor.ts
index a516e949ac1..436b69a17ff 100644
--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useFormulaEditor.ts
+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useFormulaEditor.ts
@@ -18,6 +18,7 @@ import {
} from "../../../utils/source-ids";
import type { MetricSearchDropdownRef } from "../MetricSearchDropdown";
import {
+ type MetricIdentityEntry,
type MetricNameMap,
applyTrackedDefinitions,
buildFullTextWithIdentities,
@@ -130,6 +131,10 @@ export function useFormulaEditor({
const [textAtFocus, setTextAtFocus] = useState("");
const textAtFocusRef = useRef(textAtFocus);
textAtFocusRef.current = textAtFocus;
+ const pendingMetricIdentitiesRef = useRef<MetricIdentityEntry[] | null>(null);
+ const [editingSessionIdentities, setEditingSessionIdentities] = useState<
+ MetricIdentityEntry[]
+ >([]);
// Explicitly tracks whether the expression was modified during this editing
// session (metric selected from dropdown, or text typed). Avoids timing
// issues with comparing editText vs textAtFocus across async state updates.
@@ -182,6 +187,7 @@ export function useFormulaEditor({
formulaEntitiesRef.current,
metricNamesRef.current,
);
+ setEditingSessionIdentities(initialIdentities);
const requestedCaret = pendingCaretPositionRef.current;
const shouldOpenDropdown = requestedCaret == null;
@@ -307,6 +313,7 @@ export function useFormulaEditor({
setEditText("");
setValidationError(null);
setIsExpressionDirty(false);
+ setEditingSessionIdentities([]);
}, [
editorRef,
metricNamesRef,
@@ -354,6 +361,10 @@ export function useFormulaEditor({
const handleChange = useCallback(
(newText: string) => {
+ const view = editorRef.current?.view;
+ if (view) {
+ pendingMetricIdentitiesRef.current = readMetricIdentities(view);
+ }
editTextRef.current = newText;
setEditText(newText);
setValidationError(null);
@@ -365,7 +376,6 @@ export function useFormulaEditor({
}
// Extract the word at the cursor for the dropdown search
- const view = editorRef.current?.view;
const cursorPos = view?.state.selection.main.head ?? newText.length;
const identities = view ? readMetricIdentities(view) : [];
const { word, start: wordStart } = getWordAtCursor(
@@ -387,6 +397,59 @@ export function useFormulaEditor({
[editorRef, metricNamesRef],
);
+ /**
+ * @uiw/react-codemirror can sync the controlled value with a full doc
+ * replacement, which drops our custom identity field. Restore identities that
+ * still point at the same metric text so validation does not reject them.
+ */
+ useEffect(() => {
+ const view = editorRef.current?.view;
+ const pendingIdentities = pendingMetricIdentitiesRef.current;
+
+ if (!view || pendingIdentities == null) {
+ return;
+ }
+
+ if (view.state.doc.toString() !== editText) {
+ return;
+ }
+
+ const currentIdentities = readMetricIdentities(view);
+ const identityByPosition = new Map<string, MetricIdentityEntry>(
+ currentIdentities.map((identity): [string, MetricIdentityEntry] => [
+ `${identity.from}:${identity.to}`,
+ identity,
+ ]),
+ );
+
+ const recoverableIdentities =
+ editText === textAtFocusRef.current
+ ? [...editingSessionIdentities, ...pendingIdentities]
+ : pendingIdentities;
+
+ for (const identity of recoverableIdentities) {
+ const positionKey = `${identity.from}:${identity.to}`;
+ const metricName = metricNamesRef.current[identity.sourceId];
+ if (
+ !identityByPosition.has(positionKey) &&
+ metricName != null &&
+ view.state.doc.sliceString(identity.from, identity.to) === metricName
+ ) {
+ identityByPosition.set(positionKey, identity);
+ }
+ }
+
+ const recoveredIdentities = Array.from(identityByPosition.values());
+ if (currentIdentities.length < recoveredIdentities.length) {
+ view.dispatch({
+ effects: setMetricIdentities.of(
+ identitiesFromEntries(recoveredIdentities),
+ ),
+ });
+ }
+ pendingMetricIdentitiesRef.current = null;
+ }, [editText, editingSessionIdentities, editorRef, metricNamesRef]);
+
const handleSelect = useCallback(
(metric: SelectedMetric) => {
const view = editorRef.current?.view;
diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearchPanel/MetricSearchPanel.tsx b/frontend/src/metabase/metrics-viewer/components/MetricSearchPanel/MetricSearchPanel.tsx
index 117eef8e71c..1dc37e3a88f 100644
--- a/frontend/src/metabase/metrics-viewer/components/MetricSearchPanel/MetricSearchPanel.tsx
+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearchPanel/MetricSearchPanel.tsx
@@ -87,7 +87,9 @@ export function MetricSearchPanel() {
return (
<Stack gap="md">
<Flex align="center" justify="space-between" mih="1.875rem">
- <Text fw={700} size="lg">{t`Explore`}</Text>
+ <Text fw={700} size="lg" component="h1">
+ {t`Explore`}
+ </Text>
{hasDefinitions && (
<FilterPopover
definitionSources={definitionSources}
diff --git a/frontend/src/metabase/metrics-viewer/utils/MetricsViewerClickActionsMode.ts b/frontend/src/metabase/metrics-viewer/utils/MetricsViewerClickActionsMode.ts
index bb07f0274ff..cc07ecfde92 100644
--- a/frontend/src/metabase/metrics-viewer/utils/MetricsViewerClickActionsMode.ts
+++ b/frontend/src/metabase/metrics-viewer/utils/MetricsViewerClickActionsMode.ts
@@ -9,18 +9,27 @@ import * as LibMetric from "metabase-lib/metric";
import type { CardId, DatetimeUnit, TemporalUnit } from "metabase-types/api";
import {
+ type ExpressionDefinitionEntry,
type MetricDefinitionEntry,
type MetricSourceId,
type MetricsViewerDefinitionEntry,
type MetricsViewerDimensionBreakoutState,
type MetricsViewerFormulaEntity,
+ isExpressionEntry,
isMetricEntry,
} from "../types/viewer-state";
-import { getEffectiveDefinitionEntry } from "./definition-entries";
+import {
+ getEffectiveDefinitionEntry,
+ getEffectiveTokenDefinitionEntry,
+} from "./definition-entries";
import type { DimensionFilterValue } from "./dimension-filters";
import { findDimensionById } from "./dimension-lookup";
-import { type MetricSlot, findStandaloneSlot } from "./metric-slots";
+import {
+ type MetricSlot,
+ findStandaloneSlot,
+ slotsForEntity,
+} from "./metric-slots";
type MetricsViewerClickActionParams = {
definitions: Record<MetricSourceId, MetricsViewerDefinitionEntry>;
@@ -100,7 +109,7 @@ function getZoomInTimeSeriesAction({
onDimensionBreakoutUpdate,
clickObject,
}: GetActionParams): ClickAction | undefined {
- if (!entity || entityIndex == null || !isMetricEntry(entity)) {
+ if (!entity || entityIndex == null) {
return;
}
const dimension = clickObject.dimensions?.[0];
@@ -111,14 +120,26 @@ function getZoomInTimeSeriesAction({
if (!isValidTemporalUnit(currentTemporalUnit)) {
return;
}
- const nextTemporalUnit = getNextTemporalUnit(
- definitions,
- entity,
- entityIndex,
- metricSlots,
- dimensionBreakout,
- currentTemporalUnit,
- );
+ let nextTemporalUnit: TemporalUnit | undefined;
+ if (isMetricEntry(entity)) {
+ nextTemporalUnit = getNextTemporalUnit(
+ definitions,
+ entity,
+ entityIndex,
+ metricSlots,
+ dimensionBreakout,
+ currentTemporalUnit,
+ );
+ } else if (isExpressionEntry(entity)) {
+ nextTemporalUnit = getNextTemporalUnitForExpression(
+ definitions,
+ entity,
+ entityIndex,
+ metricSlots,
+ dimensionBreakout,
+ currentTemporalUnit,
+ );
+ }
if (!nextTemporalUnit) {
return;
}
@@ -225,3 +246,46 @@ function getNextTemporalUnit(
);
return filteredNextTemporalUnitMap[currentUnit];
}
+
+function getNextTemporalUnitForExpression(
+ definitions: Record<MetricSourceId, MetricsViewerDefinitionEntry>,
+ entity: ExpressionDefinitionEntry,
+ entityIndex: number,
+ metricSlots: MetricSlot[],
+ dimensionBreakout: MetricsViewerDimensionBreakoutState,
+ currentUnit: TemporalUnit,
+): TemporalUnit | undefined {
+ const expressionSlots = slotsForEntity(metricSlots, entityIndex);
+ const firstSlot = expressionSlots[0];
+ if (!firstSlot) {
+ return undefined;
+ }
+ const tokenPosition = firstSlot.tokenPosition;
+ if (tokenPosition === undefined) {
+ return undefined;
+ }
+ const token = entity.tokens[tokenPosition];
+ if (!token || token.type !== "metric") {
+ return undefined;
+ }
+ const definitionEntry = getEffectiveTokenDefinitionEntry(token, definitions);
+ const definition = definitionEntry.definition;
+ const dimensionId = dimensionBreakout.dimensionMapping[firstSlot.slotIndex];
+ if (!definition || !dimensionId) {
+ return undefined;
+ }
+ const dimension = findDimensionById(definition, dimensionId);
+ if (!dimension) {
+ return undefined;
+ }
+ const availableBuckets = LibMetric.availableTemporalBuckets(
+ definition,
+ dimension,
+ ).map((bucket) => LibMetric.displayInfo(definition, bucket).shortName);
+ const filteredNextTemporalUnitMap = Object.fromEntries(
+ Object.entries(nextTemporalUnitMap).filter(([_key, value]) =>
+ availableBuckets.includes(value),
+ ),
+ );
+ return filteredNextTemporalUnitMap[currentUnit];
+}