From ff21b86bc8dfa39fefac073db1601ffcf3ab1dba Mon Sep 17 00:00:00 2001
From: Nemanja Glumac <31325167+nemanjaglumac@users.noreply.github.com>
Date: Mon, 22 Aug 2022 19:10:59 +0200
Subject: [PATCH] Consolidate E2E tests with nested questions (#24888)

* Delete unused scenarios from 12568

* Refactor repro for 12568

* Refactor repro 12507

* Refactor repro 10474

* Refactor repro 14787

* Refactor repro 14724

* Refactor repro 15352

* Refactor repro 15808

* Refactor repro 15397

* Merge repros 15808, 16938, 18364

* Move repro for #11561 over to nested questions spec
---
 .../18364-cannot-save-nested.cy.spec.js       |  31 -
 .../scenarios/question/nested.cy.spec.js      | 558 +++++++++---------
 .../scenarios/question/notebook.cy.spec.js    |  45 --
 ...38-nested-native-query-pk-drill.cy.spec.js |  36 --
 4 files changed, 286 insertions(+), 384 deletions(-)
 delete mode 100644 frontend/test/metabase/scenarios/native/reproductions/18364-cannot-save-nested.cy.spec.js
 delete mode 100644 frontend/test/metabase/scenarios/question/reproductions/16938-nested-native-query-pk-drill.cy.spec.js

diff --git a/frontend/test/metabase/scenarios/native/reproductions/18364-cannot-save-nested.cy.spec.js b/frontend/test/metabase/scenarios/native/reproductions/18364-cannot-save-nested.cy.spec.js
deleted file mode 100644
index ab0b7ba640a..00000000000
--- a/frontend/test/metabase/scenarios/native/reproductions/18364-cannot-save-nested.cy.spec.js
+++ /dev/null
@@ -1,31 +0,0 @@
-import { restore } from "__support__/e2e/helpers";
-
-const questionDetails = {
-  name: "REVIEWS SQL",
-  native: { query: "select REVIEWER from REVIEWS LIMIT 1" },
-};
-
-describe("issue 18364", () => {
-  beforeEach(() => {
-    cy.intercept("POST", "/api/card").as("cardCreated");
-
-    restore();
-    cy.signInAsAdmin();
-  });
-
-  it("should be able to save a nested question (metabase#18364)", () => {
-    cy.createNativeQuestion(questionDetails, { visitQuestion: true });
-
-    cy.findByText("Explore results").click();
-
-    cy.findByText("Save").click();
-
-    cy.get(".Modal").button("Save").click();
-
-    cy.wait("@cardCreated").then(({ response: { body } }) => {
-      expect(body.error).not.to.exist;
-    });
-
-    cy.button("Failed").should("not.exist");
-  });
-});
diff --git a/frontend/test/metabase/scenarios/question/nested.cy.spec.js b/frontend/test/metabase/scenarios/question/nested.cy.spec.js
index af73f4145c0..185aaa25ac7 100644
--- a/frontend/test/metabase/scenarios/question/nested.cy.spec.js
+++ b/frontend/test/metabase/scenarios/question/nested.cy.spec.js
@@ -3,11 +3,11 @@ import {
   popover,
   openOrdersTable,
   remapDisplayValueToFK,
+  visitQuestion,
   visitQuestionAdhoc,
   visualize,
   getDimensionByName,
   summarize,
-  startNewQuestion,
   filter,
   filterField,
 } from "__support__/e2e/helpers";
@@ -15,131 +15,97 @@ import {
 import { SAMPLE_DB_ID } from "__support__/e2e/cypress_data";
 import { SAMPLE_DATABASE } from "__support__/e2e/cypress_sample_database";
 
-const { ORDERS, ORDERS_ID, PRODUCTS, PRODUCTS_ID } = SAMPLE_DATABASE;
+const { ORDERS, ORDERS_ID, PRODUCTS, PRODUCTS_ID, PEOPLE } = SAMPLE_DATABASE;
+
+const ordersJoinProductsQuery = {
+  "source-table": ORDERS_ID,
+  joins: [
+    {
+      fields: "all",
+      "source-table": PRODUCTS_ID,
+      condition: [
+        "=",
+        ["field", ORDERS.PRODUCT_ID, null],
+        ["field", PRODUCTS.ID, { "join-alias": "Products" }],
+      ],
+      alias: "Products",
+    },
+  ],
+};
 
-describe("scenarios > question > nested (metabase#12568)", () => {
+describe("scenarios > question > nested", () => {
   beforeEach(() => {
     restore();
     cy.signInAsAdmin();
+  });
 
-    // Create a simple question of orders by week
-    cy.createQuestion(
-      {
-        name: "GH_12568: Simple",
-        query: {
-          "source-table": ORDERS_ID,
-          aggregation: [["count"]],
-          breakout: [["field", ORDERS.CREATED_AT, { "temporal-unit": "week" }]],
-        },
-        display: "line",
+  it("should allow 'Distribution' and 'Sum over time' on nested questions (metabase#12568)", () => {
+    cy.intercept("POST", "/api/dataset").as("dataset");
+
+    // Make sure it works for a GUI question
+    const guiQuestionDetails = {
+      name: "GH_12568: Simple",
+      query: {
+        "source-table": ORDERS_ID,
+        aggregation: [["count"]],
+        breakout: [["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }]],
       },
-      { loadMetadata: true },
-    );
+      display: "line",
+    };
 
-    // Create a native question of orders by day
-    cy.createNativeQuestion(
+    createNestedQuestion(
       {
-        name: "GH_12568: SQL",
-        native: {
-          query:
-            "SELECT date_trunc('day', CREATED_AT) as date, COUNT(*) as count FROM ORDERS GROUP BY date_trunc('day', CREATED_AT)",
-        },
-        display: "scalar",
+        baseQuestionDetails: guiQuestionDetails,
+        nestedQuestionDetails: { name: "Nested GUI" },
       },
-      { loadMetadata: true, interceptAlias: "secondCardQuery" },
+      { loadBaseQuestionMetadata: true },
     );
 
-    startNewQuestion();
-
-    cy.contains("Saved Questions").click();
-
-    // [quarantine] The whole CI was timing out
-    // Create a complex native question
-    // cy.createNativeQuestion({
-    //   name: "GH_12568: Complex SQL",
-    //   native: {
-    //     query: `WITH tmp_user_order_dates as (
-    //         SELECT
-    //           o.USER_ID,
-    //           o.CREATED_AT,
-    //           o.QUANTITY
-    //         FROM
-    //           ORDERS o
-    //       ),
-
-    //       tmp_prior_orders_by_date as (
-    //         select
-    //             tbod.USER_ID,
-    //             tbod.CREATED_AT,
-    //             tbod.QUANTITY,
-    //             (select count(*) from tmp_user_order_dates tbod2 where tbod2.USER_ID = tbod.USER_ID and tbod2.CREATED_AT < tbod.CREATED_AT ) as PRIOR_ORDERS
-    //         from tmp_user_order_dates tbod
-    //       )
-
-    //       select
-    //         date_trunc('day', tpobd.CREATED_AT) as "Date",
-    //         case when tpobd.PRIOR_ORDERS > 0 then 'Return' else 'New' end as "Customer Type",
-    //         sum(QUANTITY) as "Items Sold"
-    //       from tmp_prior_orders_by_date tpobd
-    //       group by date_trunc('day', tpobd.CREATED_AT), "Customer Type"
-    //       order by date_trunc('day', tpobd.CREATED_AT) asc`,
-    //   },
-    //   display: "scalar",
-    // });
-  });
-
-  it("should allow Distribution on a Saved Simple Question", () => {
-    cy.contains("GH_12568: Simple").click();
-    visualize();
     cy.contains("Count").click();
     cy.contains("Distribution").click();
+    cy.wait("@dataset");
     cy.contains("Count by Count: Auto binned");
     cy.get(".bar").should("have.length.of.at.least", 8);
-  });
 
-  it("should allow Sum over time on a Saved Simple Question", () => {
-    cy.contains("GH_12568: Simple").click();
-    visualize();
+    // Go back to the nested question and make sure Sum over time works
+    cy.findByText("Nested GUI").click();
+
     cy.contains("Count").click();
     cy.contains("Sum over time").click();
     cy.contains("Sum of Count");
-    cy.get(".dot").should("have.length.of.at.least", 10);
-  });
+    cy.findByText("137");
+
+    // Make sure it works for a SQL question
+    const sqlQuestionDetails = {
+      name: "GH_12568: SQL",
+      native: {
+        query:
+          "SELECT date_trunc('year', CREATED_AT) as date, COUNT(*) as count FROM ORDERS GROUP BY date_trunc('year', CREATED_AT)",
+      },
+      display: "scalar",
+    };
+
+    createNestedQuestion(
+      {
+        baseQuestionDetails: sqlQuestionDetails,
+        nestedQuestionDetails: { name: "Nested SQL" },
+      },
+      { loadBaseQuestionMetadata: true },
+    );
 
-  it("should allow Distribution on a Saved SQL Question", () => {
-    cy.contains("GH_12568: SQL").click();
-    visualize();
     cy.contains("COUNT").click();
     cy.contains("Distribution").click();
+    cy.wait("@dataset");
     cy.contains("Count by COUNT: Auto binned");
-    cy.get(".bar").should("have.length.of.at.least", 8);
-  });
+    cy.get(".bar").should("have.length.of.at.least", 5);
+
+    cy.findByText("Nested SQL").click();
 
-  // [quarantine] The whole CI was timing out
-  it.skip("should allow Sum over time on a Saved SQL Question", () => {
-    cy.contains("GH_12568: SQL").click();
-    visualize();
     cy.contains("COUNT").click();
     cy.contains("Sum over time").click();
+    cy.wait("@dataset");
     cy.contains("Sum of COUNT");
-    cy.get(".dot").should("have.length.of.at.least", 10);
-  });
-
-  // [quarantine] The whole CI was timing out
-  it.skip("should allow Distribution on a Saved complex SQL Question", () => {
-    cy.contains("GH_12568: Complex SQL").click();
-    visualize();
-    cy.contains("Items Sold").click();
-    cy.contains("Distribution").click();
-    cy.contains("Count by Items Sold: Auto binned");
-    cy.get(".bar").should("have.length.of.at.least", 10);
-  });
-});
-
-describe("scenarios > question > nested", () => {
-  beforeEach(() => {
-    restore();
-    cy.signInAsAdmin();
+    cy.findByText("744");
   });
 
   it("should handle duplicate column names in nested queries (metabase#10511)", () => {
@@ -192,11 +158,8 @@ describe("scenarios > question > nested", () => {
   });
 
   it("should apply metrics including filter to the nested question (metabase#12507)", () => {
-    const METRIC_NAME = "Sum of discounts";
-
-    cy.log("Create a metric with a filter");
-    cy.request("POST", "/api/metric", {
-      name: METRIC_NAME,
+    const metric = {
+      name: "Sum of discounts",
       description: "Discounted orders.",
       table_id: ORDERS_ID,
       definition: {
@@ -204,37 +167,34 @@ describe("scenarios > question > nested", () => {
         aggregation: [["count"]],
         filter: ["!=", ["field", ORDERS.DISCOUNT, null], 0],
       },
-    }).then(({ body: { id: metricId } }) => {
-      // "capture" the original query because we will need to re-use it later in a nested question as "source-query"
-      const ORIGINAL_QUERY = {
-        "source-table": ORDERS_ID,
-        aggregation: [["metric", metricId]],
-        breakout: [
-          ["field", ORDERS.TOTAL, { binning: { strategy: "default" } }],
-        ],
-      };
+    };
 
-      // Create new question which uses previously defined metric
-      cy.createQuestion({
-        name: "12507",
-        query: ORIGINAL_QUERY,
-      }).then(({ body: { id: questionId } }) => {
-        cy.log("Create and visit a nested question based on the previous one");
-        visitQuestionAdhoc({
-          dataset_query: {
-            type: "query",
-            query: {
-              "source-table": `card__${questionId}`,
-              filter: [">", ["field", ORDERS.TOTAL, null], 50],
-            },
-            database: SAMPLE_DB_ID,
+    cy.log("Create a metric with a filter");
+    cy.request("POST", "/api/metric", metric).then(
+      ({ body: { id: metricId } }) => {
+        // "capture" the original query because we will need to re-use it later in a nested question as "source-query"
+        const baseQuestionDetails = {
+          name: "12507",
+          query: {
+            "source-table": ORDERS_ID,
+            aggregation: [["metric", metricId]],
+            breakout: [
+              ["field", ORDERS.TOTAL, { binning: { strategy: "default" } }],
+            ],
           },
-        });
+        };
+
+        const nestedQuestionDetails = {
+          filter: [">", ["field", ORDERS.TOTAL, null], 50],
+        };
+
+        // Create new question which uses previously defined metric
+        createNestedQuestion({ baseQuestionDetails, nestedQuestionDetails });
 
         cy.log("Reported failing since v0.35.2");
-        cy.get(".cellData").contains(METRIC_NAME);
-      });
-    });
+        cy.get(".cellData").contains(metric.name);
+      },
+    );
   });
 
   it("should handle remapped display values in a base QB question (metabase#10474)", () => {
@@ -242,8 +202,6 @@ describe("scenarios > question > nested", () => {
       "Related issue [#14629](https://github.com/metabase/metabase/issues/14629)",
     );
 
-    cy.intercept("POST", "/api/dataset").as("dataset");
-
     cy.log("Remap Product ID's display value to `title`");
     remapDisplayValueToFK({
       display_value: ORDERS.PRODUCT_ID,
@@ -251,77 +209,40 @@ describe("scenarios > question > nested", () => {
       fk: PRODUCTS.TITLE,
     });
 
-    cy.createQuestion({
+    const baseQuestionDetails = {
       name: "Orders (remapped)",
-      query: { "source-table": ORDERS_ID },
-    });
+      query: { "source-table": ORDERS_ID, limit: 5 },
+    };
 
-    // Try to use saved question as a base for a new / nested question
-    startNewQuestion();
-    cy.findByText("Saved Questions").click();
-    cy.findByText("Orders (remapped)").click();
-
-    visualize(response => {
-      expect(response.body.error).not.to.exist;
-    });
+    createNestedQuestion({ baseQuestionDetails });
 
     cy.findAllByText("Awesome Concrete Shoes");
   });
 
-  ["remapped", "default"].forEach(test => {
-    describe(`${test.toUpperCase()} version: question with joins as a base for new quesiton(s) (metabase#14724)`, () => {
-      const QUESTION_NAME = "14724";
-      const SECOND_QUESTION_NAME = "14724_2";
-
-      beforeEach(() => {
-        if (test === "remapped") {
-          cy.log("Remap Product ID's display value to `title`");
-          remapDisplayValueToFK({
-            display_value: ORDERS.PRODUCT_ID,
-            name: "Product ID",
-            fk: PRODUCTS.TITLE,
-          });
-        }
-
-        cy.server();
-        cy.route("POST", "/api/dataset").as("dataset");
-      });
-
-      it("should handle single-level nesting", () => {
-        ordersJoinProducts(QUESTION_NAME);
-
-        // Start new question from a saved one
-        startNewQuestion();
-        cy.findByText("Saved Questions").click();
-        cy.findByText(QUESTION_NAME).click();
-
-        visualize(response => {
-          expect(response.body.error).not.to.exist;
+  it("nested questions based on a saved question with joins should work (metabase#14724)", () => {
+    const baseQuestionDetails = {
+      name: "14724",
+      query: ordersJoinProductsQuery,
+    };
+
+    ["default", "remapped"].forEach(scenario => {
+      if (scenario === "remapped") {
+        cy.log("Remap Product ID's display value to `title`");
+        remapDisplayValueToFK({
+          display_value: ORDERS.PRODUCT_ID,
+          name: "Product ID",
+          fk: PRODUCTS.TITLE,
         });
+      }
 
-        cy.contains("37.65");
-      });
-
-      it("should handle multi-level nesting", () => {
-        // Use the original question qith joins, then save it again
-        ordersJoinProducts(QUESTION_NAME).then(
-          ({ body: { id: ORIGINAL_QUESTION_ID } }) => {
-            cy.createQuestion({
-              name: SECOND_QUESTION_NAME,
-              query: { "source-table": `card__${ORIGINAL_QUESTION_ID}` },
-            });
-          },
-        );
+      // should hangle single-level nesting
+      createNestedQuestion({ baseQuestionDetails });
 
-        // Start new question from already saved nested question
-        startNewQuestion();
-        cy.findByText("Saved Questions").click();
-        cy.findByText(SECOND_QUESTION_NAME).click();
-
-        visualize(response => {
-          expect(response.body.error).not.to.exist;
-        });
+      cy.contains("37.65");
 
+      // should handle multi-level nesting
+      cy.get("@nestedQuestionId").then(id => {
+        visitNestedQueryAdHoc(id);
         cy.contains("37.65");
       });
     });
@@ -330,14 +251,14 @@ describe("scenarios > question > nested", () => {
   it("'distribution' should work on a joined table from a saved question (metabase#14787)", () => {
     // Set the display really wide and really tall to avoid any scrolling
     cy.viewport(1600, 1200);
+    cy.intercept("POST", "/api/dataset").as("dataset");
 
-    ordersJoinProducts("14787");
-    // This repro depends on these exact steps - it has to be opened from the saved questions
-    startNewQuestion();
-    cy.findByText("Saved Questions").click();
-    cy.findByText("14787").click();
+    const baseQuestionDetails = {
+      name: "14787",
+      query: ordersJoinProductsQuery,
+    };
 
-    visualize();
+    createNestedQuestion({ baseQuestionDetails });
 
     // The column title
     cy.findByText("Products → Category").click();
@@ -377,41 +298,32 @@ describe("scenarios > question > nested", () => {
     }
   });
 
-  ["count", "average"].forEach(test => {
-    it(`${test.toUpperCase()}:\n should be able to use aggregation functions on saved native question (metabase#15397)`, () => {
-      cy.createNativeQuestion(
-        {
-          name: "15397",
-          native: {
-            query:
-              "select count(*), orders.product_id from orders group by orders.product_id;",
-          },
-        },
-        { loadMetadata: true },
-      );
+  it("should be able to use aggregation functions on saved native question (metabase#15397)", () => {
+    cy.createNativeQuestion({
+      name: `15397`,
+      native: {
+        query:
+          "select count(*), orders.product_id from orders group by orders.product_id;",
+      },
+    }).then(({ body: { id } }) => {
+      visitQuestion(id);
 
-      startNewQuestion();
-      cy.findByText("Saved Questions").click();
-      cy.findByText("15397").click();
+      visitNestedQueryAdHoc(id);
 
-      visualize();
+      // Count
       summarize();
 
-      if (test === "average") {
-        cy.findByTestId("sidebar-right")
-          .should("be.visible")
-          .findByText("Count")
-          .click();
-        cy.findByText("Average of ...").click();
-        popover().findByText("COUNT(*)").click();
-        cy.wait("@dataset");
-      }
-
       cy.findByText("Group by").parent().findByText("COUNT(*)").click();
+      cy.wait("@dataset");
+
+      cy.get(".bar").should("have.length.of.at.least", 5);
+
+      // Replace "Count" with the "Average"
+      cy.findByTestId("aggregation-item").contains("Count").click();
+      cy.findByText("Average of ...").click();
+      popover().findByText("COUNT(*)").click();
+      cy.wait("@dataset");
 
-      cy.wait("@dataset").then(xhr => {
-        expect(xhr.response.body.error).not.to.exist;
-      });
       cy.get(".bar").should("have.length.of.at.least", 5);
     });
   });
@@ -451,28 +363,22 @@ describe("scenarios > question > nested", () => {
     });
 
     function assertOnFilter({ name, filter, value } = {}) {
-      cy.createQuestion(
-        {
-          name,
-          query: {
-            "source-table": ORDERS_ID,
-            filter,
-            aggregation: [["count"]],
-          },
-          type: "query",
-          display: "scalar",
+      cy.createQuestion({
+        name,
+        query: {
+          "source-table": ORDERS_ID,
+          filter,
+          aggregation: [["count"]],
         },
-        { visitQuestion: true },
-      );
-
-      cy.get(".ScalarValue").findByText(value);
+        type: "query",
+        display: "scalar",
+      }).then(({ body: { id } }) => {
+        visitQuestion(id);
+        cy.get(".ScalarValue").findByText(value);
 
-      // Start new question based on the saved one
-      startNewQuestion();
-      cy.findByText("Saved Questions").click();
-      cy.findByText(name).click();
-      visualize();
-      cy.get(".ScalarValue").findByText(value);
+        visitNestedQueryAdHoc(id);
+        cy.get(".ScalarValue").findByText(value);
+      });
     }
   });
 
@@ -535,16 +441,38 @@ describe("scenarios > question > nested", () => {
     });
   });
 
-  it("should be able to use integer filter on a nested query based on a saved native question (metabase#15808)", () => {
-    cy.createNativeQuestion({
+  it("should properly work with native questions (metabsae#15808, metabase#16938, metabase#18364)", () => {
+    const questionDetails = {
       name: "15808",
-      native: { query: "select * from products" },
+      native: { query: "select * from products limit 5" },
+    };
+
+    cy.intercept("POST", "/api/dataset").as("dataset");
+
+    cy.createNativeQuestion(questionDetails, { visitQuestion: true });
+
+    cy.findByText("Explore results").click();
+    cy.wait("@dataset");
+
+    // should allow to browse object details when exploring native query results (metabase#16938)
+    cy.get(".Table-ID")
+      .as("primaryKeys")
+      .should("have.length", 5)
+      .first()
+      .click();
+
+    cy.findByTestId("object-detail").within(() => {
+      cy.findByText("Swaniawski, Casper and Hilll");
     });
-    startNewQuestion();
-    cy.findByText("Saved Questions").click();
-    cy.findByText("15808").click();
-    visualize();
 
+    // Close the modal (until we implement the "X" button in the modal itself)
+    cy.get("body").click("bottomRight");
+    cy.get(".Modal").should("not.exist");
+
+    // should be able to save a nested question (metabase#18364)
+    saveQuestion();
+
+    // should be able to use integer filter on a nested query based on a saved native question (metabase#15808)
     filter();
     filterField("RATING", {
       operator: "Equal to",
@@ -554,26 +482,112 @@ describe("scenarios > question > nested", () => {
 
     cy.findByText("Synergistic Granite Chair");
     cy.findByText("Rustic Paper Wallet").should("not.exist");
+
+    function saveQuestion() {
+      cy.intercept("POST", "/api/card").as("cardCreated");
+
+      cy.findByText("Save").click({ force: true });
+      cy.get(".Modal").button("Save").click();
+
+      cy.wait("@cardCreated").then(({ response: { body } }) => {
+        expect(body.error).not.to.exist;
+      });
+
+      cy.button("Failed").should("not.exist");
+      cy.findByText("Not now").click();
+    }
+  });
+
+  it("should create a nested question with post-aggregation filter (metabase#11561)", () => {
+    visitQuestionAdhoc({
+      dataset_query: {
+        database: SAMPLE_DB_ID,
+        query: {
+          "source-table": ORDERS_ID,
+          aggregation: [["count"]],
+          breakout: [["field", PEOPLE.ID, { "source-field": ORDERS.USER_ID }]],
+        },
+        type: "query",
+      },
+    });
+
+    cy.findByText("Filter").click();
+    cy.findByText("Summaries").click();
+    cy.findByTestId("operator-select").click();
+    popover().contains("Equal to").click();
+    cy.findByPlaceholderText("Enter a number").type("5");
+    cy.button("Apply Filters").click();
+    cy.wait("@dataset");
+
+    cy.findByText("Count is equal to 5");
+    cy.findByText("Showing 100 rows");
+
+    saveQuestion();
+
+    reloadQuestion();
+    cy.findByText("Showing 100 rows");
+
+    cy.icon("notebook").click();
+    cy.findAllByTestId("notebook-cell-item").contains(/Users? → ID/);
+
+    function saveQuestion() {
+      cy.intercept("POST", "/api/card").as("cardCreated");
+
+      cy.findByText("Save").click();
+
+      cy.get(".Modal").within(() => {
+        cy.findByLabelText("Name").type("Q").blur();
+        cy.button("Save").click();
+      });
+
+      cy.wait("@cardCreated");
+      cy.findByText("Not now").click();
+    }
+
+    function reloadQuestion() {
+      cy.intercept("POST", "/api/card/*/query").as("cardQuery");
+      cy.reload();
+      cy.wait("@cardQuery");
+    }
   });
 });
 
-function ordersJoinProducts(name) {
-  return cy.createQuestion({
-    name,
-    query: {
-      "source-table": ORDERS_ID,
-      joins: [
-        {
-          fields: "all",
-          "source-table": PRODUCTS_ID,
-          condition: [
-            "=",
-            ["field", ORDERS.PRODUCT_ID, null],
-            ["field", PRODUCTS.ID, { "join-alias": "Products" }],
-          ],
-          alias: "Products",
+function createNestedQuestion(
+  { baseQuestionDetails, nestedQuestionDetails },
+  { loadBaseQuestionMetadata = false, visitNestedQuestion = true } = {},
+) {
+  createBaseQuestion(baseQuestionDetails).then(({ body: { id } }) => {
+    loadBaseQuestionMetadata && visitQuestion(id);
+
+    return cy.createQuestion(
+      {
+        name: "Nested Question",
+        query: {
+          "source-table": `card__${id}`,
         },
-      ],
+        ...nestedQuestionDetails,
+      },
+      {
+        visitQuestion: visitNestedQuestion,
+        wrapId: true,
+        idAlias: "nestedQuestionId",
+      },
+    );
+  });
+
+  function createBaseQuestion(query) {
+    return query.native
+      ? cy.createNativeQuestion(query)
+      : cy.createQuestion(query);
+  }
+}
+
+function visitNestedQueryAdHoc(id) {
+  return visitQuestionAdhoc({
+    dataset_query: {
+      database: SAMPLE_DB_ID,
+      type: "query",
+      query: { "source-table": `card__${id}` },
     },
   });
 }
diff --git a/frontend/test/metabase/scenarios/question/notebook.cy.spec.js b/frontend/test/metabase/scenarios/question/notebook.cy.spec.js
index 7f3d0482d49..18ffd4fe9e9 100644
--- a/frontend/test/metabase/scenarios/question/notebook.cy.spec.js
+++ b/frontend/test/metabase/scenarios/question/notebook.cy.spec.js
@@ -1,7 +1,6 @@
 import {
   enterCustomColumnDetails,
   getNotebookStep,
-  modal,
   openOrdersTable,
   openProductsTable,
   popover,
@@ -242,50 +241,6 @@ describe("scenarios > question > notebook", () => {
     });
   });
 
-  describe("nested", () => {
-    it("should create a nested question with post-aggregation filter", () => {
-      openProductsTable({ mode: "notebook" });
-
-      summarize({ mode: "notebook" });
-      popover().within(() => {
-        cy.findByText("Count of rows").click();
-      });
-
-      cy.findByText("Pick a column to group by").click();
-      popover().within(() => {
-        cy.findByText("Category").click();
-      });
-
-      cy.findByText("Filter").click();
-      popover().within(() => {
-        cy.findByText("Category").click();
-        cy.findByText("Gadget").click();
-        cy.findByText("Add filter").click();
-      });
-
-      visualize();
-
-      cy.findByText("Gadget").should("exist");
-      cy.findByText("Gizmo").should("not.exist");
-
-      cy.findByText("Save").click();
-
-      modal().within(() => {
-        cy.findByLabelText("Name").type("post aggregation");
-        cy.findByText("Save").click();
-      });
-
-      cy.findByText("Not now").click();
-
-      cy.icon("notebook").click();
-
-      cy.reload();
-
-      cy.findByText("Category").should("exist");
-      cy.findByText("Category is Gadget").should("exist");
-    });
-  });
-
   describe("arithmetic (metabase#13175)", () => {
     beforeEach(() => {
       openOrdersTable({ mode: "notebook" });
diff --git a/frontend/test/metabase/scenarios/question/reproductions/16938-nested-native-query-pk-drill.cy.spec.js b/frontend/test/metabase/scenarios/question/reproductions/16938-nested-native-query-pk-drill.cy.spec.js
deleted file mode 100644
index 04734853d82..00000000000
--- a/frontend/test/metabase/scenarios/question/reproductions/16938-nested-native-query-pk-drill.cy.spec.js
+++ /dev/null
@@ -1,36 +0,0 @@
-import { restore } from "__support__/e2e/helpers";
-
-describe("issue 16938", () => {
-  beforeEach(() => {
-    restore();
-    cy.signInAsAdmin();
-    cy.intercept("POST", "/api/dataset").as("dataset");
-  });
-
-  it("should allow to browse object details when exploring native query results (metabase#16938)", () => {
-    const ORDER_ID = 1;
-
-    cy.createNativeQuestion(
-      {
-        name: "Orders",
-        native: {
-          query: "select * from orders",
-        },
-      },
-      { visitQuestion: true },
-    );
-
-    cy.button(/Explore results/i).click();
-    cy.wait("@dataset");
-
-    getFirstTableColumn().eq(1).should("contain", ORDER_ID).click();
-
-    cy.findByTestId("object-detail").within(() => {
-      cy.findByText("37.65");
-    });
-  });
-});
-
-function getFirstTableColumn() {
-  return cy.get(".TableInteractive-cellWrapper--firstColumn");
-}
-- 
GitLab