Skip to content

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

Replace flaky metric-aggregation e2e test with a unit test (#82964)

Nemanja Glumac1a0ff4340be8
diff --git a/e2e/support/helpers/e2e-codemirror-helpers.ts b/e2e/support/helpers/e2e-codemirror-helpers.ts
index c7c96f9531d..60ffaeb867b 100644
--- a/e2e/support/helpers/e2e-codemirror-helpers.ts
+++ b/e2e/support/helpers/e2e-codemirror-helpers.ts
@@ -153,19 +153,14 @@ export function codeMirrorHelpers<T extends object>(testId: string, extra: T) {
return helpers.get().get("[role='textbox']");
},
value() {
- // The editor mounts with an empty document and fills it in when the first
- // format finishes. It can also mount late, because its chunk loads on
- // demand. Wait for two identical reads before reporting the value, or a
- // read that lands in either window reports an empty editor.
- let previous: string | null = null;
- cy.get(`[data-testid=${testId}] .cm-content`).should(($content) => {
- const current = textOf($content);
- const isStable = previous !== null && current === previous;
- previous = current;
- expect(isStable, "the editor text is stable").to.be.true;
- });
-
- return helpers.get().then(textOf);
+ // `invoke` chains are queries, so a chained assertion re-reads the text on every retry
+ return helpers
+ .get()
+ .invoke("find", ".cm-line")
+ .invoke("toArray")
+ .invoke("filter", (line) => !line.querySelector(".cm-placeholder"))
+ .invoke("map", (line) => line.textContent ?? "")
+ .invoke("join", "\n");
},
completions() {
return cy.get(".cm-tooltip-autocomplete").should("be.visible");
@@ -236,18 +231,3 @@ export function codeMirrorValue() {
return value;
});
}
-
-/**
- * The text of every line in a CodeMirror editor, skipping the placeholder line
- * that stands in for an empty document.
- */
-function textOf($content: JQuery<HTMLElement>) {
- const text: string[] = [];
- $content.find(".cm-line").each((_, line) => {
- if (line.querySelector(".cm-placeholder")) {
- return;
- }
- text.push(line.textContent ?? "");
- });
- return text.join("\n");
-}
diff --git a/e2e/test/scenarios/question/notebook.cy.spec.js b/e2e/test/scenarios/question/notebook.cy.spec.js
index 512c76d3c96..d47598e2c10 100644
--- a/e2e/test/scenarios/question/notebook.cy.spec.js
+++ b/e2e/test/scenarios/question/notebook.cy.spec.js
@@ -663,43 +663,6 @@ describe("scenarios > question > notebook", { tags: "@slow" }, () => {
});
});
- it("should not crash notebook when metric is used as an aggregation and breakout is applied (metabase#40553)", () => {
- H.createQuestion(
- {
- query: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.SUBTOTAL, null]]],
- },
- type: "metric",
- name: "Revenue",
- },
- {
- wrapId: true,
- idAlias: "metricId",
- },
- );
-
- cy.get("@metricId").then((metricId) => {
- const questionDetails = {
- query: {
- "source-table": ORDERS_ID,
- breakout: [
- ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
- ],
- aggregation: ["metric", metricId],
- },
- };
-
- H.createQuestion(questionDetails, { visitQuestion: true });
-
- H.openNotebook();
-
- H.getNotebookStep("summarize").contains("Revenue").click();
-
- H.CustomExpressionEditor.value().should("equal", "[Revenue]");
- });
- });
-
it("should open only one bucketing popover at a time (metabase#45036)", () => {
H.visitQuestionAdhoc(
{
diff --git a/frontend/src/metabase/querying/components/expressions/Editor/Editor.tsx b/frontend/src/metabase/querying/components/expressions/Editor/Editor.tsx
index c58d519d1ff..be4e86bc190 100644
--- a/frontend/src/metabase/querying/components/expressions/Editor/Editor.tsx
+++ b/frontend/src/metabase/querying/components/expressions/Editor/Editor.tsx
@@ -367,8 +367,12 @@ function useExpression({
);
const handleBlur = useCallback(() => {
+ // `source` is stale until formatting settles; updating now would overwrite the formatted result
+ if (isFormatting) {
+ return;
+ }
handleUpdate(source, true);
- }, [handleUpdate, source]);
+ }, [handleUpdate, source, isFormatting]);
const handleFormatExpression = useCallback(() => {
formatExpression({ initial: false });
diff --git a/frontend/src/metabase/querying/notebook/components/AggregateStep/AggregateStep.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/AggregateStep/AggregateStep.unit.spec.tsx
index 2960f8c1c5f..5b5c460a828 100644
--- a/frontend/src/metabase/querying/notebook/components/AggregateStep/AggregateStep.unit.spec.tsx
+++ b/frontend/src/metabase/querying/notebook/components/AggregateStep/AggregateStep.unit.spec.tsx
@@ -1,5 +1,6 @@
import userEvent from "@testing-library/user-event";
+import { createMockMetadata } from "__support__/metadata";
import { setupDatabaseEndpoints } from "__support__/server-mocks";
import {
createMockQueryBuilderState,
@@ -10,12 +11,21 @@ import {
queryIcon,
renderWithProviders,
screen,
+ waitFor,
} from "__support__/ui";
import * as Lib from "metabase-lib";
-import { SAMPLE_PROVIDER } from "metabase-lib/test-helpers";
-import { createMockCard } from "metabase-types/api/mocks";
import {
+ SAMPLE_PROVIDER,
+ createMetadataProvider,
+} from "metabase-lib/test-helpers";
+import {
+ createMockCard,
+ createMockStructuredDatasetQuery,
+} from "metabase-types/api/mocks";
+import {
+ ORDERS,
ORDERS_ID,
+ SAMPLE_DB_ID,
createSampleDatabase,
} from "metabase-types/api/mocks/presets";
@@ -24,6 +34,43 @@ import type { NotebookStep } from "../../types";
import { AggregateStep } from "./AggregateStep";
+function createMetricAggregatedQuery() {
+ const metric = createMockCard({
+ id: 1,
+ name: "Revenue",
+ type: "metric",
+ table_id: ORDERS_ID,
+ dataset_query: createMockStructuredDatasetQuery({
+ database: SAMPLE_DB_ID,
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.SUBTOTAL, null]]],
+ },
+ }),
+ });
+ const metadata = createMockMetadata({
+ databases: [createSampleDatabase()],
+ questions: [metric],
+ });
+
+ return Lib.createTestQuery(createMetadataProvider({ metadata }), {
+ stages: [
+ {
+ source: { type: "table", id: ORDERS_ID },
+ aggregations: [{ type: "metric", id: metric.id }],
+ breakouts: [
+ {
+ type: "column",
+ sourceName: "ORDERS",
+ name: "CREATED_AT",
+ unit: "month",
+ },
+ ],
+ },
+ ],
+ });
+}
+
function createAggregatedQuery() {
return Lib.createTestQuery(SAMPLE_PROVIDER, {
stages: [
@@ -197,6 +244,20 @@ describe("AggregateStep", () => {
expect(Lib.aggregations(nextQuery, 0)).toHaveLength(0);
});
+ it("should open a metric aggregation with a breakout in the expression editor", async () => {
+ setup({
+ step: createMockNotebookStep({ query: createMetricAggregatedQuery() }),
+ });
+
+ await userEvent.click(screen.getByText("Revenue"));
+
+ await waitFor(() =>
+ expect(screen.getByTestId("custom-expression-query-editor")).toHaveValue(
+ "[Revenue]",
+ ),
+ );
+ });
+
describe("metrics", () => {
it("should not allow to remove an existing aggregation or add another one", () => {
const query = createAggregatedQuery();