Skip to content

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

Convert remaining spec-only unit spec files to TypeScript (#79545)

Andrei Chernykh62351c70d33c
diff --git a/frontend/src/metabase-lib/v1/Question.unit.spec.js b/frontend/src/metabase-lib/v1/Question.unit.spec.ts
similarity index 93%
rename from frontend/src/metabase-lib/v1/Question.unit.spec.js
rename to frontend/src/metabase-lib/v1/Question.unit.spec.ts
index 315b00441d3..a4aef6e76bb 100644
--- a/frontend/src/metabase-lib/v1/Question.unit.spec.js
+++ b/frontend/src/metabase-lib/v1/Question.unit.spec.ts
@@ -1,7 +1,10 @@
import { createMockMetadata } from "__support__/metadata";
+import { checkNotNull } from "metabase/utils/types";
import {
createMockColumn,
createMockDatasetData,
+ createMockField,
+ createMockParameter,
} from "metabase-types/api/mocks";
import {
ORDERS,
@@ -336,7 +339,9 @@ describe("Question", () => {
describe("setQuery(query)", () => {
it("updates the dataset_query of card", () => {
- const rawQuery = native_orders_count_question.legacyNativeQuery();
+ const rawQuery = checkNotNull(
+ native_orders_count_question.legacyNativeQuery(),
+ );
const newRawQuestion = orders_raw_question.setLegacyQuery(rawQuery);
expect(newRawQuestion.legacyNativeQuery() instanceof NativeQuery).toBe(
true,
@@ -402,7 +407,7 @@ describe("Question", () => {
const question = orders_count_question
.setDisplay("table")
.lockDisplay()
- .maybeResetDisplay(ordersCountData, ["table", "scalar"]);
+ .maybeResetDisplay(ordersCountData, ["table", "scalar"], undefined);
expect(question.display()).toBe("table");
});
@@ -410,7 +415,7 @@ describe("Question", () => {
it("should set the display to scalar if a non-scalar was selected and display is locked", () => {
const question = base_question
.setDisplay("table")
- .maybeResetDisplay(ordersCountData, ["table", "scalar"]);
+ .maybeResetDisplay(ordersCountData, ["table", "scalar"], undefined);
expect(question.display()).toBe("scalar");
});
@@ -418,7 +423,11 @@ describe("Question", () => {
it("should not set the display to scalar if another scalar display was selected and display is locked", () => {
const question = base_question
.setDisplay("gauge")
- .maybeResetDisplay(ordersCountData, ["table", "scalar", "gauge"]);
+ .maybeResetDisplay(
+ ordersCountData,
+ ["table", "scalar", "gauge"],
+ undefined,
+ );
expect(question.display()).toBe("gauge");
});
@@ -426,7 +435,7 @@ describe("Question", () => {
it("switch to table view if we had a scalar and now have more than 1x1 data", () => {
const question = base_question
.setDisplay("scalar")
- .maybeResetDisplay(multipleRowsData, ["table"]);
+ .maybeResetDisplay(multipleRowsData, ["table"], undefined);
expect(question.display()).toBe("table");
});
@@ -435,7 +444,7 @@ describe("Question", () => {
const question = orders_count_question
.setDisplay("funnel")
.lockDisplay()
- .maybeResetDisplay(ordersCountData, ["table", "scalar"]);
+ .maybeResetDisplay(ordersCountData, ["table", "scalar"], undefined);
expect(question.display()).toBe("scalar");
});
@@ -510,7 +519,7 @@ describe("Question", () => {
const question = base_question
.setDisplay("scalar")
.lockDisplay()
- .maybeResetDisplay(multipleRowsData, sensibleDisplays);
+ .maybeResetDisplay(multipleRowsData, sensibleDisplays, undefined);
expect(question.display()).not.toBe("table");
expect(question.display()).toBe("scalar");
@@ -520,7 +529,7 @@ describe("Question", () => {
const sensibleDisplays = ["table", "scalar"];
const question = base_question
.setDisplay("scalar")
- .maybeResetDisplay(multipleRowsData, sensibleDisplays);
+ .maybeResetDisplay(multipleRowsData, sensibleDisplays, undefined);
expect(question.display()).not.toBe("table");
expect(question.display()).toBe("scalar");
@@ -530,7 +539,7 @@ describe("Question", () => {
const sensibleDisplays = ["table", "scalar"];
const question = orders_count_question
.setDisplay("table")
- .maybeResetDisplay(ordersCountData, sensibleDisplays);
+ .maybeResetDisplay(ordersCountData, sensibleDisplays, undefined);
expect(question.display()).not.toBe("table");
expect(question.display()).toBe("scalar");
@@ -582,8 +591,9 @@ describe("Question", () => {
describe("Question.prototype.getResultMetadata", () => {
it("should return the `result_metadata` property off the underlying card", () => {
- const question = base_question.setResultsMetadata({ columns: [1, 2, 3] });
- expect(question.getResultMetadata()).toEqual([1, 2, 3]);
+ const columns = [createMockField({ id: 1 }), createMockField({ id: 2 })];
+ const question = base_question.setResultsMetadata({ columns });
+ expect(question.getResultMetadata()).toEqual(columns);
});
it("should default to an array", () => {
@@ -611,7 +621,7 @@ describe("Question", () => {
describe("Question.prototype.setParameters", () => {
it("should set a `parameters` property on the question's card", () => {
- const parameters = [{ type: "category" }];
+ const parameters = [createMockParameter({ type: "category" })];
const questionWithParameters = base_question.setParameters(parameters);
expect(base_question).not.toBe(questionWithParameters);
@@ -700,30 +710,29 @@ describe("Question", () => {
});
it("should return a question's parameters + metadata and the parameter's value if present", () => {
+ // slugs differ from names so parameters() deriving a slug would be caught
+ const fooParameter = createMockParameter({
+ type: "category",
+ name: "foo",
+ slug: "foo_slug",
+ id: "foo_id",
+ target: ["dimension", ["field", PRODUCTS.CATEGORY, null]],
+ });
+ const barParameter = createMockParameter({
+ type: "category",
+ name: "bar",
+ slug: "bar_slug",
+ id: "bar_id",
+ });
const question = base_question
- .setParameters([
- {
- type: "category",
- name: "foo",
- id: "foo_id",
- target: ["dimension", ["field", PRODUCTS.CATEGORY, null]],
- },
- {
- type: "category",
- name: "bar",
- id: "bar_id",
- },
- ])
+ .setParameters([fooParameter, barParameter])
.setParameterValues({
foo_id: "abc",
});
expect(question.parameters()).toEqual([
{
- type: "category",
- name: "foo",
- id: "foo_id",
- target: ["dimension", ["field", PRODUCTS.CATEGORY, null]],
+ ...fooParameter,
value: "abc",
fields: [
expect.objectContaining({
@@ -733,9 +742,7 @@ describe("Question", () => {
hasVariableTemplateTagTarget: false,
},
{
- type: "category",
- name: "bar",
- id: "bar_id",
+ ...barParameter,
hasVariableTemplateTagTarget: true,
value: null,
},
@@ -826,7 +833,8 @@ describe("Question", () => {
[
"aggregation-options",
["sum", ["field", 1, null]],
- { "display-name": "Revenue" },
+ // name differs from display-name to pin which key the description uses
+ { name: "revenue_sum", "display-name": "Revenue" },
],
],
},
diff --git a/frontend/src/metabase-lib/v1/metadata/Table.unit.spec.js b/frontend/src/metabase-lib/v1/metadata/Table.unit.spec.js
deleted file mode 100644
index 5c615e9b967..00000000000
--- a/frontend/src/metabase-lib/v1/metadata/Table.unit.spec.js
+++ /dev/null
@@ -1,28 +0,0 @@
-import { createMockMetadata } from "__support__/metadata";
-import Database from "metabase-lib/v1/metadata/Database";
-import Table from "metabase-lib/v1/metadata/Table";
-import {
- ORDERS_ID,
- createSampleDatabase,
-} from "metabase-types/api/mocks/presets";
-
-describe("Table", () => {
- const metadata = createMockMetadata({
- databases: [createSampleDatabase()],
- });
- const table = metadata.table(ORDERS_ID);
-
- it("should be a table", () => {
- expect(table).toBeInstanceOf(Table);
- });
-
- it("should have a database", () => {
- expect(table.db).toBeInstanceOf(Database);
- });
-
- describe("date fields", () => {
- it("should return date fields", () => {
- expect(table.dateFields().length).toEqual(1);
- });
- });
-});
diff --git a/frontend/src/metabase-lib/v1/metadata/Table.unit.spec.ts b/frontend/src/metabase-lib/v1/metadata/Table.unit.spec.ts
index 6db6c27bd4e..a04dad5a14b 100644
--- a/frontend/src/metabase-lib/v1/metadata/Table.unit.spec.ts
+++ b/frontend/src/metabase-lib/v1/metadata/Table.unit.spec.ts
@@ -1,9 +1,15 @@
import { createMockMetadata } from "__support__/metadata";
+import Database from "metabase-lib/v1/metadata/Database";
+import Table from "metabase-lib/v1/metadata/Table";
import {
createMockField,
createMockForeignKey,
createMockTable,
} from "metabase-types/api/mocks";
+import {
+ ORDERS_ID,
+ createSampleDatabase,
+} from "metabase-types/api/mocks/presets";
const TABLE_ORIGIN_ID = 1;
const TABLE_DESTINATION_ID = 2;
@@ -80,4 +86,25 @@ describe("Table", () => {
expect(destinationTable?.connectedTables()).toEqual([originTable]);
});
});
+
+ describe("with the sample database", () => {
+ const metadata = createMockMetadata({
+ databases: [createSampleDatabase()],
+ });
+ const table = metadata.table(ORDERS_ID);
+
+ it("should be a table", () => {
+ expect(table).toBeInstanceOf(Table);
+ });
+
+ it("should have a database", () => {
+ expect(table?.db).toBeInstanceOf(Database);
+ });
+
+ describe("date fields", () => {
+ it("should return date fields", () => {
+ expect(table?.dateFields()).toHaveLength(1);
+ });
+ });
+ });
});
diff --git a/frontend/src/metabase-lib/v1/parameters/utils/parameter-type.unit.spec.js b/frontend/src/metabase-lib/v1/parameters/utils/parameter-type.unit.spec.ts
similarity index 54%
rename from frontend/src/metabase-lib/v1/parameters/utils/parameter-type.unit.spec.js
rename to frontend/src/metabase-lib/v1/parameters/utils/parameter-type.unit.spec.ts
index f7e98f68694..1823e83d1a6 100644
--- a/frontend/src/metabase-lib/v1/parameters/utils/parameter-type.unit.spec.js
+++ b/frontend/src/metabase-lib/v1/parameters/utils/parameter-type.unit.spec.ts
@@ -3,44 +3,67 @@ import {
getParameterType,
isIdParameter,
} from "metabase-lib/v1/parameters/utils/parameter-type";
+import { createMockParameter } from "metabase-types/api/mocks";
describe("parameters/utils/parameter-type", () => {
describe("getParameterType", () => {
it("should return the string before the slash in a parameter type", () => {
- expect(getParameterType({ type: "string/foo" })).toEqual("string");
- expect(getParameterType({ type: "category" })).toEqual("category");
+ expect(
+ getParameterType(createMockParameter({ type: "string/foo" })),
+ ).toEqual("string");
+ expect(
+ getParameterType(createMockParameter({ type: "category" })),
+ ).toEqual("category");
});
it("should return the string before the slash in a parameter's type", () => {
- expect(getParameterType({ type: "string/foo" })).toEqual("string");
- expect(getParameterType({ type: "category" })).toEqual("category");
+ expect(
+ getParameterType(createMockParameter({ type: "string/foo" })),
+ ).toEqual("string");
+ expect(
+ getParameterType(createMockParameter({ type: "category" })),
+ ).toEqual("category");
});
it("should prefer using a sectionId for determining the type if it exists", () => {
expect(
- getParameterType({ sectionId: "location", type: "string/=" }),
+ getParameterType(
+ createMockParameter({ sectionId: "location", type: "string/=" }),
+ ),
).toEqual("location");
});
});
describe("isIdParameter (QUE2-326)", () => {
it("should return true for sectionId 'id' with concrete type", () => {
- expect(isIdParameter({ sectionId: "id", type: "number/=" })).toBe(true);
+ expect(
+ isIdParameter(
+ createMockParameter({ sectionId: "id", type: "number/=" }),
+ ),
+ ).toBe(true);
});
it("should return true for sectionId 'id' with string type", () => {
- expect(isIdParameter({ sectionId: "id", type: "string/=" })).toBe(true);
+ expect(
+ isIdParameter(
+ createMockParameter({ sectionId: "id", type: "string/=" }),
+ ),
+ ).toBe(true);
});
it("should return true for legacy type 'id' (backward compat)", () => {
- expect(isIdParameter({ type: "id" })).toBe(true);
+ expect(isIdParameter(createMockParameter({ type: "id" }))).toBe(true);
});
it("should return false for non-id parameters", () => {
- expect(isIdParameter({ type: "number/=" })).toBe(false);
- expect(isIdParameter({ sectionId: "number", type: "number/=" })).toBe(
+ expect(isIdParameter(createMockParameter({ type: "number/=" }))).toBe(
false,
);
+ expect(
+ isIdParameter(
+ createMockParameter({ sectionId: "number", type: "number/=" }),
+ ),
+ ).toBe(false);
});
});
diff --git a/frontend/src/metabase-lib/v1/parameters/utils/template-tag-options.unit.spec.js b/frontend/src/metabase-lib/v1/parameters/utils/template-tag-options.unit.spec.ts
similarity index 64%
rename from frontend/src/metabase-lib/v1/parameters/utils/template-tag-options.unit.spec.js
rename to frontend/src/metabase-lib/v1/parameters/utils/template-tag-options.unit.spec.ts
index 220f461c1e9..29bdb752ce9 100644
--- a/frontend/src/metabase-lib/v1/parameters/utils/template-tag-options.unit.spec.js
+++ b/frontend/src/metabase-lib/v1/parameters/utils/template-tag-options.unit.spec.ts
@@ -1,20 +1,28 @@
import _ from "underscore";
+import Field from "metabase-lib/v1/metadata/Field";
import { PARAMETER_OPERATOR_TYPES } from "metabase-lib/v1/parameters/constants";
+import { createMockNormalizedField } from "metabase-types/api/mocks";
import {
getParameterOptions,
getParameterOptionsForField,
} from "./template-tag-options";
+function createMockField(mocks: Partial<Field>): Field {
+ return Object.assign(new Field(createMockNormalizedField({})), mocks);
+}
+
describe("parameters/utils/template-tag-options", () => {
describe("getParameterOptions", () => {
it("should return options with operator subtypes", () => {
- const options = new Set(_.map(getParameterOptions(), "type"));
+ const options = new Set(
+ getParameterOptions().map((option) => option.type),
+ );
const expectedOptionTypes = ["id", "boolean/="].concat(
- _.map(PARAMETER_OPERATOR_TYPES.number, "type"),
- _.map(PARAMETER_OPERATOR_TYPES.string, "type"),
- _.map(PARAMETER_OPERATOR_TYPES.date, "type"),
+ PARAMETER_OPERATOR_TYPES.number.map((option) => option.type),
+ PARAMETER_OPERATOR_TYPES.string.map((option) => option.type),
+ PARAMETER_OPERATOR_TYPES.date.map((option) => option.type),
);
expect(expectedOptionTypes.length).toEqual(options.size);
@@ -26,27 +34,25 @@ describe("parameters/utils/template-tag-options", () => {
it("should add a `combinedName` property to options", () => {
const optionsByType = _.groupBy(getParameterOptions(), "type");
- expect(optionsByType["string/="][0].combinedName).toEqual("String");
- expect(optionsByType["string/!="][0].combinedName).toEqual(
- "String is not",
- );
- expect(optionsByType["number/!="][0].combinedName).toEqual(
- "Not equal to",
- );
- expect(optionsByType["date/single"][0].combinedName).toEqual(
- "Single Date",
- );
+ expect(optionsByType["string/="][0]).toMatchObject({
+ combinedName: "String",
+ });
+ expect(optionsByType["string/!="][0]).toMatchObject({
+ combinedName: "String is not",
+ });
+ expect(optionsByType["number/!="][0]).toMatchObject({
+ combinedName: "Not equal to",
+ });
+ expect(optionsByType["date/single"][0]).toMatchObject({
+ combinedName: "Single Date",
+ });
});
});
describe("getParameterOptionsForField", () => {
- const field = {
+ const fieldPredicates = {
isDate: () => false,
isID: () => false,
- isCity: () => false,
- isState: () => false,
- isZipCode: () => false,
- isCountry: () => false,
isNumeric: () => false,
isString: () => false,
isStringLike: () => false,
@@ -55,10 +61,10 @@ describe("parameters/utils/template-tag-options", () => {
};
it("should return relevantly typed options for date field", () => {
- const dateField = {
- ...field,
+ const dateField = createMockField({
+ ...fieldPredicates,
isDate: () => true,
- };
+ });
const availableOptions = getParameterOptionsForField(dateField);
expect(
availableOptions.length > 0 &&
@@ -67,10 +73,10 @@ describe("parameters/utils/template-tag-options", () => {
});
it("should return relevantly typed options for id field", () => {
- const idField = {
- ...field,
+ const idField = createMockField({
+ ...fieldPredicates,
isID: () => true,
- };
+ });
const availableOptions = getParameterOptionsForField(idField);
expect(
availableOptions.length > 0 &&
@@ -79,11 +85,11 @@ describe("parameters/utils/template-tag-options", () => {
});
it("should return string options for an address field", () => {
- const addressField = {
- ...field,
+ const addressField = createMockField({
+ ...fieldPredicates,
isString: () => true,
isAddress: () => true,
- };
+ });
const availableOptions = getParameterOptionsForField(addressField);
expect(
availableOptions.length > 0 &&
@@ -92,11 +98,11 @@ describe("parameters/utils/template-tag-options", () => {
});
it("should return string options for a TextLike field", () => {
- const enumField = {
- ...field,
+ const enumField = createMockField({
+ ...fieldPredicates,
isString: () => false,
isStringLike: () => true,
- };
+ });
const availableOptions = getParameterOptionsForField(enumField);
expect(
availableOptions.length > 0 &&
diff --git a/frontend/src/metabase-lib/v1/parameters/utils/template-tags.unit.spec.js b/frontend/src/metabase-lib/v1/parameters/utils/template-tags.unit.spec.ts
similarity index 68%
rename from frontend/src/metabase-lib/v1/parameters/utils/template-tags.unit.spec.js
rename to frontend/src/metabase-lib/v1/parameters/utils/template-tags.unit.spec.ts
index 630543a963c..bfc95464b80 100644
--- a/frontend/src/metabase-lib/v1/parameters/utils/template-tags.unit.spec.js
+++ b/frontend/src/metabase-lib/v1/parameters/utils/template-tags.unit.spec.ts
@@ -1,85 +1,97 @@
+import { createMockMetadata } from "__support__/metadata";
import {
getTemplateTagParameters,
getTemplateTags,
} from "metabase-lib/v1/parameters/utils/template-tags";
-import { createMockTemplateTag } from "metabase-types/api/mocks";
+import type {
+ Card,
+ DatasetQuery,
+ TemplateTag,
+ TemplateTagType,
+} from "metabase-types/api";
+import {
+ createMockCard,
+ createMockNativeDatasetQuery,
+ createMockNativeQuery,
+ createMockTemplateTag,
+} from "metabase-types/api/mocks";
+
+const metadata = createMockMetadata({});
+
+const createLegacyCard = (datasetQuery: unknown): Card =>
+ // legacy dataset_query shapes that DatasetQuery cannot express
+ createMockCard({ dataset_query: datasetQuery as DatasetQuery });
describe("parameters/utils/cards", () => {
describe("getTemplateTags", () => {
it("should return an empty array for a non-native query", () => {
- const card = {
- dataset_query: {
- type: "query",
- },
- };
- expect(getTemplateTags(card)).toEqual([]);
+ const card = createLegacyCard({ type: "query" });
+ expect(getTemplateTags(card, metadata)).toEqual([]);
});
it("should return an empty array for an internal query", () => {
- const card = {
- dataset_query: {
- type: "internal",
- fn: "metabase-enterprise.audit-app.pages.queries/bad-table",
- args: [],
- },
- };
- expect(getTemplateTags(card)).toEqual([]);
+ const card = createLegacyCard({
+ type: "internal",
+ fn: "metabase-enterprise.audit-app.pages.queries/bad-table",
+ args: [],
+ });
+ expect(getTemplateTags(card, metadata)).toEqual([]);
});
it("should return an empty array for a non-parameterized query", () => {
- const card = {
- dataset_query: {
- type: "query",
- native: {
- query: "select * from PRODUCTS",
- },
+ const card = createLegacyCard({
+ type: "query",
+ native: {
+ query: "select * from PRODUCTS",
},
- };
- expect(getTemplateTags(card)).toEqual([]);
+ });
+ expect(getTemplateTags(card, metadata)).toEqual([]);
});
it("should extract the template tags", () => {
- const card = {
- dataset_query: {
- type: "native",
- native: {
+ const starsTag = createMockTemplateTag({
+ type: "number",
+ name: "stars",
+ id: "xyz777",
+ });
+ const snippetTag = createMockTemplateTag({
+ type: "snippet",
+ id: "abc123",
+ name: "snippet: foo",
+ "snippet-id": 6,
+ });
+ const card = createMockCard({
+ dataset_query: createMockNativeDatasetQuery({
+ native: createMockNativeQuery({
query: "select * from PRODUCTS where RATING > {{stars}}",
"template-tags": {
- stars: {
- type: "number",
- name: "stars",
- id: "xyz777",
- },
- "snippet: foo": {
- type: "snippet",
- id: "abc123",
- name: "snippet: foo",
- "snippet-id": 6,
- },
+ stars: starsTag,
+ "snippet: foo": snippetTag,
},
- },
- },
- };
- expect(getTemplateTags(card)).toEqual([
- {
- type: "number",
- name: "stars",
- id: "xyz777",
- },
- {
- id: "abc123",
- name: "snippet: foo",
- "snippet-id": 6,
- type: "snippet",
+ }),
+ }),
+ });
+ expect(getTemplateTags(card, metadata)).toEqual([starsTag, snippetTag]);
+ });
+
+ it("should return minimal legacy tags unmodified", () => {
+ const starsTag = { type: "number", name: "stars", id: "xyz777" };
+ const card = createLegacyCard({
+ type: "native",
+ native: {
+ query: "select * from PRODUCTS where RATING > {{stars}}",
+ "template-tags": { stars: starsTag },
},
- ]);
+ });
+ expect(getTemplateTags(card, metadata)).toEqual([starsTag]);
});
});
describe("getTemplateTagParameters", () => {
- let tags;
+ let tags: TemplateTag[];
beforeEach(() => {
+ // legacy-shaped tags (numeric ids, retired types) that TemplateTag cannot express
tags = [
{
"widget-type": "foo",
@@ -124,7 +136,7 @@ describe("parameters/utils/cards", () => {
name: "f",
"display-name": "F",
},
- ];
+ ] as unknown as TemplateTag[];
});
it("should convert tags into tag parameters with field filter operator types", () => {
@@ -228,7 +240,8 @@ describe("parameters/utils/cards", () => {
it("should produce string/= for unknown tag types (QUE2-326)", () => {
const tags = [
createMockTemplateTag({
- type: "unknown-type",
+ // not a real TemplateTagType: exercises the string/= fallback
+ type: "unknown-type" as TemplateTagType,
id: "1",
name: "x",
"display-name": "X",
@@ -250,7 +263,8 @@ describe("parameters/utils/cards", () => {
it("should exclude tags that are not parameters", () => {
const tags = [
createMockTemplateTag({
- type: "string",
+ // legacy tag type value that predates the TemplateTagType union
+ type: "string" as TemplateTagType,
id: "1",
name: "a",
"display-name": "A",
diff --git a/frontend/src/metabase-lib/v1/queries/NativeQuery.unit.spec.js b/frontend/src/metabase-lib/v1/queries/NativeQuery.unit.spec.ts
similarity index 82%
rename from frontend/src/metabase-lib/v1/queries/NativeQuery.unit.spec.js
rename to frontend/src/metabase-lib/v1/queries/NativeQuery.unit.spec.ts
index e7e3b809109..5873af9a71b 100644
--- a/frontend/src/metabase-lib/v1/queries/NativeQuery.unit.spec.js
+++ b/frontend/src/metabase-lib/v1/queries/NativeQuery.unit.spec.ts
@@ -1,9 +1,18 @@
import { createMockMetadata } from "__support__/metadata";
+import { checkNotNull } from "metabase/utils/types";
import Question from "metabase-lib/v1/Question";
+import type Metadata from "metabase-lib/v1/metadata/Metadata";
import NativeQuery, {
updateCardTemplateTagNames,
} from "metabase-lib/v1/queries/NativeQuery";
+import type {
+ DatabaseId,
+ DatasetQuery,
+ TemplateTag,
+ TemplateTags,
+} from "metabase-types/api";
import {
+ createMockCard,
createMockDatabase,
createMockNativeQuerySnippet,
createMockTemplateTag,
@@ -25,7 +34,7 @@ const METADATA = createMockMetadata({
engine: "mongo",
features: [
"basic-aggregations",
- "nested-fields",
+ "nested-field-columns",
"dynamic-schema",
"native-requires-specified-collection",
],
@@ -40,7 +49,15 @@ const METADATA = createMockMetadata({
],
});
-function makeDatasetQuery(queryText, templateTags, databaseId) {
+const createIncompleteTag = (tag: Partial<TemplateTag>): TemplateTag =>
+ // deliberately incomplete tags for exercising canRun validation
+ tag as TemplateTag;
+
+function makeDatasetQuery(
+ queryText: string,
+ templateTags: TemplateTags | undefined,
+ databaseId: DatabaseId,
+): DatasetQuery {
return {
type: "native",
database: databaseId,
@@ -51,17 +68,21 @@ function makeDatasetQuery(queryText, templateTags, databaseId) {
};
}
-function makeQuery(query, templateTags, metadata = METADATA) {
+function makeQuery(
+ query = "",
+ templateTags?: TemplateTags,
+ metadata: Metadata = METADATA,
+) {
return new NativeQuery(
Question.create({ DEPRECATED_RAW_MBQL_type: "native", metadata }),
makeDatasetQuery(query, templateTags, SAMPLE_DB_ID),
);
}
-function makeMongoQuery(query, templateTags, metadata = METADATA) {
+function makeMongoQuery(query: string) {
return new NativeQuery(
- Question.create({ DEPRECATED_RAW_MBQL_type: "native", metadata }),
- makeDatasetQuery(query, templateTags, MONGO_DB_ID),
+ Question.create({ DEPRECATED_RAW_MBQL_type: "native", metadata: METADATA }),
+ makeDatasetQuery(query, undefined, MONGO_DB_ID),
);
}
@@ -75,7 +96,8 @@ describe("NativeQuery", () => {
});
it("Tables should return a table map that includes fields", () => {
- expect(Array.isArray(query.tables()[0].fields)).toBe(true);
+ const [table] = checkNotNull(query.tables());
+ expect(Array.isArray(table.fields)).toBe(true);
});
});
@@ -87,7 +109,7 @@ describe("NativeQuery", () => {
describe("_database()", () => {
it("returns a dictionary with the underlying database of the wrapped query", () => {
- expect(query._database().id).toBe(SAMPLE_DB_ID);
+ expect(query._database()?.id).toBe(SAMPLE_DB_ID);
});
});
@@ -216,49 +238,67 @@ describe("NativeQuery", () => {
});
it("requires a display name", () => {
- q = q.setTemplateTag("foo", { name: "foo", type: "text" });
+ q = q.setTemplateTag(
+ "foo",
+ createIncompleteTag({ name: "foo", type: "text" }),
+ );
expect(q.canRun()).toBe(false);
- q = q.setTemplateTag("foo", {
- name: "foo",
- type: "text",
- "display-name": "Foo",
- });
+ q = q.setTemplateTag(
+ "foo",
+ createIncompleteTag({
+ name: "foo",
+ type: "text",
+ "display-name": "Foo",
+ }),
+ );
expect(q.canRun()).toBe(true);
});
it("dimension type without a dimension", () => {
- q = q.setTemplateTag("foo", {
- type: "dimension",
- "widget-type": "category",
- "display-name": "bar",
- });
+ q = q.setTemplateTag(
+ "foo",
+ createIncompleteTag({
+ type: "dimension",
+ "widget-type": "category",
+ "display-name": "bar",
+ }),
+ );
expect(q.canRun()).toBe(false);
- q = q.setTemplateTag("foo", {
- name: "foo",
- type: "dimension",
- "widget-type": "category",
- dimension: ["field", 123, null],
- "display-name": "bar",
- });
+ q = q.setTemplateTag(
+ "foo",
+ createIncompleteTag({
+ name: "foo",
+ type: "dimension",
+ "widget-type": "category",
+ dimension: ["field", 123, null],
+ "display-name": "bar",
+ }),
+ );
expect(q.canRun()).toBe(true);
});
it("temporal-unit type without a dimension", () => {
- q = q.setTemplateTag("foo", {
- name: "foo",
- type: "temporal-unit",
- "display-name": "bar",
- });
+ q = q.setTemplateTag(
+ "foo",
+ createIncompleteTag({
+ name: "foo",
+ type: "temporal-unit",
+ "display-name": "bar",
+ }),
+ );
expect(q.canRun()).toBe(false);
- q = q.setTemplateTag("foo", {
- name: "foo",
- type: "temporal-unit",
- dimension: ["field", 123, null],
- "display-name": "bar",
- });
+ q = q.setTemplateTag(
+ "foo",
+ createIncompleteTag({
+ name: "foo",
+ type: "temporal-unit",
+ dimension: ["field", 123, null],
+ "display-name": "bar",
+ }),
+ );
expect(q.canRun()).toBe(true);
});
});
@@ -328,7 +368,9 @@ describe("NativeQuery", () => {
"snippet-id": SNIPPET_ID,
"snippet-name": "foo",
}),
- }).updateSnippetNames([{ id: SNIPPET_ID, name: "bar" }]);
+ }).updateSnippetNames([
+ createMockNativeQuerySnippet({ id: SNIPPET_ID, name: "bar" }),
+ ]);
expect(q.queryText()).toEqual("{{snippet: bar}}");
});
@@ -346,7 +388,9 @@ describe("NativeQuery", () => {
"snippet-id": SNIPPET_ID,
"snippet-name": "foo",
}),
- }).updateSnippetNames([{ id: SNIPPET_ID, name: "bar" }]);
+ }).updateSnippetNames([
+ createMockNativeQuerySnippet({ id: SNIPPET_ID, name: "bar" }),
+ ]);
expect(q.queryText()).toEqual("{{snippet: bar}} {{snippet: bar}}");
});
});
@@ -414,7 +458,10 @@ describe("NativeQuery", () => {
it("should not return variable for dimension template tag", () => {
const q = makeQuery()
.setQueryText("SELECT * FROM PRODUCTS WHERE {{category}}")
- .setTemplateTag("category", { name: "category", type: "dimension" });
+ .setTemplateTag(
+ "category",
+ createIncompleteTag({ name: "category", type: "dimension" }),
+ );
expect(q.variables()).toHaveLength(0);
});
});
@@ -428,11 +475,14 @@ describe("NativeQuery", () => {
it("should return a dimension for a dimension template tag", () => {
const q = makeQuery()
.setQueryText("SELECT * FROM PRODUCTS WHERE {{category}}")
- .setTemplateTag("category", {
- name: "category",
- type: "dimension",
- dimension: ["field", PRODUCTS.CATEGORY, null],
- });
+ .setTemplateTag(
+ "category",
+ createIncompleteTag({
+ name: "category",
+ type: "dimension",
+ dimension: ["field", PRODUCTS.CATEGORY, null],
+ }),
+ );
const dimensions = q.dimensionOptions().dimensions;
expect(dimensions).toHaveLength(1);
expect(dimensions.map((d) => d.displayName())).toEqual(["Category"]);
@@ -442,7 +492,7 @@ describe("NativeQuery", () => {
describe("updateCardTemplateTagNames", () => {
it("should update the query text with new tag names", () => {
const query = makeQuery().setQueryText("{{#123-foo}} {{#1234-bar}}");
- const newCards = [{ id: 123, name: "Foo New" }]; // newCards is deliberately missing a the bar card
+ const newCards = [createMockCard({ id: 123, name: "Foo New" })]; // newCards is deliberately missing the bar card
const templateTagsMap = updateCardTemplateTagNames(
query,
newCards,
diff --git a/frontend/src/metabase/dashboard/components/DashboardChartSettings/ChartNestedSettingSeriesMultiple.unit.spec.js b/frontend/src/metabase/dashboard/components/DashboardChartSettings/ChartNestedSettingSeriesMultiple.unit.spec.tsx
similarity index 82%
rename from frontend/src/metabase/dashboard/components/DashboardChartSettings/ChartNestedSettingSeriesMultiple.unit.spec.js
rename to frontend/src/metabase/dashboard/components/DashboardChartSettings/ChartNestedSettingSeriesMultiple.unit.spec.tsx
index 53200d0ecce..66fc584e17a 100644
--- a/frontend/src/metabase/dashboard/components/DashboardChartSettings/ChartNestedSettingSeriesMultiple.unit.spec.js
+++ b/frontend/src/metabase/dashboard/components/DashboardChartSettings/ChartNestedSettingSeriesMultiple.unit.spec.tsx
@@ -6,13 +6,18 @@ import userEvent from "@testing-library/user-event";
import { renderWithProviders, screen, within } from "__support__/ui";
import { MockDashboardContext } from "metabase/dashboard/context/mock-context";
import { registerVisualizations } from "metabase/visualizations/register";
-import { createMockCard } from "metabase-types/api/mocks";
+import type { CardDisplayType } from "metabase-types/api";
+import { createMockCard, createMockDataset } from "metabase-types/api/mocks";
import { DashboardChartSettings } from "./DashboardChartSettings";
registerVisualizations();
-function getSeries(display, index, changeSeriesName) {
+function getSeries(
+ display: CardDisplayType,
+ index: number,
+ changeSeriesName: boolean,
+) {
return {
card: createMockCard({
display,
@@ -25,34 +30,36 @@ function getSeries(display, index, changeSeriesName) {
: {},
name: `Test ${index}`,
}),
- data: {
- rows: [
- ["a", 1],
- ["b", 2],
- ],
- cols: [
- { name: "foo", display_name: "Foo", source: "breakout" },
- {
- name: `Test ${index}`,
- display_name: `Test ${index}`,
- source: "aggregation",
- },
- ],
- },
+ ...createMockDataset({
+ data: {
+ rows: [
+ ["a", 1],
+ ["b", 2],
+ ],
+ cols: [
+ { name: "foo", display_name: "Foo", source: "breakout" },
+ {
+ name: `Test ${index}`,
+ display_name: `Test ${index}`,
+ source: "aggregation",
+ },
+ ],
+ },
+ }),
};
}
-const setup = (seriesDisplay, numberOfSeries = 1, changeSeriesName = false) => {
- const series = new Array(numberOfSeries)
- .fill(1)
- .map((s, index) => getSeries(seriesDisplay, index, changeSeriesName));
+const setup = (
+ seriesDisplay: CardDisplayType,
+ numberOfSeries = 1,
+ changeSeriesName = false,
+) => {
+ const series = Array.from({ length: numberOfSeries }, (_, index) =>
+ getSeries(seriesDisplay, index, changeSeriesName),
+ );
return renderWithProviders(
<MockDashboardContext>
- <DashboardChartSettings
- series={series}
- initial={{ section: "Display" }}
- isDashboard={true}
- />
+ <DashboardChartSettings series={series} isDashboard={true} />
</MockDashboardContext>,
);
};
diff --git a/frontend/src/metabase/parameters/utils/parameter-parsing.unit.spec.js b/frontend/src/metabase/parameters/utils/parameter-parsing.unit.spec.ts
similarity index 86%
rename from frontend/src/metabase/parameters/utils/parameter-parsing.unit.spec.js
rename to frontend/src/metabase/parameters/utils/parameter-parsing.unit.spec.ts
index 4f4b2aae49f..4081e2c934a 100644
--- a/frontend/src/metabase/parameters/utils/parameter-parsing.unit.spec.js
+++ b/frontend/src/metabase/parameters/utils/parameter-parsing.unit.spec.ts
@@ -1,24 +1,41 @@
-import { createMockParameter } from "metabase-types/api/mocks";
+import Field from "metabase-lib/v1/metadata/Field";
+import type { FieldFilterUiParameter } from "metabase-lib/v1/parameters/types";
+import type {
+ Parameter,
+ ParameterValueOrArray,
+ ParameterValuesMap,
+} from "metabase-types/api";
+import {
+ createMockNormalizedField,
+ createMockParameter,
+} from "metabase-types/api/mocks";
import {
getParameterValueFromQueryParams,
getParameterValuesByIdFromQueryParams,
} from "./parameter-parsing";
+function createMockField(mocks: Partial<Field>): Field {
+ return Object.assign(new Field(createMockNormalizedField({})), mocks);
+}
+
+// bypasses the strict signature to pin the runtime `|| {}` guard
+const UNDEFINED_QUERY_PARAMS = undefined as unknown as ParameterValuesMap;
+
describe("parameters/utils/parameter-values", () => {
- let field1;
- let field2;
- let field3;
- let field4;
- let parameter1;
- let parameter2;
- let parameter3;
- let parameter4;
- let parameters;
- let queryParams;
+ let field1: Field;
+ let field2: Field;
+ let field3: Field;
+ let field4: Field;
+ let parameter1: FieldFilterUiParameter;
+ let parameter2: FieldFilterUiParameter;
+ let parameter3: FieldFilterUiParameter;
+ let parameter4: Parameter;
+ let parameters: Parameter[];
+ let queryParams: ParameterValuesMap;
beforeEach(() => {
- field1 = {
+ field1 = createMockField({
id: 1,
table_id: 1,
isString: () => false,
@@ -26,8 +43,8 @@ describe("parameters/utils/parameter-values", () => {
isNumeric: () => false,
isDate: () => false,
isBoolean: () => false,
- };
- field2 = {
+ });
+ field2 = createMockField({
id: 2,
table_id: 1,
isString: () => false,
@@ -35,8 +52,8 @@ describe("parameters/utils/parameter-values", () => {
isNumeric: () => false,
isDate: () => false,
isBoolean: () => false,
- };
- field3 = {
+ });
+ field3 = createMockField({
id: 3,
table_id: 1,
isString: () => false,
@@ -44,8 +61,8 @@ describe("parameters/utils/parameter-values", () => {
isNumeric: () => false,
isDate: () => false,
isBoolean: () => false,
- };
- field4 = {
+ });
+ field4 = createMockField({
id: 4,
table_id: 1,
isString: () => false,
@@ -53,33 +70,39 @@ describe("parameters/utils/parameter-values", () => {
isNumeric: () => false,
isDate: () => false,
isBoolean: () => false,
- };
+ });
// found in queryParams and not defaulted
parameter1 = {
- id: 111,
- slug: "foo",
+ ...createMockParameter({
+ id: "111",
+ slug: "foo",
+ }),
fields: [field1, field4],
};
// found in queryParams and defaulted
parameter2 = {
- id: 222,
- slug: "bar",
- default: "parameter2 default value",
+ ...createMockParameter({
+ id: "222",
+ slug: "bar",
+ default: "parameter2 default value",
+ }),
fields: [field2],
};
// not found in queryParams and defaulted
parameter3 = {
- id: 333,
- slug: "baz",
- default: "parameter3 default value",
+ ...createMockParameter({
+ id: "333",
+ slug: "baz",
+ default: "parameter3 default value",
+ }),
fields: [field3],
};
// not found in queryParams and not defaulted
- parameter4 = {
- id: 444,
+ parameter4 = createMockParameter({
+ id: "444",
slug: "qux",
- };
+ });
parameters = [parameter1, parameter2, parameter3, parameter4];
queryParams = {
foo: "parameter1 queryParam value",
@@ -90,15 +113,15 @@ describe("parameters/utils/parameter-values", () => {
describe("getParameterValueFromQueryParams", () => {
it("should return null when given an undefined queryParams arg", () => {
- expect(getParameterValueFromQueryParams(parameter1, undefined)).toBe(
- null,
- );
+ expect(
+ getParameterValueFromQueryParams(parameter1, UNDEFINED_QUERY_PARAMS),
+ ).toBe(null);
});
it("should return the parameter's default value when given an undefined queryParams arg", () => {
- expect(getParameterValueFromQueryParams(parameter2, undefined)).toBe(
- "parameter2 default value",
- );
+ expect(
+ getParameterValueFromQueryParams(parameter2, UNDEFINED_QUERY_PARAMS),
+ ).toBe("parameter2 default value");
});
it("should return the parameter's default value when the parameter value is not found in queryParams", () => {
@@ -299,6 +322,21 @@ describe("parameters/utils/parameter-values", () => {
).toEqual(["true"]);
});
+ it("should handle legacy parameters without a type", () => {
+ // legacy saved parameters may lack `type`, which Parameter requires
+ const typelessParameter = {
+ id: "555",
+ slug: "legacy",
+ fields: [field1, field4],
+ } as unknown as FieldFilterUiParameter;
+
+ expect(
+ getParameterValueFromQueryParams(typelessParameter, {
+ [typelessParameter.slug]: "foo",
+ }),
+ ).toEqual(["foo"]);
+ });
+
it("should not try to parse default values", () => {
field2.isNumeric = () => true;
field2.isDate = () => false;
@@ -374,13 +412,15 @@ describe("parameters/utils/parameter-values", () => {
});
describe("for number filter type", () => {
- const numberParameter = {
- id: 111,
+ const numberParameter = createMockParameter({
+ id: "111",
slug: "numberParameter",
type: "number/=",
- };
+ });
- const runGetParameterValueFromQueryParams = (value) =>
+ const runGetParameterValueFromQueryParams = (
+ value: ParameterValueOrArray,
+ ) =>
getParameterValueFromQueryParams(numberParameter, {
[numberParameter.slug]: value,
});
@@ -431,7 +471,10 @@ describe("parameters/utils/parameter-values", () => {
it("should handle an undefined queryParams", () => {
expect(
- getParameterValuesByIdFromQueryParams(parameters, undefined),
+ getParameterValuesByIdFromQueryParams(
+ parameters,
+ UNDEFINED_QUERY_PARAMS,
+ ),
).toEqual({
[parameter1.id]: null,
[parameter2.id]: "parameter2 default value",
diff --git a/frontend/src/metabase/redux/uploads.unit.spec.js b/frontend/src/metabase/redux/uploads.unit.spec.ts
similarity index 84%
rename from frontend/src/metabase/redux/uploads.unit.spec.js
rename to frontend/src/metabase/redux/uploads.unit.spec.ts
index 2a59de10260..8a3e667a5b3 100644
--- a/frontend/src/metabase/redux/uploads.unit.spec.js
+++ b/frontend/src/metabase/redux/uploads.unit.spec.ts
@@ -2,6 +2,7 @@ import fetchMock from "fetch-mock";
import { getMainStore } from "__support__/entities-store";
import { createMockState } from "metabase/redux/store/mocks";
+import { UploadMode } from "metabase/redux/store/upload";
import {
MAX_UPLOAD_STRING,
@@ -47,19 +48,15 @@ const mockAppendCSV = (valid = true) => {
// Asserts the matching request was sent as multipart form data — locks down
// that table.ts hands the FormData through unwrapped (a JSON-stringified
// `{ formData }` would set Content-Type: application/json instead).
-const expectMultipartBody = (urlSuffix) => {
+const expectMultipartBody = (urlSuffix: string) => {
const call = fetchMock.callHistory
.calls()
.find((c) => c.url.endsWith(urlSuffix));
expect(call).toBeDefined();
- const headers = call.options?.headers ?? {};
- const contentType =
- headers instanceof Headers
- ? headers.get("content-type")
- : (headers["content-type"] ?? headers["Content-Type"]);
+ const headers = new Headers(call?.options?.headers ?? {});
// Either absent (browser sets it with the multipart boundary) or multipart;
// application/json would mean FormData got JSON-stringified.
- expect(contentType ?? "").not.toMatch(/application\/json/);
+ expect(headers.get("content-type") ?? "").not.toMatch(/application\/json/);
};
const mockReplaceCSV = (valid = true) => {
@@ -100,9 +97,11 @@ describe("csv uploads", () => {
it("should handle file upload success", async () => {
mockUploadCSV();
- await uploadFile({ file, collectionId: "root", uploadMode: "create" })(
- dispatch,
- );
+ await uploadFile({
+ file,
+ collectionId: "root",
+ uploadMode: UploadMode.create,
+ })(store.dispatch, store.getState);
jest.advanceTimersByTime(NOTIFICATION_DELAY);
expect(dispatch).toHaveBeenCalledWith({
@@ -118,7 +117,7 @@ describe("csv uploads", () => {
type: UPLOAD_FILE_END,
payload: {
id: now,
- uploadMode: "create",
+ uploadMode: UploadMode.create,
modelId: 3,
},
});
@@ -134,7 +133,11 @@ describe("csv uploads", () => {
it("should handle file append success", async () => {
mockAppendCSV();
- await uploadFile({ file, tableId: 123, uploadMode: "append" })(dispatch);
+ await uploadFile({
+ file,
+ tableId: 123,
+ uploadMode: UploadMode.append,
+ })(store.dispatch, store.getState);
jest.advanceTimersByTime(NOTIFICATION_DELAY);
expectMultipartBody("append-csv");
@@ -153,7 +156,7 @@ describe("csv uploads", () => {
payload: {
id: now,
modelId: 3,
- uploadMode: "append",
+ uploadMode: UploadMode.append,
},
});
@@ -168,7 +171,11 @@ describe("csv uploads", () => {
it("should handle file replace success", async () => {
mockReplaceCSV();
- await uploadFile({ file, tableId: 123, uploadMode: "replace" })(dispatch);
+ await uploadFile({
+ file,
+ tableId: 123,
+ uploadMode: UploadMode.replace,
+ })(store.dispatch, store.getState);
jest.advanceTimersByTime(NOTIFICATION_DELAY);
expectMultipartBody("replace-csv");
@@ -187,7 +194,7 @@ describe("csv uploads", () => {
payload: {
id: now,
modelId: 3,
- uploadMode: "replace",
+ uploadMode: UploadMode.replace,
},
});
@@ -202,9 +209,11 @@ describe("csv uploads", () => {
it("should handle file upload error", async () => {
mockUploadCSV(false);
- await uploadFile({ file, collectionId: "root", uploadMode: "create" })(
- dispatch,
- );
+ await uploadFile({
+ file,
+ collectionId: "root",
+ uploadMode: UploadMode.create,
+ })(store.dispatch, store.getState);
jest.advanceTimersByTime(NOTIFICATION_DELAY);
expect(dispatch).toHaveBeenCalledWith({
@@ -231,8 +240,8 @@ describe("csv uploads", () => {
await uploadFile({
file: bigFile,
collectionId: "root",
- uploadMode: "create",
- })(dispatch);
+ uploadMode: UploadMode.create,
+ })(store.dispatch, store.getState);
jest.advanceTimersByTime(NOTIFICATION_DELAY);
expect(dispatch).toHaveBeenCalledWith({