Skip to content

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

Move data model error-handling coverage from e2e to unit tests (#82953)

Nemanja Glumac735aef353920
diff --git a/e2e/test/scenarios/data-model/data-model-shared-4.cy.spec.ts b/e2e/test/scenarios/data-model/data-model-shared-4.cy.spec.ts
index c55b479820c..76094bc121e 100644
--- a/e2e/test/scenarios/data-model/data-model-shared-4.cy.spec.ts
+++ b/e2e/test/scenarios/data-model/data-model-shared-4.cy.spec.ts
@@ -6,8 +6,7 @@ import {
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
const { H } = cy;
-const { TablePicker, TableSection, FieldSection, PreviewSection, Shared } =
- cy.H.DataModel;
+const { TablePicker, TableSection, FieldSection, Shared } = cy.H.DataModel;
const { ORDERS_ID, ORDERS } = SAMPLE_DATABASE;
const { visitArea } = Shared;
@@ -49,200 +48,6 @@ areas.forEach((area) => {
}
});
- describe("Error handling", { tags: "@external" }, () => {
- beforeEach(() => {
- H.restore("postgres-writable");
- H.resetTestTable({ type: "postgres", table: "many_data_types" });
- cy.signInAsAdmin();
- H.resyncDatabase({
- dbId: WRITABLE_DB_ID,
- tableName: "many_data_types",
- });
-
- const error = { statusCode: 500 };
- cy.intercept("POST", "/api/dataset*", error);
- cy.intercept("PUT", "/api/field/*", error);
- cy.intercept("PUT", "/api/table/*/fields/order", error);
- cy.intercept("POST", "/api/field/*/values", error);
- cy.intercept("POST", "/api/field/*/dimension", error);
- cy.intercept("PUT", "/api/table/*", error);
- if (area === "admin") {
- cy.intercept("POST", "/api/table/*/sync_schema", error);
- cy.intercept("POST", "/api/table/*/rescan_values", error);
- cy.intercept("POST", "/api/table/*/discard_values", error);
- } else {
- cy.intercept("POST", "/api/data-studio/table/sync-schema", error);
- cy.intercept("POST", "/api/data-studio/table/rescan-values", error);
- cy.intercept("POST", "/api/data-studio/table/discard-values", error);
- }
- });
-
- it("shows toast errors and preview errors", () => {
- visit({
- databaseId: SAMPLE_DB_ID,
- schemaId: SAMPLE_DB_SCHEMA_ID,
- tableId: ORDERS_ID,
- fieldId: ORDERS.QUANTITY,
- });
-
- cy.log("table section");
-
- if (area === "data studio") {
- TableSection.clickDetailsTab();
- }
- cy.log("name");
- TableSection.getNameInput().type("a").blur();
- verifyAndCloseToast("Failed to update table name");
-
- cy.log("description");
- TableSection.getDescriptionInput().type("a").blur();
- verifyAndCloseToast("Failed to update table description");
-
- if (area === "data studio") {
- TableSection.clickFieldsTab();
- // cy.pause();
- }
- cy.log("predefined field order");
- TableSection.getSortButton().click();
- TableSection.getSortOrderInput()
- .findByLabelText("Alphabetical order")
- .click();
- verifyAndCloseToast("Failed to update field order");
-
- cy.log("custom field order");
- TableSection.getSortableField("ID").as("dragElement");
- H.moveDnDKitElementByAlias("@dragElement", {
- vertical: 50,
- });
- verifyAndCloseToast("Failed to update field order");
- TableSection.get().button("Done").click();
-
- if (area === "data studio") {
- TableSection.clickDetailsTab();
- }
- cy.log("sync");
-
- if (area === "data studio") {
- TableSection.getActionsMenuButton().click();
- H.popover().findByText("Re-sync schema").click();
- } else {
- TableSection.getSyncOptionsButton().click();
- H.modal().button("Sync table schema").click();
- }
- verifyAndCloseToast("Failed to start sync");
-
- if (area === "data studio") {
- TableSection.getActionsMenuButton().click();
- H.popover().findByText("Re-scan field values").click();
- } else {
- H.modal().button("Re-scan table").click();
- }
- verifyAndCloseToast("Failed to start scan");
-
- if (area === "data studio") {
- TableSection.getActionsMenuButton().click();
- H.popover().findByText("Discard cached field values").click();
- } else {
- H.modal().button("Discard cached field values").click();
- }
-
- verifyAndCloseToast("Failed to discard values");
- if (area === "admin") {
- // synthetic escape: realPress depends on real browser focus, which
- // the app may not hold in CI, so the keystroke can miss the modal
- cy.get("body").type("{esc}");
- H.modal().should("not.exist");
- }
-
- if (area === "data studio") {
- TableSection.clickFieldsTab();
- }
- cy.log("field name");
- TableSection.getFieldNameInput("Quantity").type("a").blur();
- verifyAndCloseToast("Failed to update name of Quantity");
-
- cy.log("field description");
- TableSection.getFieldDescriptionInput("Quantity").type("a").blur();
- verifyAndCloseToast("Failed to update description of Quantity");
-
- cy.log("field section");
- TableSection.clickField("Quantity");
- cy.log("name");
- FieldSection.getNameInput().type("a").blur();
- verifyAndCloseToast("Failed to update name of Quantity");
-
- cy.log("description");
- FieldSection.getDescriptionInput().type("a").blur();
- verifyAndCloseToast("Failed to update description of Quantity");
-
- cy.log("coercion strategy");
- FieldSection.getCoercionToggle().parent().scrollIntoView().click();
- H.popover()
- .findByText("UNIX seconds → Datetime")
- .scrollIntoView()
- .click();
- verifyAndCloseToast("Failed to enable casting for Quantity");
-
- cy.log("semantic type");
- FieldSection.getSemanticTypeInput().click();
- H.popover().findByText("Score").click();
- verifyAndCloseToast("Failed to update semantic type of Quantity");
-
- cy.log("visibility");
- FieldSection.getVisibilityInput().click();
- H.popover().findByText("Only in detail views").click();
- verifyAndCloseToast("Failed to update visibility of Quantity");
-
- cy.log("filtering");
- FieldSection.getFilteringInput().click();
- H.popover().findByText("Search box").click();
- verifyAndCloseToast("Failed to update filtering of Quantity");
-
- cy.log("display values");
- FieldSection.getDisplayValuesInput().click();
- H.popover().findByText("Custom mapping").click();
- verifyAndCloseToast("Failed to update display values of Quantity");
-
- cy.log("JSON unfolding");
- // navigating away would cause onChange to be triggered in InputBlurChange and TextareaBlurChange
- // components, so new undos will appear - this makes this test flaky, so we navigate with page reload instead
- visit({ databaseId: WRITABLE_DB_ID });
- TablePicker.getTable("Many Data Types").click();
- if (area === "data studio") {
- TableSection.clickFieldsTab();
- }
- TableSection.clickField("Json");
- FieldSection.getUnfoldJsonInput().click();
- H.popover().findByText("No").click();
- verifyAndCloseToast("Failed to disable JSON unfolding for Json");
-
- cy.log("formatting");
- TablePicker.getDatabase("Sample Database").click();
- TablePicker.getTable("Orders").click();
- if (area === "data studio") {
- TableSection.clickFieldsTab();
- }
- TableSection.clickField("Quantity");
- FieldSection.getPrefixInput().type("5").blur();
- verifyAndCloseToast("Failed to update formatting of Quantity");
-
- cy.log("preview section");
-
- cy.log("table preview");
- FieldSection.getPreviewButton().click();
- PreviewSection.get()
- .scrollIntoView()
- .findByText("Something went wrong")
- .should("be.visible");
-
- cy.log("object detail preview");
- PreviewSection.getPreviewTypeInput().findByText("Detail").click();
- PreviewSection.get()
- .findByText("Something went wrong")
- .should("be.visible");
- });
- });
-
describe("Undos", { tags: "@external" }, () => {
beforeEach(() => {
H.restore("postgres-writable");
@@ -410,10 +215,7 @@ areas.forEach((area) => {
// The in-test DB switch via picker (.getDatabase().click() then
// .getTable().click()) races the picker re-render: the table click can
// land before the writable DB tables list is interactive, so the click
- // never propagates to a URL change. The "Error handling" sibling above
- // hit the same flake and was fixed by using visit({ databaseId:
- // WRITABLE_DB_ID }) (which waits for picker bootstrap). Same pattern
- // here.
+ // never propagates to a URL change. visit() waits for picker bootstrap.
visit({ databaseId: WRITABLE_DB_ID });
TablePicker.getTable("Many Data Types").click();
if (area === "data studio") {
diff --git a/frontend/src/metabase/data-studio/data-model/components/TableSection/components/TableActionsMenu/TableActionsMenu.unit.spec.tsx b/frontend/src/metabase/data-studio/data-model/components/TableSection/components/TableActionsMenu/TableActionsMenu.unit.spec.tsx
index d27c912de6a..a2b75142a9f 100644
--- a/frontend/src/metabase/data-studio/data-model/components/TableSection/components/TableActionsMenu/TableActionsMenu.unit.spec.tsx
+++ b/frontend/src/metabase/data-studio/data-model/components/TableSection/components/TableActionsMenu/TableActionsMenu.unit.spec.tsx
@@ -1,10 +1,14 @@
import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
import { setupEnterprisePlugins } from "__support__/enterprise";
-import { setupListSourceReplacementRunsEndpoint } from "__support__/server-mocks";
+import {
+ setupListSourceReplacementRunsEndpoint,
+ setupTablesBulkEndpoints,
+} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { createMockState } from "__support__/state";
-import { renderWithProviders, screen } from "__support__/ui";
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
import { Route } from "metabase/router";
import type { Table } from "metabase-types/api";
import {
@@ -23,6 +27,7 @@ interface SetupOpts {
function setup({ table, isAdmin = false }: SetupOpts) {
setupListSourceReplacementRunsEndpoint([]);
+ setupTablesBulkEndpoints();
const state = createMockState({
currentUser: createMockUser({ is_superuser: isAdmin }),
@@ -37,7 +42,7 @@ function setup({ table, isAdmin = false }: SetupOpts) {
renderWithProviders(
<Route path="/" element={<TableActionsMenu table={table} />} />,
- { storeInitialState: state, withRouter: true },
+ { storeInitialState: state, withRouter: true, withUndos: true },
);
}
@@ -108,4 +113,43 @@ describe("TableActionsMenu", () => {
screen.queryByRole("menuitem", { name: /Re-sync schema/ }),
).not.toBeInTheDocument();
});
+
+ describe("error handling", () => {
+ it.each([
+ {
+ item: "Re-sync schema",
+ route: "tables-sync-schema",
+ message: "Failed to start sync",
+ },
+ {
+ item: "Re-scan field values",
+ route: "tables-rescan-values",
+ message: "Failed to start scan",
+ },
+ {
+ item: "Discard cached field values",
+ route: "tables-discard-values",
+ message: "Failed to discard values",
+ },
+ ])(
+ "shows an error toast when $item fails",
+ async ({ item, route, message }) => {
+ setup({ table: createMockTable({ db: createMockDatabase() }) });
+ fetchMock.modifyRoute(route, { response: { status: 500 } });
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "More actions" }),
+ );
+ await userEvent.click(
+ await screen.findByRole("menuitem", { name: new RegExp(item) }),
+ );
+
+ await waitFor(() => {
+ expect(
+ within(screen.getByTestId("undo-list")).getByText(message),
+ ).toBeInTheDocument();
+ });
+ },
+ );
+ });
});
diff --git a/frontend/src/metabase/metadata/components/FieldSection/FieldSection.unit.spec.tsx b/frontend/src/metabase/metadata/components/FieldSection/FieldSection.unit.spec.tsx
new file mode 100644
index 00000000000..62f90b6eb75
--- /dev/null
+++ b/frontend/src/metabase/metadata/components/FieldSection/FieldSection.unit.spec.tsx
@@ -0,0 +1,237 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ setupDatabaseEndpoints,
+ setupFieldValuesEndpoint,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
+import { UndoListing } from "metabase/common/components/UndoListing";
+import { getRawTableFieldId } from "metabase/metadata/utils/field";
+import { registerVisualizations } from "metabase/visualizations/register";
+import type { Database, Field, Table } from "metabase-types/api";
+import {
+ createMockDatabase,
+ createMockField,
+ createMockFieldValues,
+ createMockTable,
+} from "metabase-types/api/mocks";
+import {
+ createOrdersQuantityField,
+ createOrdersTable,
+ createSampleDatabase,
+} from "metabase-types/api/mocks/presets";
+
+import { FieldSection } from "./FieldSection";
+
+registerVisualizations();
+
+const QUANTITY_FIELD = createOrdersQuantityField();
+
+const ORDERS_TABLE = createOrdersTable({ fields: [QUANTITY_FIELD] });
+
+const SAMPLE_DB = createSampleDatabase({ tables: [ORDERS_TABLE] });
+
+const JSON_FIELD = createMockField({
+ id: 100,
+ name: "JSON",
+ display_name: "Json",
+ base_type: "type/JSON",
+ json_unfolding: true,
+});
+
+const JSON_TABLE = createMockTable({
+ id: 100,
+ db_id: 100,
+ fields: [JSON_FIELD],
+});
+
+const JSON_DB = createMockDatabase({
+ id: 100,
+ tables: [JSON_TABLE],
+ features: ["nested-field-columns"],
+});
+
+type SetupOpts = {
+ field?: Field;
+ table?: Table;
+ database?: Database;
+ fieldValues?: [number, string][];
+};
+
+function setup({
+ field = QUANTITY_FIELD,
+ table = ORDERS_TABLE,
+ database = SAMPLE_DB,
+ fieldValues = [
+ [1, "1 remapped"],
+ [2, "2 remapped"],
+ ],
+}: SetupOpts = {}) {
+ const id = getRawTableFieldId(field);
+
+ setupDatabaseEndpoints(database);
+ setupFieldValuesEndpoint(
+ createMockFieldValues({ field_id: id, values: fieldValues }),
+ );
+ fetchMock.post(
+ `path:/api/field/${id}/dimension`,
+ {},
+ { name: `field-${id}-dimension` },
+ );
+
+ renderWithProviders(
+ <>
+ <FieldSection
+ field={field}
+ table={table}
+ getFieldHref={(fieldId) => `/field/${fieldId}`}
+ onFieldValuesClick={jest.fn()}
+ onPreviewClick={jest.fn()}
+ onTrackMetadataChange={jest.fn()}
+ />
+ <UndoListing />
+ </>,
+ );
+}
+
+/**
+ * Every field setting in this section persists through PUT /api/field/:id, so
+ * failing that one route exercises each handler's error branch.
+ */
+function failFieldUpdates(field: Field = QUANTITY_FIELD) {
+ fetchMock.modifyRoute(`field-${getRawTableFieldId(field)}-put`, {
+ response: { status: 500 },
+ });
+}
+
+async function assertErrorToast(message: string) {
+ await waitFor(() => {
+ expect(
+ within(screen.getByTestId("undo-list")).getByText(message),
+ ).toBeInTheDocument();
+ });
+}
+
+async function selectOption(input: HTMLElement, name: string) {
+ await userEvent.click(input);
+ const listbox = within(await screen.findByRole("listbox"));
+ await userEvent.click(listbox.getByText(name));
+}
+
+describe("FieldSection", () => {
+ describe("error handling", () => {
+ it("shows an error toast when renaming the field fails", async () => {
+ setup();
+ failFieldUpdates();
+
+ await userEvent.type(
+ screen.getByPlaceholderText("Give this field a name"),
+ "a",
+ );
+ await userEvent.tab();
+
+ await assertErrorToast("Failed to update name of Quantity");
+ });
+
+ it("shows an error toast when updating the field description fails", async () => {
+ setup();
+ failFieldUpdates();
+
+ await userEvent.type(
+ screen.getByPlaceholderText("Give this field a description"),
+ "a",
+ );
+ await userEvent.tab();
+
+ await assertErrorToast("Failed to update description of Quantity");
+ });
+
+ it("shows an error toast when enabling casting fails", async () => {
+ setup();
+ failFieldUpdates();
+
+ // the toggle opens the strategy picker itself
+ await userEvent.click(
+ screen.getByLabelText("Cast to a specific data type"),
+ );
+ const listbox = within(await screen.findByRole("listbox"));
+ await userEvent.click(listbox.getByText("UNIX seconds → Datetime"));
+
+ await assertErrorToast("Failed to enable casting for Quantity");
+ });
+
+ it("shows an error toast when updating the semantic type fails", async () => {
+ setup();
+ failFieldUpdates();
+
+ await selectOption(
+ screen.getByPlaceholderText("Select a semantic type"),
+ "Score",
+ );
+
+ await assertErrorToast("Failed to update semantic type of Quantity");
+ });
+
+ it("shows an error toast when updating visibility fails", async () => {
+ setup();
+ failFieldUpdates();
+
+ await selectOption(
+ screen.getByPlaceholderText("Select a field visibility"),
+ "Only in detail views",
+ );
+
+ await assertErrorToast("Failed to update visibility of Quantity");
+ });
+
+ it("shows an error toast when updating filtering fails", async () => {
+ setup();
+ failFieldUpdates();
+
+ await selectOption(
+ screen.getByPlaceholderText("Select field filtering"),
+ "Search box",
+ );
+
+ await assertErrorToast("Failed to update filtering of Quantity");
+ });
+
+ it("shows an error toast when updating display values fails", async () => {
+ setup();
+ fetchMock.modifyRoute(`field-${QUANTITY_FIELD.id}-dimension`, {
+ response: { status: 500 },
+ });
+
+ // RemappingPicker renders only once the database query resolves
+ await selectOption(
+ await screen.findByPlaceholderText("Select display values"),
+ "Custom mapping",
+ );
+
+ await assertErrorToast("Failed to update display values of Quantity");
+ });
+
+ it("shows an error toast when disabling JSON unfolding fails", async () => {
+ setup({ field: JSON_FIELD, table: JSON_TABLE, database: JSON_DB });
+ failFieldUpdates(JSON_FIELD);
+
+ await selectOption(
+ await screen.findByPlaceholderText("Select whether to unfold JSON"),
+ "No",
+ );
+
+ await assertErrorToast("Failed to disable JSON unfolding for Json");
+ });
+
+ it("shows an error toast when updating formatting fails", async () => {
+ setup();
+ failFieldUpdates();
+
+ await userEvent.type(screen.getByTestId("prefix"), "5");
+ await userEvent.tab();
+
+ await assertErrorToast("Failed to update formatting of Quantity");
+ });
+ });
+});
diff --git a/frontend/src/metabase/metadata/components/PreviewSection/PreviewSection.unit.spec.tsx b/frontend/src/metabase/metadata/components/PreviewSection/PreviewSection.unit.spec.tsx
index 516e072162d..4e54f8c0557 100644
--- a/frontend/src/metabase/metadata/components/PreviewSection/PreviewSection.unit.spec.tsx
+++ b/frontend/src/metabase/metadata/components/PreviewSection/PreviewSection.unit.spec.tsx
@@ -2,11 +2,14 @@ import userEvent from "@testing-library/user-event";
import { useState } from "react";
import { setupCardDataset } from "__support__/server-mocks";
+import { createMockState } from "__support__/state";
+import { createMockEntitiesState } from "__support__/store";
import { renderWithProviders, screen } from "__support__/ui";
import { registerVisualizations } from "metabase/visualizations/register";
import {
createOrdersTable,
createOrdersTotalField,
+ createSampleDatabase,
} from "metabase-types/api/mocks/presets";
import { PreviewSection } from "./PreviewSection";
@@ -40,13 +43,22 @@ function TestComponent({
);
}
-function setup() {
- setupCardDataset();
+function setup({ status = 200 }: { status?: number } = {}) {
+ setupCardDataset({ status });
const onPreviewTypeChange = jest.fn();
renderWithProviders(
<TestComponent onPreviewTypeChange={onPreviewTypeChange} />,
+ {
+ // the preview query is built from the metadata store, so an empty store
+ // means no request is ever issued
+ storeInitialState: createMockState({
+ entities: createMockEntitiesState({
+ databases: [createSampleDatabase()],
+ }),
+ }),
+ },
);
return { onPreviewTypeChange };
@@ -65,4 +77,20 @@ describe("PreviewSection", () => {
await userEvent.click(screen.getByLabelText("Table"));
expect(onPreviewTypeChange).toHaveBeenCalledWith("table");
});
+
+ describe("error handling", () => {
+ it("shows an error in the table preview when the query fails", async () => {
+ setup({ status: 500 });
+
+ expect(await screen.findByText("Something went wrong")).toBeVisible();
+ });
+
+ it("shows an error in the object detail preview when the query fails", async () => {
+ setup({ status: 500 });
+
+ await userEvent.click(screen.getByLabelText("Detail"));
+
+ expect(await screen.findByText("Something went wrong")).toBeVisible();
+ });
+ });
});
diff --git a/frontend/src/metabase/metadata/components/TableFieldList/TableFieldList.unit.spec.tsx b/frontend/src/metabase/metadata/components/TableFieldList/TableFieldList.unit.spec.tsx
new file mode 100644
index 00000000000..95bbee1917f
--- /dev/null
+++ b/frontend/src/metabase/metadata/components/TableFieldList/TableFieldList.unit.spec.tsx
@@ -0,0 +1,74 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { setupTableEndpoints } from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
+import { UndoListing } from "metabase/common/components/UndoListing";
+import {
+ createOrdersQuantityField,
+ createOrdersTable,
+} from "metabase-types/api/mocks/presets";
+
+import { TableFieldList } from "./TableFieldList";
+
+const QUANTITY_FIELD = createOrdersQuantityField();
+
+const ORDERS_TABLE = createOrdersTable({ fields: [QUANTITY_FIELD] });
+
+function setup() {
+ setupTableEndpoints(ORDERS_TABLE);
+
+ renderWithProviders(
+ <>
+ <TableFieldList
+ table={ORDERS_TABLE}
+ getFieldHref={(fieldId) => `/field/${fieldId}`}
+ />
+ <UndoListing />
+ </>,
+ );
+
+ fetchMock.modifyRoute(`field-${QUANTITY_FIELD.id}-put`, {
+ response: { status: 500 },
+ });
+}
+
+function getField(name: string) {
+ return within(screen.getByRole("listitem", { name }));
+}
+
+async function assertErrorToast(message: string) {
+ await waitFor(() => {
+ expect(
+ within(screen.getByTestId("undo-list")).getByText(message),
+ ).toBeInTheDocument();
+ });
+}
+
+describe("TableFieldList", () => {
+ describe("error handling", () => {
+ it("shows an error toast when renaming a field fails", async () => {
+ setup();
+
+ await userEvent.type(
+ getField("Quantity").getByPlaceholderText("Give this field a name"),
+ "a",
+ );
+ await userEvent.tab();
+
+ await assertErrorToast("Failed to update name of Quantity");
+ });
+
+ it("shows an error toast when updating a field description fails", async () => {
+ setup();
+
+ await userEvent.type(
+ getField("Quantity").getByPlaceholderText("No description yet"),
+ "a",
+ );
+ await userEvent.tab();
+
+ await assertErrorToast("Failed to update description of Quantity");
+ });
+ });
+});
diff --git a/frontend/src/metabase/metadata/components/TableSection/TableSection.unit.spec.tsx b/frontend/src/metabase/metadata/components/TableSection/TableSection.unit.spec.tsx
index 87a2ec7a262..938065569a2 100644
--- a/frontend/src/metabase/metadata/components/TableSection/TableSection.unit.spec.tsx
+++ b/frontend/src/metabase/metadata/components/TableSection/TableSection.unit.spec.tsx
@@ -1,10 +1,23 @@
-import { renderWithProviders, screen } from "__support__/ui";
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { setupTableEndpoints } from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
+import { UndoListing } from "metabase/common/components/UndoListing";
import { Route } from "metabase/router";
import type { FieldId, Table } from "metabase-types/api";
import { createMockDatabase, createMockTable } from "metabase-types/api/mocks";
+import {
+ createOrdersQuantityField,
+ createOrdersTable,
+} from "metabase-types/api/mocks/presets";
import { TableSection } from "./TableSection";
+const ORDERS_TABLE = createOrdersTable({
+ fields: [createOrdersQuantityField()],
+});
+
type SetupOpts = {
table?: Table;
fieldId?: FieldId;
@@ -13,17 +26,22 @@ type SetupOpts = {
function setup({ table = createMockTable(), fieldId }: SetupOpts = {}) {
const onSyncOptionsClick = jest.fn();
+ setupTableEndpoints(table);
+
renderWithProviders(
<Route
path="/"
element={
- <TableSection
- table={table}
- fieldId={fieldId}
- withName
- getFieldHref={(fieldId) => `/field/${fieldId}`}
- onSyncOptionsClick={onSyncOptionsClick}
- />
+ <>
+ <TableSection
+ table={table}
+ fieldId={fieldId}
+ withName
+ getFieldHref={(fieldId) => `/field/${fieldId}`}
+ onSyncOptionsClick={onSyncOptionsClick}
+ />
+ <UndoListing />
+ </>
}
/>,
{ withRouter: true },
@@ -32,6 +50,14 @@ function setup({ table = createMockTable(), fieldId }: SetupOpts = {}) {
return { onSyncOptionsClick };
}
+async function assertErrorToast(message: string) {
+ await waitFor(() => {
+ expect(
+ within(screen.getByTestId("undo-list")).getByText(message),
+ ).toBeInTheDocument();
+ });
+}
+
describe("TableSection", () => {
it("should render the link to explore this table in the query builder", () => {
const table = createMockTable();
@@ -51,4 +77,48 @@ describe("TableSection", () => {
setup({ table });
expect(screen.queryByText("Sync options")).not.toBeInTheDocument();
});
+
+ describe("error handling", () => {
+ it("shows an error toast when updating the table name fails", async () => {
+ setup({ table: ORDERS_TABLE });
+ fetchMock.modifyRoute(`table-${ORDERS_TABLE.id}-put`, {
+ response: { status: 500 },
+ });
+
+ await userEvent.type(
+ screen.getByPlaceholderText("Give this table a name"),
+ "a",
+ );
+ await userEvent.tab();
+
+ await assertErrorToast("Failed to update table name");
+ });
+
+ it("shows an error toast when updating the table description fails", async () => {
+ setup({ table: ORDERS_TABLE });
+ fetchMock.modifyRoute(`table-${ORDERS_TABLE.id}-put`, {
+ response: { status: 500 },
+ });
+
+ await userEvent.type(
+ screen.getByPlaceholderText("Give this table a description"),
+ "a",
+ );
+ await userEvent.tab();
+
+ await assertErrorToast("Failed to update table description");
+ });
+
+ it("shows an error toast when updating the field order fails", async () => {
+ setup({ table: ORDERS_TABLE });
+ fetchMock.modifyRoute(`table-${ORDERS_TABLE.id}-put`, {
+ response: { status: 500 },
+ });
+
+ await userEvent.click(screen.getByRole("button", { name: /Sorting/ }));
+ await userEvent.click(screen.getByLabelText("Alphabetical order"));
+
+ await assertErrorToast("Failed to update field order");
+ });
+ });
});
diff --git a/frontend/src/metabase/metadata/hooks/use-table-update-handlers.unit.spec.tsx b/frontend/src/metabase/metadata/hooks/use-table-update-handlers.unit.spec.tsx
new file mode 100644
index 00000000000..d8ba240734c
--- /dev/null
+++ b/frontend/src/metabase/metadata/hooks/use-table-update-handlers.unit.spec.tsx
@@ -0,0 +1,58 @@
+import fetchMock from "fetch-mock";
+
+import { setupTableEndpoints } from "__support__/server-mocks";
+import {
+ renderHookWithProviders,
+ screen,
+ waitFor,
+ within,
+} from "__support__/ui";
+import { getRawTableFieldId } from "metabase/metadata/utils/field";
+import {
+ createOrdersIdField,
+ createOrdersQuantityField,
+ createOrdersTable,
+} from "metabase-types/api/mocks/presets";
+
+import { useTableUpdateHandlers } from "./use-table-update-handlers";
+
+const ORDERS_TABLE = createOrdersTable({
+ fields: [createOrdersIdField(), createOrdersQuantityField()],
+});
+
+/**
+ * The sortable field list drives this handler through a dnd-kit PointerSensor,
+ * which jsdom cannot simulate, so the handler is exercised directly.
+ */
+function setup() {
+ setupTableEndpoints(ORDERS_TABLE);
+
+ const { result } = renderHookWithProviders(
+ () => useTableUpdateHandlers({ table: ORDERS_TABLE }),
+ { withUndos: true },
+ );
+
+ return result;
+}
+
+describe("useTableUpdateHandlers", () => {
+ it("shows an error toast when a custom field order fails to save", async () => {
+ const result = setup();
+
+ fetchMock.modifyRoute(`table-${ORDERS_TABLE.id}-fields-order`, {
+ response: { status: 500 },
+ });
+
+ await result.current.handleCustomFieldOrderChange(
+ (ORDERS_TABLE.fields ?? []).map(getRawTableFieldId).reverse(),
+ );
+
+ await waitFor(() => {
+ expect(
+ within(screen.getByTestId("undo-list")).getByText(
+ "Failed to update field order",
+ ),
+ ).toBeInTheDocument();
+ });
+ });
+});
diff --git a/frontend/test/__support__/server-mocks/field.ts b/frontend/test/__support__/server-mocks/field.ts
index c008f5998d6..ea52c07ec3d 100644
--- a/frontend/test/__support__/server-mocks/field.ts
+++ b/frontend/test/__support__/server-mocks/field.ts
@@ -12,6 +12,9 @@ import { PERMISSION_ERROR } from "./constants";
export function setupFieldEndpoints(field: Field) {
fetchMock.get(`path:/api/field/${field.id}`, field);
+ fetchMock.put(`path:/api/field/${field.id}`, field, {
+ name: `field-${field.id}-put`,
+ });
fetchMock.post(
`path:/api/field/${field.id}/rescan_values`,
{},
diff --git a/frontend/test/__support__/server-mocks/table.ts b/frontend/test/__support__/server-mocks/table.ts
index e24b8195240..1a52369fcf1 100644
--- a/frontend/test/__support__/server-mocks/table.ts
+++ b/frontend/test/__support__/server-mocks/table.ts
@@ -19,6 +19,11 @@ export function setupTableEndpoints(
{},
{ name: `table-${table.id}-put` },
);
+ fetchMock.put(
+ `path:/api/table/${table.id}/fields/order`,
+ {},
+ { name: `table-${table.id}-fields-order` },
+ );
fetchMock.post(
`path:/api/table/${table.id}/rescan_values`,
{},