Skip to content

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

e2e2unit: Move the frontend-only connection string tests to Jest (#85663)

Romeo Van Snickbc40718bff4c
diff --git a/e2e/test/scenarios/admin/database-connection-strings.cy.spec.ts b/e2e/test/scenarios/admin/database-connection-strings.cy.spec.ts
index 81d8fec85a8..9c0432251e0 100644
--- a/e2e/test/scenarios/admin/database-connection-strings.cy.spec.ts
+++ b/e2e/test/scenarios/admin/database-connection-strings.cy.spec.ts
@@ -2,8 +2,6 @@ import { QA_MYSQL_PORT, QA_POSTGRES_PORT } from "e2e/support/cypress_data";
import { waitForDbSync } from "./helpers/e2e-database-helpers";
-const { H } = cy;
-
beforeEach(() => {
cy.H.restore();
cy.signInAsAdmin();
@@ -205,20 +203,9 @@ const databaseTestCases = [
];
describe("Database connection strings", () => {
- it("should enable 'Save' for a valid connection string, and parse connection strings for all supported databases without clearing existing values", () => {
- cy.log(
- "should enable the 'Save' button when the connection string is valid",
- );
- // Runs on a fresh form: engine changes keep earlier values, which could
- // enable Save before the paste
- cy.visit("/admin/databases/create");
- chooseDatabase("MySQL");
- cy.findByLabelText("Connection string (optional)").paste(
- "jdbc:mysql://testuser:testpass@host:3306/dbname?ssl=true",
- );
- cy.button("Save").should("be.enabled");
-
- cy.log("should parse connection strings for all supported databases");
+ // The field labels come from the driver definitions the backend serves, so
+ // this is the only place that pins the mapper's detail keys to them.
+ it("should parse connection strings for all supported databases", () => {
cy.visit("/admin/databases/create");
databaseTestCases.forEach(
@@ -239,19 +226,6 @@ describe("Database connection strings", () => {
});
},
);
-
- cy.log("should not clear the existing values");
- // Keep this step last: values that the connection string doesn't set are
- // preserved, so running it earlier could leak into the cases above.
- chooseDatabase("PostgreSQL");
- cy.findByLabelText("Port").clear().type("1111");
-
- cy.findByLabelText("Connection string (optional)").paste(
- "postgresql://postgres:[email protected]/postgres",
- );
-
- cy.findByLabelText("Port").should("have.value", "1111");
- cy.findByLabelText("Database type").should("have.value", "PostgreSQL");
});
describe("actual database connections", { tags: "@external" }, () => {
@@ -354,59 +328,3 @@ describe("Database connection strings", () => {
});
});
});
-
-describe("Database connection strings events", () => {
- beforeEach(() => {
- H.resetSnowplow();
- H.restore();
- H.enableTracking();
- cy.visit("/admin/databases/create?engine=mysql");
- });
-
- it("should track success and failure events correctly", () => {
- cy.log("should track success events correctly");
- const successEvent = {
- event: "connection_string_parsed_success",
- triggered_from: "full-page",
- };
-
- cy.findByLabelText("Connection string (optional)")
- .focus()
- .paste("jdbc:mysql://testuser:testpass@host:3306/dbname?ssl=true")
- .paste("jdbc:mysql://a:b@c:3/dbname?ssl=false");
-
- cy.findByTextEnsureVisible("Connection details pre-filled below.").should(
- "exist",
- );
-
- cy.findByLabelText("Display name").click();
-
- H.expectUnstructuredSnowplowEvent(successEvent, 1);
-
- cy.findByLabelText("Connection string (optional)").click();
- cy.findByLabelText("Display name").click();
-
- // Should not track the same event again
- H.expectUnstructuredSnowplowEvent(successEvent, 1);
-
- cy.log("should track failure events correctly");
- cy.findByLabelText("Connection string (optional)")
- .focus()
- .paste("broken string")
- .type("also not a valid string");
-
- cy.findByTextEnsureVisible("Couldn’t use this connection string.").should(
- "exist",
- );
-
- cy.findByLabelText("Display name").click();
-
- H.expectUnstructuredSnowplowEvent(
- {
- event: "connection_string_parsed_failed",
- triggered_from: "full-page",
- },
- 1,
- );
- });
-});
diff --git a/frontend/src/metabase/admin/databases/containers/DatabasePage.unit.spec.tsx b/frontend/src/metabase/admin/databases/containers/DatabasePage.unit.spec.tsx
index 5a071231f77..21caeec3358 100644
--- a/frontend/src/metabase/admin/databases/containers/DatabasePage.unit.spec.tsx
+++ b/frontend/src/metabase/admin/databases/containers/DatabasePage.unit.spec.tsx
@@ -46,12 +46,25 @@ const POSTGRES_ENGINE = createMockEngine({
],
});
+const MYSQL_ENGINE = createMockEngine({
+ "driver-name": "MySQL",
+ "details-fields": [
+ createMockEngineField({ name: "host", "display-name": "Host" }),
+ ],
+});
+
interface SetupOpts {
createDatabaseErrorBody?: string | Record<string, unknown>;
+ searchParams?: string;
}
-const setup = ({ createDatabaseErrorBody }: SetupOpts = {}) => {
- setupEnginesEndpoint(createMockEngines({ postgres: POSTGRES_ENGINE }));
+const setup = ({ createDatabaseErrorBody, searchParams }: SetupOpts = {}) => {
+ // The page reads the engine off window.location, which the memory router
+ // used by renderWithProviders never touches.
+ window.history.replaceState({}, "", `/${searchParams ?? ""}`);
+ setupEnginesEndpoint(
+ createMockEngines({ postgres: POSTGRES_ENGINE, mysql: MYSQL_ENGINE }),
+ );
if (createDatabaseErrorBody !== undefined) {
setupCreateDatabaseEndpointError({
status: 400,
@@ -80,6 +93,22 @@ const fillInAndSaveDatabase = async () => {
};
describe("DatabasePage", () => {
+ afterEach(() => {
+ window.history.replaceState({}, "", "/");
+ });
+
+ describe("choosing the engine", () => {
+ it("should default to PostgreSQL", async () => {
+ setup();
+ expect(await screen.findByDisplayValue("PostgreSQL")).toBeInTheDocument();
+ });
+
+ it("should preselect the engine named in the URL", async () => {
+ setup({ searchParams: "?engine=mysql" });
+ expect(await screen.findByDisplayValue("MySQL")).toBeInTheDocument();
+ });
+ });
+
describe("Help button", () => {
it("should render the 'Help is here' button", async () => {
setup();
diff --git a/frontend/src/metabase/databases/components/DatabaseForm/tests/connection-string.unit.spec.tsx b/frontend/src/metabase/databases/components/DatabaseForm/tests/connection-string.unit.spec.tsx
new file mode 100644
index 00000000000..e157e8aa956
--- /dev/null
+++ b/frontend/src/metabase/databases/components/DatabaseForm/tests/connection-string.unit.spec.tsx
@@ -0,0 +1,163 @@
+import userEvent from "@testing-library/user-event";
+
+import { screen, waitFor } from "__support__/ui";
+import type { SimpleEventSchema } from "metabase-types/analytics/event";
+import type { Engine } from "metabase-types/api";
+
+import { mysqlFormConfig } from "./mysql-form-config.mock";
+import { TEST_ENGINES, setup } from "./setup";
+
+const ENGINES: Record<string, Engine> = {
+ ...TEST_ENGINES,
+ mysql: mysqlFormConfig,
+};
+
+const MYSQL_CONNECTION_STRING =
+ "jdbc:mysql://testuser:testpass@host:3306/dbname?ssl=true";
+
+const getConnectionStringField = () =>
+ screen.getByLabelText("Connection string (optional)");
+
+const pasteConnectionString = async (connectionString: string) => {
+ await userEvent.click(getConnectionStringField());
+ await userEvent.paste(connectionString);
+};
+
+describe("DatabaseForm connection string", () => {
+ it("should enable Save once a valid connection string pre-fills the required fields", async () => {
+ const { onSubmit } = await setup({
+ engines: ENGINES,
+ initialValues: { engine: "mysql" },
+ });
+
+ const saveButton = screen.getByRole("button", { name: "Save" });
+ expect(saveButton).toBeDisabled();
+
+ await pasteConnectionString(MYSQL_CONNECTION_STRING);
+
+ expect(
+ await screen.findByText("Connection details pre-filled below."),
+ ).toBeInTheDocument();
+ await waitFor(() => expect(saveButton).toBeEnabled());
+
+ expect(screen.getByLabelText("Host")).toHaveValue("host");
+ expect(screen.getByLabelText("Port")).toHaveValue("3306");
+ expect(screen.getByLabelText("Database name")).toHaveValue("dbname");
+ expect(screen.getByLabelText("Display name")).toHaveValue("dbname");
+ expect(screen.getByLabelText("Username")).toHaveValue("testuser");
+ expect(screen.getByLabelText("Password")).toHaveValue("testpass");
+ expect(
+ screen.getByLabelText("Use a secure connection (SSL)"),
+ ).toBeChecked();
+
+ await userEvent.click(saveButton);
+
+ // The connection string only pre-fills the form, the backend never sees it.
+ await waitFor(() =>
+ expect(onSubmit).toHaveBeenCalledWith(
+ expect.not.objectContaining({ "connection-string": expect.anything() }),
+ ),
+ );
+ });
+
+ it("should keep the values that the connection string does not set", async () => {
+ await setup({ engines: ENGINES, initialValues: { engine: "postgres" } });
+
+ await userEvent.type(screen.getByLabelText("Port"), "1111");
+
+ await pasteConnectionString(
+ "postgresql://postgres:[email protected]/postgres",
+ );
+
+ await waitFor(() =>
+ expect(screen.getByLabelText("Database name")).toHaveValue("postgres"),
+ );
+ expect(screen.getByLabelText("Port")).toHaveValue("1111");
+ expect(screen.getByLabelText("Database type")).toHaveValue("PostgreSQL");
+ });
+
+ describe("analytics", () => {
+ // metabase/analytics is auto-mocked globally, and only an analytics.ts file
+ // may import the tracker by name.
+ const { trackSimpleEvent } = jest.requireMock<{
+ trackSimpleEvent: jest.Mock<void, [SimpleEventSchema]>;
+ }>("metabase/analytics");
+
+ const getConnectionStringEvents = () =>
+ trackSimpleEvent.mock.calls
+ .map(([event]) => event)
+ .filter(({ event }) => event.startsWith("connection_string_parsed_"));
+
+ beforeEach(() => {
+ trackSimpleEvent.mockClear();
+ });
+
+ it("should track a single success event for everything typed before the field is blurred", async () => {
+ await setup({
+ engines: ENGINES,
+ initialValues: { engine: "mysql" },
+ location: "full-page",
+ });
+
+ await pasteConnectionString(MYSQL_CONNECTION_STRING);
+ await userEvent.paste("jdbc:mysql://a:b@c:3/dbname?ssl=false");
+
+ expect(
+ await screen.findByText("Connection details pre-filled below."),
+ ).toBeInTheDocument();
+ expect(getConnectionStringEvents()).toEqual([]);
+
+ await userEvent.click(screen.getByLabelText("Display name"));
+
+ expect(getConnectionStringEvents()).toEqual([
+ {
+ event: "connection_string_parsed_success",
+ triggered_from: "full-page",
+ },
+ ]);
+
+ await userEvent.click(getConnectionStringField());
+ await userEvent.click(screen.getByLabelText("Display name"));
+
+ expect(getConnectionStringEvents()).toHaveLength(1);
+ });
+
+ it("should track a failure event when the connection string cannot be parsed", async () => {
+ await setup({
+ engines: ENGINES,
+ initialValues: { engine: "mysql" },
+ location: "full-page",
+ });
+
+ await pasteConnectionString("broken string");
+
+ expect(
+ await screen.findByText("Couldn’t use this connection string."),
+ ).toBeInTheDocument();
+
+ await userEvent.click(screen.getByLabelText("Display name"));
+
+ expect(getConnectionStringEvents()).toEqual([
+ {
+ event: "connection_string_parsed_failed",
+ triggered_from: "full-page",
+ },
+ ]);
+ });
+
+ it("should report the admin modal as the source of the event", async () => {
+ await setup({
+ engines: ENGINES,
+ initialValues: { engine: "mysql" },
+ location: "admin",
+ });
+
+ await pasteConnectionString(MYSQL_CONNECTION_STRING);
+ await userEvent.click(screen.getByLabelText("Display name"));
+
+ expect(getConnectionStringEvents()).toEqual([
+ { event: "connection_string_parsed_success", triggered_from: "admin" },
+ ]);
+ });
+ });
+});