level_0
int64 0
10k
| index
int64 0
0
| repo_id
stringlengths 22
152
| file_path
stringlengths 41
203
| content
stringlengths 11
11.5M
|
---|---|---|---|---|
2,255 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSInputWidget/widget/propertyPaneConfig | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSInputWidget/widget/propertyPaneConfig/validations/index.test.ts | import _ from "lodash";
import {
minValueValidation,
maxValueValidation,
defaultValueValidation,
} from ".";
import type { InputWidgetProps } from "../../types";
describe("defaultValueValidation", () => {
let result: ReturnType<typeof defaultValueValidation>;
it("should validate defaulttext of text type", () => {
result = defaultValueValidation(
"text",
{ inputType: "TEXT" } as InputWidgetProps,
_,
);
expect(result).toEqual({
isValid: true,
parsed: "text",
messages: [{ name: "", message: "" }],
});
result = defaultValueValidation(
1,
{ inputType: "TEXT" } as InputWidgetProps,
_,
);
expect(result).toEqual({
isValid: true,
parsed: "1",
messages: [{ name: "", message: "" }],
});
});
it("should validate defaulttext of Number type", () => {
result = defaultValueValidation(
1,
{ inputType: "NUMBER" } as InputWidgetProps,
_,
);
expect(result).toEqual({
isValid: true,
parsed: 1,
messages: [{ name: "", message: "" }],
});
result = defaultValueValidation(
"test",
{ inputType: "NUMBER" } as InputWidgetProps,
_,
);
expect(result).toEqual({
isValid: false,
parsed: null,
messages: [
{
name: "TypeError",
message: "This value must be number",
},
],
});
});
it("should validate defaulttext of Email type", () => {
result = defaultValueValidation(
"[email protected]",
{ inputType: "EMAIL" } as InputWidgetProps,
_,
);
expect(result).toEqual({
isValid: true,
parsed: "[email protected]",
messages: [{ name: "", message: "" }],
});
result = defaultValueValidation(
1,
{ inputType: "EMAIL" } as InputWidgetProps,
_,
);
expect(result).toEqual({
isValid: true,
parsed: "1",
messages: [{ name: "", message: "" }],
});
});
it("should validate defaulttext of Password type", () => {
result = defaultValueValidation(
"admin123",
{ inputType: "PASSWORD" } as InputWidgetProps,
_,
);
expect(result).toEqual({
isValid: true,
parsed: "admin123",
messages: [{ name: "", message: "" }],
});
result = defaultValueValidation(
1,
{ inputType: "PASSWORD" } as InputWidgetProps,
_,
);
expect(result).toEqual({
isValid: true,
parsed: "1",
messages: [{ name: "", message: "" }],
});
});
it("should validate defaulttext with type missing", () => {
result = defaultValueValidation(
"admin123",
{ inputType: "" } as any as InputWidgetProps,
_,
);
expect(result).toEqual({
isValid: false,
parsed: "",
messages: [
{
name: "TypeError",
message: "This value must be string",
},
],
});
});
it("should validate defaulttext with object value", () => {
const value = {};
result = defaultValueValidation(
value,
{ inputType: "" } as any as InputWidgetProps,
_,
);
expect(result).toEqual({
isValid: false,
parsed: JSON.stringify(value, null, 2),
messages: [
{
name: "TypeError",
message: "This value must be string",
},
],
});
});
});
describe("minValueValidation - ", () => {
it("should return true if minNum is empty", () => {
expect(
minValueValidation("", { maxNum: 10 } as InputWidgetProps, _ as any)
.isValid,
).toBeTruthy();
expect(
minValueValidation(null, { maxNum: 10 } as InputWidgetProps, _ as any)
.isValid,
).toBeTruthy();
});
it("should return false if minNum is not a valid number", () => {
expect(
minValueValidation("test", { maxNum: 10 } as InputWidgetProps, _ as any)
.isValid,
).toBeFalsy();
});
it("should return false if minNum is not lesser than maxNum", () => {
expect(
minValueValidation("11", { maxNum: 10 } as InputWidgetProps, _ as any)
.isValid,
).toBeFalsy();
});
it("should return true if minNum is a finite number and lesser than maxNum", () => {
expect(
minValueValidation("1", { maxNum: 10 } as InputWidgetProps, _ as any)
.isValid,
).toBeTruthy();
});
});
describe("maxValueValidation - ", () => {
it("should return true if maxNum is empty", () => {
expect(
maxValueValidation("", { minNum: 10 } as InputWidgetProps, _ as any)
.isValid,
).toBeTruthy();
expect(
maxValueValidation(null, { minNum: 10 } as InputWidgetProps, _ as any)
.isValid,
).toBeTruthy();
});
it("should return false if maxNum is not a valid number", () => {
expect(
maxValueValidation("test", { minNum: 10 } as InputWidgetProps, _ as any)
.isValid,
).toBeFalsy();
});
it("should return false if maxNum is not greater than minNum", () => {
expect(
maxValueValidation("9", { minNum: 10 } as InputWidgetProps, _ as any)
.isValid,
).toBeFalsy();
});
it("should return true if maxNum is a finite number and lesser than minNum", () => {
expect(
maxValueValidation("18", { minNum: 10 } as InputWidgetProps, _ as any)
.isValid,
).toBeTruthy();
});
});
|
2,265 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSPhoneInputWidget | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSPhoneInputWidget/widget/derived.test.ts | import derivedProperty from "./derived";
describe("Derived property - ", () => {
describe("isValid property", () => {
it("should test isRequired", () => {
let isValid = derivedProperty.isValid({
text: undefined,
isRequired: false,
});
expect(isValid).toBeTruthy();
isValid = derivedProperty.isValid({
text: undefined,
isRequired: true,
});
expect(isValid).toBeFalsy();
isValid = derivedProperty.isValid({
value: "0000000000",
text: "0000000000",
isRequired: true,
});
expect(isValid).toBeTruthy();
});
it("should test validation", () => {
let isValid = derivedProperty.isValid({
value: "0000000000",
text: "0000000000",
validation: false,
});
expect(isValid).toBeFalsy();
isValid = derivedProperty.isValid({
value: "0000000000",
text: "0000000000",
validation: true,
});
expect(isValid).toBeTruthy();
});
it("should test regex validation", () => {
let isValid = derivedProperty.isValid({
value: "0000000000",
text: "0000000000",
regex: "^0000000000$",
});
expect(isValid).toBeTruthy();
isValid = derivedProperty.isValid({
value: "0000000001",
text: "0000000001",
regex: "^0000000000$",
});
expect(isValid).toBeFalsy();
});
});
});
|
2,266 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSPhoneInputWidget | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSPhoneInputWidget/widget/helpers.test.ts | import { countryToFlag } from "./helpers";
describe("Utilities - ", () => {
it("should test countryToFlag", () => {
[
["+91", "🇮🇳"],
["+1", "🇺🇸"],
["", ""],
].forEach((d) => {
expect(countryToFlag(d[0])).toBe(d[1]);
});
});
});
|
2,280 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSPhoneInputWidget/widget/config/propertyPaneConfig | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSPhoneInputWidget/widget/config/propertyPaneConfig/validations/defaultValueValidation.test.ts | import type { PhoneInputWidgetProps } from "../../../types";
import { defaultValueValidation } from "./defaultValueValidation";
import _ from "lodash";
describe("defaultValueValidation", () => {
let result: ReturnType<typeof defaultValueValidation>;
it("should validate defaulttext", () => {
result = defaultValueValidation(
"0000000000",
{} as PhoneInputWidgetProps,
_,
);
expect(result).toEqual({
isValid: true,
parsed: "0000000000",
messages: [{ name: "", message: "" }],
});
});
it("should validate defaulttext with object value", () => {
const value = {};
result = defaultValueValidation(value, {} as PhoneInputWidgetProps, _);
expect(result).toEqual({
isValid: false,
parsed: JSON.stringify(value, null, 2),
messages: [
{
name: "TypeError",
message: "This value must be string",
},
],
});
});
});
|
2,335 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSTableWidget | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSTableWidget/component/Constants.test.ts | import { ConditionFunctions } from "./Constants";
import moment from "moment";
describe("ConditionFunctions Constants", () => {
it("works as expected for isExactly", () => {
const conditionFunction = ConditionFunctions["isExactly"];
expect(conditionFunction("test", "test")).toStrictEqual(true);
});
it("works as expected for isExactly", () => {
const conditionFunction = ConditionFunctions["isExactly"];
expect(conditionFunction("test", "random")).toStrictEqual(false);
});
it("works as expected for empty", () => {
const conditionFunction = ConditionFunctions["empty"];
expect(conditionFunction("", "")).toStrictEqual(true);
});
it("works as expected for notEmpty", () => {
const conditionFunction = ConditionFunctions["notEmpty"];
expect(conditionFunction("test", "")).toStrictEqual(true);
});
it("works as expected for notEqualTo", () => {
const conditionFunction = ConditionFunctions["notEqualTo"];
expect(conditionFunction("test", "random")).toStrictEqual(true);
});
it("works as expected for isEqualTo", () => {
const conditionFunction = ConditionFunctions["isEqualTo"];
expect(conditionFunction("test", "test")).toStrictEqual(true);
});
it("works as expected for lessThan", () => {
const conditionFunction = ConditionFunctions["lessThan"];
expect(conditionFunction(50, 100)).toStrictEqual(true);
});
it("works as expected for lessThanEqualTo", () => {
const conditionFunction = ConditionFunctions["lessThanEqualTo"];
expect(conditionFunction(50, 50)).toStrictEqual(true);
});
it("works as expected for greaterThan", () => {
const conditionFunction = ConditionFunctions["greaterThan"];
expect(conditionFunction(100, 50)).toStrictEqual(true);
});
it("works as expected for contains", () => {
const conditionFunction = ConditionFunctions["contains"];
expect(conditionFunction("random", "and")).toStrictEqual(true);
});
it("works as expected for startsWith", () => {
const conditionFunction = ConditionFunctions["startsWith"];
expect(conditionFunction("tested", "test")).toStrictEqual(true);
});
it("works as expected for endsWith", () => {
const conditionFunction = ConditionFunctions["endsWith"];
expect(conditionFunction("subtest", "test")).toStrictEqual(true);
expect(conditionFunction("subtest", "t")).toStrictEqual(true);
});
it("works as expected for is", () => {
const conditionFunction = ConditionFunctions["is"];
const date1 = moment();
expect(conditionFunction(date1, date1)).toStrictEqual(true);
});
it("works as expected for isNot", () => {
const conditionFunction = ConditionFunctions["isNot"];
const date1 = moment();
const date2 = moment().add(1, "day");
expect(conditionFunction(date1, date2)).toStrictEqual(true);
});
it("works as expected for isAfter", () => {
const conditionFunction = ConditionFunctions["isAfter"];
const date1 = moment();
const date2 = moment().add(1, "day");
expect(conditionFunction(date1, date2)).toStrictEqual(true);
});
it("works as expected for isBefore", () => {
const conditionFunction = ConditionFunctions["isBefore"];
const date1 = moment();
const date2 = moment().subtract(1, "day");
expect(conditionFunction(date1, date2)).toStrictEqual(true);
});
});
|
2,358 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSTableWidget/component | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSTableWidget/component/cellComponents/PlainTextCell.test.tsx | import { getCellText } from "./PlainTextCell";
import { ColumnTypes } from "widgets/wds/WDSTableWidget/constants";
describe("DefaultRendere - ", () => {
describe("getCellText", () => {
it("should test with different values", () => {
[
{
value: "#1",
cellProperties: { displayText: "test" },
columnType: ColumnTypes.TEXT,
expected: "#1",
},
{
value: 1,
cellProperties: { displayText: "test" },
columnType: ColumnTypes.TEXT,
expected: "1",
},
{
value: true,
cellProperties: { displayText: "test" },
columnType: ColumnTypes.TEXT,
expected: "true",
},
{
value: undefined,
cellProperties: { displayText: "test" },
columnType: ColumnTypes.TEXT,
expected: "",
},
{
value: null,
cellProperties: { displayText: "test" },
columnType: ColumnTypes.TEXT,
expected: "",
},
{
value: NaN,
cellProperties: { displayText: "test" },
columnType: ColumnTypes.TEXT,
expected: "",
},
{
value: "www.appsmith.com",
cellProperties: { displayText: "test" },
columnType: ColumnTypes.URL,
expected: "test",
},
{
value: { test: 1 },
cellProperties: { displayText: "test" },
columnType: ColumnTypes.TEXT,
expected: "[object Object]",
},
].forEach((testValue) => {
expect(
getCellText(
testValue.value,
testValue.columnType,
testValue.cellProperties.displayText,
),
).toEqual(testValue.expected);
});
});
});
});
|
2,370 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSTableWidget/component/header | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSTableWidget/component/header/actions/Utilities.test.ts | import { transformTableDataIntoCsv } from "./Utilities";
import type { TableColumnProps } from "../../Constants";
import { ColumnTypes } from "widgets/wds/WDSTableWidget/constants";
describe("TransformTableDataIntoArrayOfArray", () => {
const columns: TableColumnProps[] = [
{
Header: "Id",
id: "id",
alias: "id",
accessor: "id",
minWidth: 60,
draggable: true,
metaProperties: {
isHidden: false,
type: ColumnTypes.TEXT,
},
columnProperties: {
id: "id",
originalId: "id",
alias: "id",
label: "Id",
columnType: "string",
isVisible: true,
index: 0,
width: 60,
isDerived: false,
computedValue: "",
isCellEditable: false,
isEditable: false,
allowCellWrapping: false,
},
},
];
it("work as expected", () => {
const data = [
{
id: "abc",
},
{
id: "xyz",
},
];
const csvData = transformTableDataIntoCsv({
columns,
data,
});
const expectedCsvData = [["Id"], ["abc"], ["xyz"]];
expect(JSON.stringify(csvData)).toStrictEqual(
JSON.stringify(expectedCsvData),
);
});
it("work as expected with newline", () => {
const data = [
{
id: "abc\ntest",
},
{
id: "xyz",
},
];
const csvData = transformTableDataIntoCsv({
columns,
data,
});
const expectedCsvData = [["Id"], ["abc test"], ["xyz"]];
expect(JSON.stringify(csvData)).toStrictEqual(
JSON.stringify(expectedCsvData),
);
});
it("work as expected with comma", () => {
const data = [
{
id: "abc,test",
},
{
id: "xyz",
},
];
const csvData = transformTableDataIntoCsv({
columns,
data,
});
const expectedCsvData = [["Id"], ['"abc,test"'], ["xyz"]];
expect(JSON.stringify(csvData)).toStrictEqual(
JSON.stringify(expectedCsvData),
);
});
});
|
2,385 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSTableWidget | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSTableWidget/widget/propertyUtils.test.ts | import {
totalRecordsCountValidation,
uniqueColumnNameValidation,
updateColumnStyles,
updateColumnOrderHook,
getBasePropertyPath,
hideByColumnType,
uniqueColumnAliasValidation,
updateCustomColumnAliasOnLabelChange,
selectColumnOptionsValidation,
allowedFirstDayOfWeekRange,
} from "./propertyUtils";
import _ from "lodash";
import type { ColumnTypes, TableWidgetProps } from "../constants";
import { StickyType } from "../component/Constants";
describe("PropertyUtils - ", () => {
it("totalRecordsCountValidation - should test with all possible values", () => {
const ERROR_MESSAGE = [
{ name: "ValidationError", message: "This value must be a number" },
];
const values = [
[
undefined,
{
isValid: true,
parsed: 0,
messages: [],
},
],
[
null,
{
isValid: true,
parsed: 0,
messages: [],
},
],
[
"",
{
isValid: true,
parsed: 0,
messages: [],
},
],
[
{},
{
isValid: false,
parsed: 0,
messages: ERROR_MESSAGE,
},
],
[
[],
{
isValid: false,
parsed: 0,
messages: ERROR_MESSAGE,
},
],
[
"test",
{
isValid: false,
parsed: 0,
messages: ERROR_MESSAGE,
},
],
[
"1",
{
isValid: true,
parsed: 1,
messages: [],
},
],
[
1,
{
isValid: true,
parsed: 1,
messages: [],
},
],
];
values.forEach(([input, expected]) => {
expect(
totalRecordsCountValidation(input, {} as TableWidgetProps, _),
).toEqual(expected);
});
});
it("uniqueColumnNameValidation - should test with all possible values", () => {
let value = [
{
label: "column1",
},
{
label: "column2",
},
{
label: "column3",
},
];
expect(
uniqueColumnNameValidation(value, {} as TableWidgetProps, _),
).toEqual({
isValid: true,
parsed: value,
messages: [""],
});
value = [
{
label: "column1",
},
{
label: "column2",
},
{
label: "column1",
},
];
expect(
uniqueColumnNameValidation(value, {} as TableWidgetProps, _),
).toEqual({
isValid: false,
parsed: value,
messages: ["Column names should be unique."],
});
});
it("updateColumnStyles - should test with all possible values", () => {
let props: any = {
primaryColumns: {
1: {
id: 1,
style: "someRandomStyleValue",
},
2: {
id: 2,
style: "someRandomStyleValue",
},
3: {
id: 3,
style: "someRandomStyleValue",
},
},
};
expect(
updateColumnStyles(
props as any as TableWidgetProps,
"style",
"someOtherRandomStyleValue",
),
).toEqual([
{
propertyPath: "primaryColumns.1.style",
propertyValue: "someOtherRandomStyleValue",
},
{
propertyPath: "primaryColumns.2.style",
propertyValue: "someOtherRandomStyleValue",
},
{
propertyPath: "primaryColumns.3.style",
propertyValue: "someOtherRandomStyleValue",
},
]);
props = {
dynamicBindingPathList: [
{
key: "primaryColumns.3.style",
},
],
primaryColumns: {
1: {
id: 1,
style: "someRandomStyleValue",
},
2: {
id: 2,
style: "someRandomStyleValue",
},
3: {
id: 3,
style: "someRandomStyleValue",
},
},
};
expect(
updateColumnStyles(
props as any as TableWidgetProps,
"style",
"someOtherRandomStyleValue",
),
).toEqual([
{
propertyPath: "primaryColumns.1.style",
propertyValue: "someOtherRandomStyleValue",
},
{
propertyPath: "primaryColumns.2.style",
propertyValue: "someOtherRandomStyleValue",
},
]);
expect(
updateColumnStyles(
props as any as TableWidgetProps,
"",
"someOtherRandomStyleValue",
),
).toEqual(undefined);
expect(
updateColumnStyles(
{} as any as TableWidgetProps,
"style",
"someOtherRandomStyleValue",
),
).toEqual(undefined);
expect(
updateColumnStyles(
{} as any as TableWidgetProps,
"",
"someOtherRandomStyleValue",
),
).toEqual(undefined);
});
it("updateColumnOrderHook - should test with all possible values", () => {
const defaultStickyValuesForPrimaryCols = {
column1: {
sticky: StickyType.NONE,
},
column2: {
sticky: StickyType.NONE,
},
column3: {
sticky: StickyType.NONE,
},
};
expect(
updateColumnOrderHook(
{
columnOrder: ["column1", "column2"],
primaryColumns: defaultStickyValuesForPrimaryCols,
} as any as TableWidgetProps,
"primaryColumns.column3",
{
id: "column3",
},
),
).toEqual([
{
propertyPath: "columnOrder",
propertyValue: ["column1", "column2", "column3"],
},
{
propertyPath: "primaryColumns.column3",
propertyValue: {
id: "column3",
labelColor: "#FFFFFF",
},
},
]);
expect(
updateColumnOrderHook(
{
columnOrder: ["column1", "column2"],
} as any as TableWidgetProps,
"",
{
id: "column3",
},
),
).toEqual(undefined);
expect(
updateColumnOrderHook({} as any as TableWidgetProps, "", {
id: "column3",
}),
).toEqual(undefined);
expect(
updateColumnOrderHook(
{
columnOrder: ["column1", "column2"],
} as any as TableWidgetProps,
"primaryColumns.column3.iconAlignment",
{
id: "column3",
},
),
).toEqual(undefined);
});
it("getBasePropertyPath - should test with all possible values", () => {
expect(getBasePropertyPath("primaryColumns.test")).toBe("primaryColumns");
expect(getBasePropertyPath("primaryColumns.test.style")).toBe(
"primaryColumns.test",
);
expect(getBasePropertyPath("")).toBe(undefined);
expect(getBasePropertyPath("primaryColumns")).toBe(undefined);
});
describe("hideByColumnType - ", () => {
it("should test with column type that should not be hidden", () => {
const prop = {
primaryColumns: {
column: {
columnType: "text",
},
},
};
expect(
hideByColumnType(
prop as any as TableWidgetProps,
"primaryColumns.column",
["text"] as ColumnTypes[],
true,
),
).toBe(false);
});
it("should test with column type that should be hidden", () => {
const prop = {
primaryColumns: {
column: {
columnType: "select",
},
},
};
expect(
hideByColumnType(
prop as any as TableWidgetProps,
"primaryColumns.column",
["text"] as ColumnTypes[],
true,
),
).toBe(true);
});
it("should test column that should be hidden, with full propertyPath", () => {
const prop = {
primaryColumns: {
column: {
columnType: "select",
},
},
};
expect(
hideByColumnType(
prop as any as TableWidgetProps,
"primaryColumns.column.buttonColor",
["Button"] as any as ColumnTypes[],
),
).toBe(true);
});
it("should test column that should not be hidden, with full propertyPath", () => {
const prop = {
primaryColumns: {
column: {
columnType: "Button",
},
},
};
expect(
hideByColumnType(
prop as any as TableWidgetProps,
"primaryColumns.column.buttonColor",
["Button"] as any as ColumnTypes[],
),
).toBe(false);
});
});
});
describe("uniqueColumnAliasValidation", () => {
it("should validate that duplicate value is not allowed", () => {
expect(
uniqueColumnAliasValidation(
"column",
{
primaryColumns: {
column: {
alias: "column",
},
column1: {
alias: "column",
},
column2: {
alias: "column2",
},
},
} as unknown as TableWidgetProps,
_,
),
).toEqual({
isValid: false,
parsed: "column",
messages: ["Property names should be unique."],
});
});
it("should validate that empty value is not allowed", () => {
expect(
uniqueColumnAliasValidation(
"",
{
primaryColumns: {
column: {
alias: "column",
},
column1: {
alias: "column1",
},
column2: {
alias: "column2",
},
},
} as unknown as TableWidgetProps,
_,
),
).toEqual({
isValid: false,
parsed: "",
messages: ["Property name should not be empty."],
});
});
it("should validate that unique value is allowed", () => {
expect(
uniqueColumnAliasValidation(
"column1",
{
primaryColumns: {
column: {
alias: "column",
},
column1: {
alias: "column1",
},
column2: {
alias: "column2",
},
},
} as unknown as TableWidgetProps,
_,
),
).toEqual({
isValid: true,
parsed: "column1",
messages: [""],
});
});
});
describe("selectColumnOptionsValidation", () => {
describe("- Array of label, values", () => {
it("should check that for empty values are allowed", () => {
["", undefined, null].forEach((value) => {
expect(
selectColumnOptionsValidation(value, {} as TableWidgetProps, _),
).toEqual({
isValid: true,
parsed: [],
messages: [""],
});
});
});
it("should check that value should be an array", () => {
expect(
selectColumnOptionsValidation("test", {} as TableWidgetProps, _),
).toEqual({
isValid: false,
parsed: [],
messages: [
`This value does not evaluate to type Array<{ "label": string | number, "value": string | number | boolean }>`,
],
});
expect(
selectColumnOptionsValidation(1, {} as TableWidgetProps, _),
).toEqual({
isValid: false,
parsed: [],
messages: [
`This value does not evaluate to type Array<{ "label": string | number, "value": string | number | boolean }>`,
],
});
expect(
selectColumnOptionsValidation([], {} as TableWidgetProps, _),
).toEqual({
isValid: true,
parsed: [],
messages: [""],
});
});
it("should check that there are no null or undefined values", () => {
expect(
selectColumnOptionsValidation(
[null, { label: "2", value: "1" }],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: false,
parsed: [],
messages: [
`Invalid entry at index: 0. This value does not evaluate to type: { "label": string | number, "value": string | number | boolean }`,
],
});
});
it("should check that value should be an array of objects", () => {
expect(
selectColumnOptionsValidation([1, 2], {} as TableWidgetProps, _),
).toEqual({
isValid: false,
parsed: [1, 2],
messages: [
`Invalid entry at index: 0. This value does not evaluate to type: { "label": string | number, "value": string | number | boolean }`,
],
});
});
it("should check that each value should have label key", () => {
expect(
selectColumnOptionsValidation(
[{ value: "1" }, { value: "2" }],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: false,
parsed: [{ value: "1" }, { value: "2" }],
messages: [`Invalid entry at index: 0. Missing required key: label`],
});
});
it("should check that each value should have value key", () => {
expect(
selectColumnOptionsValidation(
[{ label: "1" }, { label: "2" }],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: false,
parsed: [{ label: "1" }, { label: "2" }],
messages: [`Invalid entry at index: 0. Missing required key: value`],
});
});
it("should check that each value should have unique value", () => {
expect(
selectColumnOptionsValidation(
[
{ label: "1", value: "1" },
{ label: "2", value: "1" },
],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: false,
parsed: [
{ label: "1", value: "1" },
{ label: "2", value: "1" },
],
messages: [
"Duplicate values found for the following properties, in the array entries, that must be unique -- value.",
],
});
});
it("should check that array of label, value witn invalid values", () => {
expect(
selectColumnOptionsValidation(
[{ label: "1", value: [] }],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: false,
parsed: [{ label: "1", value: [] }],
messages: [
"Invalid entry at index: 0. value does not evaluate to type string | number | boolean",
],
});
expect(
selectColumnOptionsValidation(
[{ label: true, value: "1" }],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: false,
parsed: [{ label: true, value: "1" }],
messages: [
"Invalid entry at index: 0. label does not evaluate to type string | number",
],
});
});
it("should check that array of label, value is valid", () => {
expect(
selectColumnOptionsValidation(
[
{ label: "1", value: "1" },
{ label: "2", value: "2" },
],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: true,
parsed: [
{ label: "1", value: "1" },
{ label: "2", value: "2" },
],
messages: [""],
});
expect(
selectColumnOptionsValidation(
[
{ label: "1", value: 1 },
{ label: "2", value: "2" },
],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: true,
parsed: [
{ label: "1", value: 1 },
{ label: "2", value: "2" },
],
messages: [""],
});
expect(
selectColumnOptionsValidation(
[
{ label: "1", value: true },
{ label: "2", value: "2" },
],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: true,
parsed: [
{ label: "1", value: true },
{ label: "2", value: "2" },
],
messages: [""],
});
expect(
selectColumnOptionsValidation(
[
{ label: 1, value: true },
{ label: "2", value: "2" },
],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: true,
parsed: [
{ label: 1, value: true },
{ label: "2", value: "2" },
],
messages: [""],
});
});
});
describe("- Array of Array of label, values", () => {
it("should check that value should be an array of arrays", () => {
expect(
selectColumnOptionsValidation([[1, 2], 1], {} as TableWidgetProps, _),
).toEqual({
isValid: false,
parsed: [],
messages: [
`This value does not evaluate to type Array<{ "label": string | number, "value": string | number | boolean }>`,
],
});
});
it("should check that value should be an array of arrays of object", () => {
expect(
selectColumnOptionsValidation([[1, 2]], {} as TableWidgetProps, _),
).toEqual({
isValid: false,
parsed: [[1, 2]],
messages: [
`Invalid entry at Row: 0 index: 0. This value does not evaluate to type: { "label": string | number, "value": string | number | boolean }`,
],
});
});
it("should check that each value should have label key", () => {
expect(
selectColumnOptionsValidation(
[[{ value: "1" }, { value: "2" }]],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: false,
parsed: [[{ value: "1" }, { value: "2" }]],
messages: [
`Invalid entry at Row: 0 index: 0. Missing required key: label`,
],
});
expect(
selectColumnOptionsValidation(
[
[
{ label: "1", value: "1" },
{ label: "2", value: "2" },
],
[{ value: "1" }, { value: "2" }],
],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: false,
parsed: [
[
{ label: "1", value: "1" },
{ label: "2", value: "2" },
],
[{ value: "1" }, { value: "2" }],
],
messages: [
`Invalid entry at Row: 1 index: 0. Missing required key: label`,
],
});
});
it("should check that each value should have value key", () => {
expect(
selectColumnOptionsValidation(
[[{ label: "1" }, { label: "2" }]],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: false,
parsed: [[{ label: "1" }, { label: "2" }]],
messages: [
`Invalid entry at Row: 0 index: 0. Missing required key: value`,
],
});
expect(
selectColumnOptionsValidation(
[
[
{ label: "1", value: "1" },
{ label: "2", value: "2" },
],
[{ label: "1" }, { label: "2" }],
],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: false,
parsed: [
[
{ label: "1", value: "1" },
{ label: "2", value: "2" },
],
[{ label: "1" }, { label: "2" }],
],
messages: [
`Invalid entry at Row: 1 index: 0. Missing required key: value`,
],
});
});
it("should check that each value should have unique value", () => {
expect(
selectColumnOptionsValidation(
[
[
{ label: "1", value: "1" },
{ label: "2", value: "1" },
],
],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: false,
parsed: [
[
{ label: "1", value: "1" },
{ label: "2", value: "1" },
],
],
messages: [
"Duplicate values found for the following properties, in the array entries, that must be unique -- value.",
],
});
expect(
selectColumnOptionsValidation(
[
[
{ label: "1", value: "1" },
{ label: "2", value: "2" },
],
[
{ label: "1", value: "1" },
{ label: "2", value: "2" },
],
],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: true,
parsed: [
[
{ label: "1", value: "1" },
{ label: "2", value: "2" },
],
[
{ label: "1", value: "1" },
{ label: "2", value: "2" },
],
],
messages: [""],
});
});
it("should check that array of arrays of label, value is valid", () => {
expect(
selectColumnOptionsValidation(
[
[
{ label: "1", value: "1" },
{ label: "2", value: "2" },
],
[
{ label: "1", value: "1" },
{ label: "2", value: "2" },
],
],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: true,
parsed: [
[
{ label: "1", value: "1" },
{ label: "2", value: "2" },
],
[
{ label: "1", value: "1" },
{ label: "2", value: "2" },
],
],
messages: [""],
});
});
it("should check that array of JSON is valid", () => {
expect(
selectColumnOptionsValidation(
[
JSON.stringify([
{ label: "1", value: "1" },
{ label: "2", value: "2" },
]),
JSON.stringify([
{ label: "1", value: "1" },
{ label: "2", value: "2" },
]),
],
{} as TableWidgetProps,
_,
),
).toEqual({
isValid: true,
parsed: [
[
{ label: "1", value: "1" },
{ label: "2", value: "2" },
],
[
{ label: "1", value: "1" },
{ label: "2", value: "2" },
],
],
messages: [""],
});
});
});
});
describe("updateCustomColumnAliasOnLabelChange", () => {
it("should return the propertyToUpdate array to update alias for the given custom column", () => {
expect(
updateCustomColumnAliasOnLabelChange(
{} as TableWidgetProps,
"primaryColumns.customColumn1.label",
"customColumn12",
),
).toEqual([
{
propertyPath: "primaryColumns.customColumn1.alias",
propertyValue: "customColumn12",
},
]);
});
it("should not return propertyToUpdate array to update alias for the given column", () => {
expect(
updateCustomColumnAliasOnLabelChange(
{} as TableWidgetProps,
"primaryColumns.resume_url.label",
"customColumn12",
),
).toEqual(undefined);
});
it("should not return the propertyToUpdate array to update alias when any property other than label property of the custom column gets changed", () => {
expect(
updateCustomColumnAliasOnLabelChange(
{} as TableWidgetProps,
"primaryColumns.customColumn1.notlabel",
"customColumn12",
),
).toEqual(undefined);
});
it("should return the propertyToUpdate array to update alias for any given custom column", () => {
expect(
updateCustomColumnAliasOnLabelChange(
{} as TableWidgetProps,
"primaryColumns.customColumn12345.label",
"customColumn12",
),
).toEqual([
{
propertyPath: "primaryColumns.customColumn12345.alias",
propertyValue: "customColumn12",
},
]);
});
});
describe("allowedFirstDayOfWeekRange", () => {
it("should return valid object value is within 0 to 6", () => {
expect(allowedFirstDayOfWeekRange(4)).toEqual({
isValid: true,
parsed: 4,
messages: [],
});
});
it("should return valid object value is within 0 to 6", () => {
expect(allowedFirstDayOfWeekRange(0)).toEqual({
isValid: true,
parsed: 0,
messages: [],
});
});
it("should return invalid object when value is not within 0 to 6", () => {
expect(allowedFirstDayOfWeekRange(8)).toEqual({
isValid: false,
parsed: 0,
messages: ["Number should be between 0-6."],
});
});
it("should return invalid object when value is not within 0 to 6", () => {
expect(allowedFirstDayOfWeekRange(-2)).toEqual({
isValid: false,
parsed: 0,
messages: ["Number should be between 0-6."],
});
});
});
|
2,387 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSTableWidget | petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSTableWidget/widget/utilities.test.ts | import type { ColumnProperties, TableStyles } from "../component/Constants";
import { StickyType } from "../component/Constants";
import { ColumnTypes } from "../constants";
import {
convertNumToCompactString,
escapeString,
generateNewColumnOrderFromStickyValue,
getAllTableColumnKeys,
getArrayPropertyValue,
getColumnType,
getDerivedColumns,
getHeaderClassNameOnDragDirection,
getOriginalRowIndex,
getSelectOptions,
getSelectRowIndex,
getSelectRowIndices,
getSourceDataAndCaluclateKeysForEventAutoComplete,
getTableStyles,
reorderColumns,
} from "./utilities";
const getCurrentRowBinding = (
entityName: string,
userInput: string,
withBinding = true,
) => {
let rowBinding = `${entityName}.processedTableData.map((currentRow, currentIndex) => ( ${userInput}))`;
if (withBinding) rowBinding = `{{${rowBinding}}}`;
return rowBinding;
};
describe("getOriginalRowIndex", () => {
it("With no new data ", () => {
const oldTableData = [
{
step: "#1",
task: " a fetch_users wih the Mock DB",
status: "--",
},
{
step: "#2",
task: " a fetch_users wih the Mock DB",
status: "--",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
},
];
const newTableData: Record<string, unknown>[] = [];
const selectedRowIndex = 1;
const result = getOriginalRowIndex(
oldTableData,
newTableData,
selectedRowIndex,
"step",
);
const expected = -1;
expect(result).toStrictEqual(expected);
});
it("With no old data", () => {
const oldTableData: Record<string, unknown>[] = [];
const newTableData = [
{
step: "#1",
task: " a fetch_users wih the Mock DB",
status: "--",
},
{
step: "#2",
task: " a fetch_users wih the Mock DB",
status: "--",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
},
];
const selectedRowIndex = 1;
const result = getOriginalRowIndex(
oldTableData,
newTableData,
selectedRowIndex,
"step",
);
const expected = 1;
expect(result).toStrictEqual(expected);
});
it("With no selectedRowIndex", () => {
const oldTableData = [
{
step: "#1",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "2",
},
];
const newTableData = [
{
step: "#1",
task: " a fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "2",
},
];
const result = getOriginalRowIndex(
oldTableData,
newTableData,
undefined,
"step",
);
const expected = -1;
expect(result).toStrictEqual(expected);
});
it("With no data", () => {
const oldTableData = undefined;
const newTableData = undefined;
const selectedRowIndex = 1;
const result = getOriginalRowIndex(
oldTableData as any as Array<Record<string, unknown>>,
newTableData as any as Array<Record<string, unknown>>,
selectedRowIndex,
"step",
);
const expected = -1;
expect(result).toStrictEqual(expected);
});
it("With selectedRowIndex and data", () => {
const oldTableData = [
{
step: "#1",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#3",
},
];
const newTableData = [
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#3",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#1",
task: " a fetch_users with the Mock DB",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#1",
},
];
const result = getOriginalRowIndex(oldTableData, newTableData, 0, "step");
const expected = 2;
expect(result).toStrictEqual(expected);
});
it("With invalid primaryColumnId", () => {
const oldTableData = [
{
step: "#1",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#3",
},
];
const newTableData = [
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#3",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#1",
task: " a fetch_users with the Mock DB",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#1",
},
];
const result = getOriginalRowIndex(oldTableData, newTableData, 0, "");
const expected = -1;
expect(result).toStrictEqual(expected);
});
it("With new primaryColumn values", () => {
const oldTableData = [
{
step: "#1",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#3",
},
];
const newTableData = [
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#31",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#21",
},
{
step: "#1",
task: " a fetch_users with the Mock DB",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#11",
},
];
const result = getOriginalRowIndex(oldTableData, newTableData, 0, "");
const expected = -1;
expect(result).toStrictEqual(expected);
});
});
describe("selectRowIndex", () => {
it("With new Data", () => {
const oldTableData = [
{
step: "#1",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#3",
},
];
const newTableData = [
{
step: "#1",
task: " a fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#3",
},
];
const selectedRowIndexProp = 0;
const defaultSelectedRowIndex = 0;
const result = getSelectRowIndex(
oldTableData,
newTableData,
defaultSelectedRowIndex,
selectedRowIndexProp,
"step",
);
expect(result).toStrictEqual(0);
});
it("With new Data and different order", () => {
const oldTableData = [
{
step: "#1",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#3",
},
];
const newTableData = [
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#3",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#1",
task: " a fetch_users with the Mock DB",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#1",
},
];
const selectedRowIndexProp = 0;
const defaultSelectedRowIndex = 0;
const result = getSelectRowIndex(
oldTableData,
newTableData,
defaultSelectedRowIndex,
selectedRowIndexProp,
"step",
);
expect(result).toStrictEqual(2);
});
it("With new Data and no primaryColumnId", () => {
const oldTableData = [
{
step: "#1",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#3",
},
];
const newTableData = [
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#3",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#1",
task: " a fetch_users with the Mock DB",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#1",
},
];
const selectedRowIndexProp = -1;
const defaultSelectedRowIndex = 0;
const result = getSelectRowIndex(
oldTableData,
newTableData,
defaultSelectedRowIndex,
selectedRowIndexProp,
undefined,
);
expect(result).toStrictEqual(0);
});
it("With new Data and primaryColumnId, without selectRowIndex", () => {
const oldTableData = [
{
step: "#1",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#3",
},
];
const newTableData = [
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#3",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#1",
task: " a fetch_users with the Mock DB",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#1",
},
];
const selectedRowIndexProp = -1;
const defaultSelectedRowIndex = 0;
const result = getSelectRowIndex(
oldTableData,
newTableData,
defaultSelectedRowIndex,
selectedRowIndexProp,
"step",
);
expect(result).toStrictEqual(0);
});
it("With new Data and primaryColumnId, without selectRowIndex, defaultRowIndex", () => {
const oldTableData = [
{
step: "#1",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#3",
},
];
const newTableData = [
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#3",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#1",
task: " a fetch_users with the Mock DB",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#1",
},
];
const selectedRowIndexProp = -1;
const defaultSelectedRowIndex = -1;
const result = getSelectRowIndex(
oldTableData,
newTableData,
defaultSelectedRowIndex,
selectedRowIndexProp,
"step",
);
expect(result).toStrictEqual(-1);
});
});
describe("selectRowIndices", () => {
it("With no selected index", () => {
const oldTableData = [
{
step: "#1",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "2",
},
];
const newTableData = [
{
step: "#1",
task: " a fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "2",
},
];
const defaultSelectedRowIndices = [0];
const result = getSelectRowIndices(
oldTableData,
newTableData,
defaultSelectedRowIndices,
[],
undefined,
);
expect(result).toEqual([0]);
});
it("With selected indices and defaultRowIndices", () => {
const oldTableData = [
{
step: "#1",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "2",
},
];
const newTableData = [
{
step: "#1",
task: " a fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "2",
},
];
const defaultSelectedRowIndices = undefined;
const result = getSelectRowIndices(
oldTableData,
newTableData,
defaultSelectedRowIndices,
[],
undefined,
);
expect(result).toEqual([]);
});
it("With selected indices and no primaryColumnid", () => {
const oldTableData = [
{
step: "#1",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#3",
},
];
const newTableData = [
{
step: "#1",
task: " a fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#3",
},
];
const defaultSelectedRowIndices = undefined;
const result = getSelectRowIndices(
oldTableData,
newTableData,
defaultSelectedRowIndices,
[0],
undefined,
);
expect(result).toEqual([]);
});
it("With selected indices and primaryColumnid", () => {
const oldTableData = [
{
step: "#1",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#3",
},
];
const newTableData = [
{
step: "#1",
task: " a fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#3",
},
];
const defaultSelectedRowIndices = undefined;
const result = getSelectRowIndices(
oldTableData,
newTableData,
defaultSelectedRowIndices,
[0],
"step",
);
expect(result).toEqual([0]);
});
it("With selected indices, primaryColumnid and new order", () => {
const oldTableData = [
{
step: "#1",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#1",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#3",
},
];
const newTableData = [
{
step: "#3",
task: "Bind the query => fetch_users.data",
status: "--",
__originalIndex__: 0,
__primaryKey__: "#3",
},
{
step: "#2",
task: "fetch_users with the Mock DB",
status: "--",
__originalIndex__: 1,
__primaryKey__: "#2",
},
{
step: "#1",
task: " a fetch_users with the Mock DB",
status: "--",
__originalIndex__: 2,
__primaryKey__: "#1",
},
];
const defaultSelectedRowIndices = undefined;
const result = getSelectRowIndices(
oldTableData,
newTableData,
defaultSelectedRowIndices,
[0, 2],
"step",
);
expect(result).toEqual([2, 0]);
});
});
describe("getAllTableColumnKeys - ", () => {
it("should test with a valid tableData", () => {
const tableData = [
{
name: "jest",
type: "unit",
},
{
name: "cypress",
type: "integration",
},
];
expect(getAllTableColumnKeys(tableData)).toEqual(["name", "type"]);
});
it("should test with a valid tableData with varying schema", () => {
const tableData = [
{
name: "jest",
type: "unit",
typescript: true,
},
{
name: "cypress",
type: "integration",
coverage: "56%",
},
];
expect(getAllTableColumnKeys(tableData)).toEqual([
"name",
"type",
"typescript",
"coverage",
]);
});
it("should test with a empty tableData", () => {
expect(getAllTableColumnKeys([] as Array<Record<string, unknown>>)).toEqual(
[],
);
});
it("should test with undefined", () => {
expect(
getAllTableColumnKeys(undefined as any as Array<Record<string, unknown>>),
).toEqual([]);
});
});
describe("getTableStyles - ", () => {
it("should test with valid values", () => {
expect(
getTableStyles({
textColor: "#fff",
textSize: "HEADING1",
fontStyle: "12",
cellBackground: "#f00",
verticalAlignment: "TOP",
horizontalAlignment: "CENTER",
}) as any as TableStyles,
).toEqual({
textColor: "#fff",
textSize: "HEADING1",
fontStyle: "12",
cellBackground: "#f00",
verticalAlignment: "TOP",
horizontalAlignment: "CENTER",
});
});
});
describe("getDerivedColumns - ", () => {
it("should check with primary columns without derived columns", () => {
const primaryColumns = {
column1: {
isDerived: false,
id: "column1",
},
column2: {
isDerived: false,
id: "column2",
},
column3: {
isDerived: false,
id: "column3",
},
};
expect(
getDerivedColumns(
primaryColumns as any as Record<string, ColumnProperties>,
),
).toEqual({});
});
it("should check with primary columns with derived columns", () => {
const primaryColumns = {
column1: {
isDerived: true,
id: "column1",
},
column2: {
isDerived: false,
id: "column2",
},
column3: {
isDerived: false,
id: "column3",
},
};
expect(
getDerivedColumns(
primaryColumns as any as Record<string, ColumnProperties>,
),
).toEqual({
column1: {
isDerived: true,
id: "column1",
},
});
});
it("should check with primary columns with all derived columns", () => {
const primaryColumns = {
column1: {
isDerived: true,
id: "column1",
},
column2: {
isDerived: true,
id: "column2",
},
column3: {
isDerived: true,
id: "column3",
},
};
expect(
getDerivedColumns(
primaryColumns as any as Record<string, ColumnProperties>,
),
).toEqual({
column1: {
isDerived: true,
id: "column1",
},
column2: {
isDerived: true,
id: "column2",
},
column3: {
isDerived: true,
id: "column3",
},
});
});
it("should check with undefined", () => {
expect(
getDerivedColumns(undefined as any as Record<string, ColumnProperties>),
).toEqual({});
});
it("should check with simple string", () => {
expect(
getDerivedColumns("test" as any as Record<string, ColumnProperties>),
).toEqual({});
});
it("should check with number", () => {
expect(
getDerivedColumns(1 as any as Record<string, ColumnProperties>),
).toEqual({});
});
});
describe("escapeString", () => {
it("should test that string without quotes are retured as it is", () => {
["column", "1", "columnNameThatIsReallyLong"].forEach((str) => {
expect(escapeString(str)).toBe(str);
});
});
it("should test that string with quotes are escaped correctly", () => {
[
{
input: `column"`,
output: `column\"`,
},
{
input: `1"`,
output: `1\"`,
},
{
input: `columnName " ThatIsReallyLong`,
output: `columnName \" ThatIsReallyLong`,
},
].forEach(({ input, output }) => {
expect(escapeString(input)).toBe(output);
});
});
it("should test that string with escaped quotes are returned as it is", () => {
[
`column\"`,
`column\\\"`,
`column\\\\\"`,
`col\\\\\"umn\\\\\"`,
`1\"`,
`columnNameThatIsReallyLong\"`,
].forEach((str) => {
expect(escapeString(str)).toBe(str);
});
});
});
const MOCK_COLUMNS: Record<string, any> = {
id: {
isDerived: false,
computedValue: getCurrentRowBinding("Table1", "currentRow.id"),
textSize: "PARAGRAPH",
index: 0,
isVisible: true,
label: "id",
columnType: "text",
horizontalAlignment: "LEFT",
width: 150,
enableFilter: true,
enableSort: true,
id: "id",
verticalAlignment: "CENTER",
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
name: {
index: 1,
width: 150,
id: "name",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "name",
computedValue: getCurrentRowBinding("Table1", "currentRow.name"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
createdAt: {
index: 2,
width: 150,
id: "createdAt",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "createdAt",
computedValue: getCurrentRowBinding("Table1", "currentRow.createdAt"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
updatedAt: {
index: 3,
width: 150,
id: "updatedAt",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "updatedAt",
computedValue: getCurrentRowBinding("Table1", "currentRow.updatedAt"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
status: {
index: 4,
width: 150,
id: "status",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "status",
computedValue: getCurrentRowBinding("Table1", "currentRow.status"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
gender: {
index: 5,
width: 150,
id: "gender",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "gender",
computedValue: getCurrentRowBinding("Table1", "currentRow.gender"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
avatar: {
index: 6,
width: 150,
id: "avatar",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "avatar",
computedValue: getCurrentRowBinding("Table1", "currentRow.avatar"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
address: {
index: 8,
width: 150,
id: "address",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "address",
computedValue: getCurrentRowBinding("Table1", "currentRow.address"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
role: {
index: 9,
id: "role",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
width: 150,
label: "address",
computedValue: getCurrentRowBinding("Table1", "currentRow.address"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
dob: {
index: 10,
width: 150,
id: "dob",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "dob",
computedValue: getCurrentRowBinding("Table1", "currentRow.dob"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
phoneNo: {
index: 11,
width: 150,
id: "phoneNo",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "phoneNo",
computedValue: getCurrentRowBinding("Table1", "currentRow.phoneNo"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
email: {
isDerived: false,
computedValue: getCurrentRowBinding("Table1", "currentRow.email"),
textSize: "PARAGRAPH",
index: 1,
isVisible: true,
label: "email",
columnType: "text",
horizontalAlignment: "LEFT",
width: 150,
enableFilter: true,
enableSort: true,
id: "email",
verticalAlignment: "CENTER",
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
};
describe("reorderColumns", () => {
it("correctly reorders columns", () => {
const columnOrder = [
"phoneNo",
"id",
"name",
"createdAt",
"updatedAt",
"status",
"gender",
"avatar",
"email",
"address",
"role",
"dob",
];
const expected = {
phoneNo: {
index: 0,
width: 150,
id: "phoneNo",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "phoneNo",
computedValue: getCurrentRowBinding("Table1", "currentRow.phoneNo"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
id: {
isDerived: false,
computedValue: getCurrentRowBinding("Table1", "currentRow.id"),
textSize: "PARAGRAPH",
index: 1,
isVisible: true,
label: "id",
columnType: "text",
horizontalAlignment: "LEFT",
width: 150,
enableFilter: true,
enableSort: true,
id: "id",
verticalAlignment: "CENTER",
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
name: {
index: 2,
width: 150,
id: "name",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "name",
computedValue: getCurrentRowBinding("Table1", "currentRow.name"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
createdAt: {
index: 3,
width: 150,
id: "createdAt",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "createdAt",
computedValue: getCurrentRowBinding("Table1", "currentRow.createdAt"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
updatedAt: {
index: 4,
width: 150,
id: "updatedAt",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "updatedAt",
computedValue: getCurrentRowBinding("Table1", "currentRow.updatedAt"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
status: {
index: 5,
width: 150,
id: "status",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "status",
computedValue: getCurrentRowBinding("Table1", "currentRow.status"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
gender: {
index: 6,
width: 150,
id: "gender",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "gender",
computedValue: getCurrentRowBinding("Table1", "currentRow.gender"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
avatar: {
index: 7,
width: 150,
id: "avatar",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "avatar",
computedValue: getCurrentRowBinding("Table1", "currentRow.avatar"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
email: {
isDerived: false,
computedValue: getCurrentRowBinding("Table1", "currentRow.email"),
textSize: "PARAGRAPH",
index: 8,
isVisible: true,
label: "email",
columnType: "text",
horizontalAlignment: "LEFT",
width: 150,
enableFilter: true,
enableSort: true,
id: "email",
verticalAlignment: "CENTER",
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
address: {
index: 9,
width: 150,
id: "address",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "address",
computedValue: getCurrentRowBinding("Table1", "currentRow.address"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
role: {
index: 10,
id: "role",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
width: 150,
label: "address",
computedValue: getCurrentRowBinding("Table1", "currentRow.address"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
dob: {
index: 11,
width: 150,
id: "dob",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "dob",
computedValue: getCurrentRowBinding("Table1", "currentRow.dob"),
isEditable: false,
isCellEditable: false,
allowCellWrapping: false,
},
};
const result = reorderColumns(MOCK_COLUMNS, columnOrder);
expect(expected).toEqual(result);
});
it("Ignores duplicates in column order and includes all columns", () => {
const columnOrder = [
"phoneNo",
"id",
"name",
"createdAt",
"updatedAt",
"status",
"status",
"gender",
"avatar",
"email",
];
const expected = {
phoneNo: {
index: 0,
width: 150,
id: "phoneNo",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "phoneNo",
computedValue: getCurrentRowBinding("Table1", "currentRow.phoneNo"),
allowCellWrapping: false,
isCellEditable: false,
isEditable: false,
},
id: {
isDerived: false,
computedValue: getCurrentRowBinding("Table1", "currentRow.id"),
textSize: "PARAGRAPH",
index: 1,
isVisible: true,
label: "id",
columnType: "text",
horizontalAlignment: "LEFT",
width: 150,
enableFilter: true,
enableSort: true,
id: "id",
verticalAlignment: "CENTER",
allowCellWrapping: false,
isCellEditable: false,
isEditable: false,
},
name: {
index: 2,
width: 150,
id: "name",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "name",
computedValue: getCurrentRowBinding("Table1", "currentRow.name"),
allowCellWrapping: false,
isCellEditable: false,
isEditable: false,
},
createdAt: {
index: 3,
width: 150,
id: "createdAt",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "createdAt",
computedValue: getCurrentRowBinding("Table1", "currentRow.createdAt"),
allowCellWrapping: false,
isCellEditable: false,
isEditable: false,
},
updatedAt: {
index: 4,
width: 150,
id: "updatedAt",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "updatedAt",
computedValue: getCurrentRowBinding("Table1", "currentRow.updatedAt"),
allowCellWrapping: false,
isCellEditable: false,
isEditable: false,
},
status: {
index: 5,
width: 150,
id: "status",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "status",
computedValue: getCurrentRowBinding("Table1", "currentRow.status"),
allowCellWrapping: false,
isCellEditable: false,
isEditable: false,
},
gender: {
index: 6,
width: 150,
id: "gender",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "gender",
computedValue: getCurrentRowBinding("Table1", "currentRow.gender"),
allowCellWrapping: false,
isCellEditable: false,
isEditable: false,
},
avatar: {
index: 7,
width: 150,
id: "avatar",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "avatar",
computedValue: getCurrentRowBinding("Table1", "currentRow.avatar"),
allowCellWrapping: false,
isCellEditable: false,
isEditable: false,
},
email: {
isDerived: false,
computedValue: getCurrentRowBinding("Table1", "currentRow.email"),
textSize: "PARAGRAPH",
index: 8,
isVisible: true,
label: "email",
columnType: "text",
horizontalAlignment: "LEFT",
width: 150,
enableFilter: true,
enableSort: true,
id: "email",
verticalAlignment: "CENTER",
allowCellWrapping: false,
isCellEditable: false,
isEditable: false,
},
address: {
index: 9,
width: 150,
id: "address",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "address",
computedValue: getCurrentRowBinding("Table1", "currentRow.address"),
allowCellWrapping: false,
isCellEditable: false,
isEditable: false,
},
role: {
index: 10,
id: "role",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
width: 150,
label: "address",
computedValue: getCurrentRowBinding("Table1", "currentRow.address"),
allowCellWrapping: false,
isCellEditable: false,
isEditable: false,
},
dob: {
index: 11,
width: 150,
id: "dob",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "dob",
computedValue: getCurrentRowBinding("Table1", "currentRow.dob"),
allowCellWrapping: false,
isCellEditable: false,
isEditable: false,
},
};
const result = reorderColumns(MOCK_COLUMNS, columnOrder);
expect(expected).toEqual(result);
});
});
describe("getColumnType", () => {
const tableData = [
{
id: 1,
gender: "female",
latitude: -45.7997,
longitude: null,
dob: null,
phone: null,
email: "[email protected]",
image: "https://randomuser.me/api/portraits/med/women/39.jpg",
country: "Germany",
name: "Bene",
checked: true,
},
{
id: 2,
gender: "male",
latitude: "42.9756",
longitude: null,
dob: null,
phone: null,
email: "[email protected]",
image: "https://randomuser.me/api/portraits/med/women/6.jpg",
country: "Netherlandss",
name: "AliceBggg11144",
checked: false,
},
{
id: 3,
gender: "female",
latitude: "-14.0884",
longitude: 27.0428,
dob: null,
phone: null,
email: null,
image: "https://randomuser.me/api/portraits/med/women/88.jpg",
country: "Norway",
name: null,
checked: true,
},
{
id: 4,
gender: "male",
latitude: "-88.0169",
longitude: "-118.7708",
dob: "1984-02-25T07:31:12.723Z",
phone: "594-620-3202",
email: "[email protected]",
image: "https://randomuser.me/api/portraits/med/men/52.jpg",
country: "Cornwall",
name: "Jack1",
},
{
id: 5,
gender: "female",
latitude: "73.6320",
longitude: "-167.3976",
dob: null,
phone: null,
email: "",
image: "https://randomuser.me/api/portraits/med/women/91.jpg",
country: "United Kingdom",
name: "Sue",
premium: false,
},
{
id: 6,
gender: "male",
latitude: "86.1891",
longitude: "-56.8442",
dob: "1959-02-20T02:42:20.579Z",
phone: "61521059",
email: "[email protected]",
image: "https://randomuser.me/api/portraits/med/men/58.jpg",
country: "Norway",
name: "Allih Persson",
},
{
id: 7,
gender: "male",
latitude: "-83.6654",
longitude: "87.6481",
dob: "1952-02-22T18:47:29.476Z",
phone: "(212)-051-1147",
email: "[email protected]",
image: "https://randomuser.me/api/portraits/med/women/30.jpg",
country: "United States",
name: "Julia Armstrong",
},
{
id: 8,
gender: "female",
latitude: "38.7394",
longitude: "-31.7919",
dob: "1955-10-07T11:31:49.823Z",
phone: "(817)-164-4040",
email: "[email protected]",
image: "https://randomuser.me/api/portraits/med/women/88.jpg",
country: "Netherlands",
name: "Shiva Duijf",
},
{
id: 9,
gender: "male",
latitude: "4.5623",
longitude: "9.0901",
dob: null,
phone: null,
email: null,
image: "https://randomuser.me/api/portraits/med/men/30.jpg",
country: "Norway",
name: null,
},
{
id: 10,
gender: "male",
latitude: "-49.4156",
longitude: "-132.3755",
dob: "1977-03-27T02:12:01.151Z",
phone: "212-355-8035",
email: "[email protected]",
image: "https://randomuser.me/api/portraits/med/men/73.jpg",
country: "Canada",
name: "David Mackay",
},
];
it("returns NUMBER column type for number value", () => {
const result = getColumnType(tableData, "id");
expect(ColumnTypes.NUMBER).toEqual(result);
});
it("returns TEXT column type for empty columnKey", () => {
const result = getColumnType(tableData, "");
expect(ColumnTypes.TEXT).toEqual(result);
});
it("returns TEXT column type for string value", () => {
const result = getColumnType(tableData, "gender");
expect(ColumnTypes.TEXT).toEqual(result);
});
it("returns TEXT column type for string columnKey that does not exist in tableData", () => {
const result = getColumnType(tableData, "coordinates");
expect(ColumnTypes.TEXT).toEqual(result);
});
it("returns CHECKBOX column type for columnKey that has boolean columnValue", () => {
const result = getColumnType(tableData, "checked");
expect(ColumnTypes.CHECKBOX).toEqual(result);
});
it("returns proper column type for columnKey that has first few rows data as null", () => {
const result = getColumnType(tableData, "longitude");
expect(ColumnTypes.NUMBER).toEqual(result);
});
it("returns proper column type for columnKey that does not exist in the first few rows", () => {
const result = getColumnType(tableData, "premium");
expect(ColumnTypes.CHECKBOX).toEqual(result);
});
it("returns Date column type for valid Date field", () => {
const result = getColumnType(tableData, "dob");
expect(ColumnTypes.DATE).toEqual(result);
});
});
describe("getSourceDataAndCaluclateKeysForEventAutoComplete", () => {
it("Should test with valid values", () => {
const mockProps = {
type: "TABLE_WIDGET_V2",
widgetName: "Table1",
widgetId: "9oh3qyw84m",
primaryColumns: {
action: {
configureMenuItems: {
config: {
label:
"{{Table1.primaryColumns.action.sourceData.map((currentItem, currentIndex) => ( currentItem.))}}",
},
},
},
},
__evaluation__: {
errors: {
primaryColumns: [],
},
evaluatedValues: {
primaryColumns: {
step: {
index: 0,
width: 150,
id: "step",
originalId: "step",
alias: "step",
columnType: "text",
label: "step",
computedValue: ["#1", "#2", "#3"],
validation: {},
labelColor: "#FFFFFF",
},
action: {
index: 3,
width: 150,
id: "action",
originalId: "action",
alias: "action",
columnType: "menuButton",
label: "action",
computedValue: ["", "", ""],
labelColor: "#FFFFFF",
buttonLabel: ["Action", "Action", "Action"],
menuColor: ["#553DE9", "#553DE9", "#553DE9"],
menuItemsSource: "DYNAMIC",
menuButtonLabel: ["Open Menu", "Open Menu", "Open Menu"],
sourceData: [
{
gender: "male",
name: "Victor",
email: "[email protected]",
},
{
gender: "male",
name: "Tobias",
email: "[email protected]",
},
{
gender: "female",
name: "Jane",
email: "[email protected]",
},
{
gender: "female",
name: "Yaromira",
email: "[email protected]",
},
{
gender: "male",
name: "Andre",
email: "[email protected]",
},
],
configureMenuItems: {
label: "Configure menu items",
id: "config",
config: {
id: "config",
label: ["male", "male", "female", "female", "male"],
isVisible: true,
isDisabled: false,
onClick: "",
backgroundColor: ["red", "red", "tan", "tan", "red"],
iconName: "add-row-top",
iconAlign: "right",
},
},
},
},
},
},
};
const result = getSourceDataAndCaluclateKeysForEventAutoComplete(
mockProps as any,
);
const expected = {
currentItem: {
name: "",
email: "",
gender: "",
},
};
expect(result).toStrictEqual(expected);
});
it("Should test with empty sourceData", () => {
const mockProps = {
type: "TABLE_WIDGET_V2",
widgetName: "Table1",
widgetId: "9oh3qyw84m",
primaryColumns: {
action: {
configureMenuItems: {
config: {
label:
"{{Table1.primaryColumns.action.sourceData.map((currentItem, currentIndex) => ( currentItem.))}}",
},
},
},
},
__evaluation__: {
errors: {
primaryColumns: [],
},
evaluatedValues: {
primaryColumns: {
step: {
index: 0,
width: 150,
id: "step",
originalId: "step",
alias: "step",
columnType: "text",
label: "step",
computedValue: ["#1", "#2", "#3"],
validation: {},
labelColor: "#FFFFFF",
},
action: {
index: 3,
width: 150,
id: "action",
originalId: "action",
alias: "action",
columnType: "menuButton",
label: "action",
computedValue: ["", "", ""],
labelColor: "#FFFFFF",
buttonLabel: ["Action", "Action", "Action"],
menuColor: ["#553DE9", "#553DE9", "#553DE9"],
menuItemsSource: "DYNAMIC",
menuButtonLabel: ["Open Menu", "Open Menu", "Open Menu"],
sourceData: [],
configureMenuItems: {
label: "Configure menu items",
id: "config",
config: {
id: "config",
label: ["male", "male", "female", "female", "male"],
isVisible: true,
isDisabled: false,
onClick: "",
backgroundColor: ["red", "red", "tan", "tan", "red"],
iconName: "add-row-top",
iconAlign: "right",
},
},
},
},
},
},
};
const result = getSourceDataAndCaluclateKeysForEventAutoComplete(
mockProps as any,
);
const expected = { currentItem: {} };
expect(result).toStrictEqual(expected);
});
it("Should test without sourceData", () => {
const mockProps = {
type: "TABLE_WIDGET_V2",
widgetName: "Table1",
widgetId: "9oh3qyw84m",
primaryColumns: {
action: {
configureMenuItems: {
config: {
label:
"{{Table1.primaryColumns.action.sourceData.map((currentItem, currentIndex) => ( currentItem.))}}",
},
},
},
},
__evaluation__: {
errors: {
primaryColumns: [],
},
evaluatedValues: {
primaryColumns: {
step: {
index: 0,
width: 150,
id: "step",
originalId: "step",
alias: "step",
columnType: "text",
label: "step",
computedValue: ["#1", "#2", "#3"],
validation: {},
labelColor: "#FFFFFF",
},
action: {
index: 3,
width: 150,
id: "action",
originalId: "action",
alias: "action",
columnType: "menuButton",
label: "action",
computedValue: ["", "", ""],
labelColor: "#FFFFFF",
buttonLabel: ["Action", "Action", "Action"],
menuColor: ["#553DE9", "#553DE9", "#553DE9"],
menuItemsSource: "DYNAMIC",
menuButtonLabel: ["Open Menu", "Open Menu", "Open Menu"],
configureMenuItems: {
label: "Configure menu items",
id: "config",
config: {
id: "config",
label: ["male", "male", "female", "female", "male"],
isVisible: true,
isDisabled: false,
onClick: "",
backgroundColor: ["red", "red", "tan", "tan", "red"],
iconName: "add-row-top",
iconAlign: "right",
},
},
},
},
},
},
};
const result = getSourceDataAndCaluclateKeysForEventAutoComplete(
mockProps as any,
);
const expected = { currentItem: {} };
expect(result).toStrictEqual(expected);
});
});
describe("getArrayPropertyValue", () => {
it("should test that it returns the same value when value is not of expected type", () => {
expect(getArrayPropertyValue("test", 1)).toEqual("test");
expect(getArrayPropertyValue(1, 1)).toEqual(1);
});
it("should test that it returns the same value when value is empty", () => {
expect(getArrayPropertyValue([], 1)).toEqual([]);
});
it("should test that it returns the correct value when value is just array of label values", () => {
expect(
getArrayPropertyValue([{ label: "test", value: "test" }], 1),
).toEqual([{ label: "test", value: "test" }]);
expect(
getArrayPropertyValue(
[
{ label: "test", value: "test" },
{ label: "test1", value: "test1" },
],
1,
),
).toEqual([
{ label: "test", value: "test" },
{ label: "test1", value: "test1" },
]);
});
it("should test that it returns the correct value when value is an array of array of label values", () => {
expect(
getArrayPropertyValue(
[
[
{
label: "test1",
value: "test1",
},
],
[
{
label: "test2",
value: "test2",
},
],
],
1,
),
).toEqual([
{
label: "test2",
value: "test2",
},
]);
expect(
getArrayPropertyValue(
[
[
{
label: "test1",
value: "test1",
},
{
label: "test2",
value: "test2",
},
],
[
{
label: "test3",
value: "test3",
},
],
],
0,
),
).toEqual([
{
label: "test1",
value: "test1",
},
{
label: "test2",
value: "test2",
},
]);
});
});
describe("generateNewColumnOrderFromStickyValue", () => {
const baseTableConfig: {
primaryColumns: Record<string, Pick<ColumnProperties, "sticky">>;
columnOrder: string[];
columnName: string;
sticky?: string;
} = {
primaryColumns: {
step: {
sticky: StickyType.NONE,
},
task: {
sticky: StickyType.NONE,
},
status: {
sticky: StickyType.NONE,
},
action: {
sticky: StickyType.NONE,
},
},
columnOrder: ["step", "task", "status", "action"],
columnName: "",
sticky: "",
};
let tableConfig: {
primaryColumns: any;
columnOrder: any;
columnName?: string;
sticky?: string | undefined;
};
let newColumnOrder;
const resetValues = (config: {
primaryColumns: any;
columnOrder: any;
columnName?: string;
sticky?: string | undefined;
}) => {
config.primaryColumns = {
step: {
sticky: "",
id: "step",
},
task: {
sticky: "",
id: "task",
},
status: {
sticky: "",
id: "status",
},
action: {
sticky: "",
id: "action",
},
};
config.columnOrder = ["step", "task", "status", "action"];
config.columnName = "";
config.sticky = "";
return config;
};
test("Column order should remain same when leftmost or the right-most columns are frozen", () => {
tableConfig = { ...baseTableConfig };
newColumnOrder = generateNewColumnOrderFromStickyValue(
tableConfig.primaryColumns as any,
tableConfig.columnOrder,
"step",
"left",
);
tableConfig.primaryColumns.step.sticky = "left";
expect(newColumnOrder).toEqual(["step", "task", "status", "action"]);
newColumnOrder = generateNewColumnOrderFromStickyValue(
tableConfig.primaryColumns as any,
tableConfig.columnOrder,
"action",
"right",
);
tableConfig.primaryColumns.action.sticky = "right";
expect(newColumnOrder).toEqual(["step", "task", "status", "action"]);
});
test("Column that is frozen to left should appear first in the column order", () => {
tableConfig = resetValues(baseTableConfig);
newColumnOrder = generateNewColumnOrderFromStickyValue(
tableConfig.primaryColumns as any,
tableConfig.columnOrder,
"action",
"left",
);
expect(newColumnOrder).toEqual(["action", "step", "task", "status"]);
});
test("Column that is frozen to right should appear last in the column order", () => {
tableConfig = resetValues(baseTableConfig);
newColumnOrder = generateNewColumnOrderFromStickyValue(
tableConfig.primaryColumns as any,
tableConfig.columnOrder,
"step",
"right",
);
expect(newColumnOrder).toEqual(["task", "status", "action", "step"]);
});
test("Column that is frozen to left should appear after the last left frozen column in the column order", () => {
tableConfig = resetValues(baseTableConfig);
// Consisder step to be already frozen to left.
tableConfig.primaryColumns.step.sticky = "left";
newColumnOrder = generateNewColumnOrderFromStickyValue(
tableConfig.primaryColumns as any,
tableConfig.columnOrder,
"action",
"left",
);
expect(newColumnOrder).toEqual(["step", "action", "task", "status"]);
});
test("Column that is frozen to right should appear before the first right frozen column in the column order", () => {
tableConfig = resetValues(baseTableConfig);
// Consisder action to be already frozen to right.
tableConfig.primaryColumns.action.sticky = "right";
newColumnOrder = generateNewColumnOrderFromStickyValue(
tableConfig.primaryColumns as any,
tableConfig.columnOrder,
"step",
"right",
);
expect(newColumnOrder).toEqual(["task", "status", "step", "action"]);
});
test("When leftmost and rightmost columns are only frozen, then on unfreeze left column should be first and right most column should at last", () => {
tableConfig = resetValues(baseTableConfig);
// Consisder step to be left frozen and action to be frozen to right.
tableConfig.primaryColumns.step.sticky = "left";
tableConfig.primaryColumns.action.sticky = "right";
newColumnOrder = generateNewColumnOrderFromStickyValue(
tableConfig.primaryColumns as any,
tableConfig.columnOrder,
"step",
"",
);
tableConfig.primaryColumns.step.sticky = "";
expect(newColumnOrder).toEqual(["step", "task", "status", "action"]);
newColumnOrder = generateNewColumnOrderFromStickyValue(
tableConfig.primaryColumns as any,
tableConfig.columnOrder,
"action",
"",
);
expect(newColumnOrder).toEqual(["step", "task", "status", "action"]);
});
test("Unfreezing first column from multiple left frozen columns, should place the unfrozen column after the last frozen column", () => {
tableConfig = resetValues(baseTableConfig);
// Consisder step to be left frozen and action to be frozen to right.
tableConfig.primaryColumns.step.sticky = "left";
tableConfig.primaryColumns.action.sticky = "left";
tableConfig.primaryColumns.task.sticky = "left";
newColumnOrder = generateNewColumnOrderFromStickyValue(
tableConfig.primaryColumns as any,
["step", "action", "task", "status"],
"step",
"",
);
tableConfig.primaryColumns.step.sticky = "";
expect(newColumnOrder).toEqual(["action", "task", "step", "status"]);
});
test("Unfreezing last column from multiple right frozen columns, should place the unfrozen column before the first frozen column", () => {
tableConfig = resetValues(baseTableConfig);
// Consisder step to be left frozen and action to be frozen to right.
tableConfig.primaryColumns.step.sticky = "right";
tableConfig.primaryColumns.action.sticky = "right";
tableConfig.primaryColumns.task.sticky = "right";
newColumnOrder = generateNewColumnOrderFromStickyValue(
tableConfig.primaryColumns as any,
["status", "step", "action", "task"],
"task",
"",
);
tableConfig.primaryColumns.step.sticky = "";
expect(newColumnOrder).toEqual(["status", "task", "step", "action"]);
});
});
describe("getHeaderClassNameOnDragDirection", () => {
test("Should return left highlight class when dragging from right to left", () => {
expect(getHeaderClassNameOnDragDirection(3, 2)).toEqual(
"th header-reorder highlight-left",
);
});
test("Should return right highlight class when dragging from left to right", () => {
expect(getHeaderClassNameOnDragDirection(1, 2)).toEqual(
"th header-reorder highlight-right",
);
});
});
describe("getSelectOptions", () => {
it("Should return select options when user is not adding a new row", () => {
const columnProperties = {
allowSameOptionsInNewRow: true,
selectOptions: [
{
label: "male",
value: "male",
},
{
label: "female",
value: "female",
},
],
};
expect(
getSelectOptions(false, 0, columnProperties as ColumnProperties),
).toEqual([
{
label: "male",
value: "male",
},
{
label: "female",
value: "female",
},
]);
// Check when select options are inside dynamic binding
const columnPropertiesDynamicSelectOptions = {
allowSameOptionsInNewRow: true,
selectOptions: [
[
{
label: "abc",
value: "abc",
},
],
[
{
label: "efg",
value: "efg",
},
],
[
{
label: "xyz",
value: "xyz",
},
],
],
};
expect(
getSelectOptions(
false,
0,
columnPropertiesDynamicSelectOptions as ColumnProperties,
),
).toEqual([
{
label: "abc",
value: "abc",
},
]);
});
it("Should return select options while adding a new row and when 'Same options in new row' option is turned on", () => {
const columnProperties = {
allowSameOptionsInNewRow: true,
selectOptions: [
{
label: "male",
value: "male",
},
{
label: "female",
value: "female",
},
],
};
expect(
getSelectOptions(true, -1, columnProperties as ColumnProperties),
).toEqual([
{
label: "male",
value: "male",
},
{
label: "female",
value: "female",
},
]);
});
it("Should return new row options", () => {
const columnProperties = {
allowSameOptionsInNewRow: false,
newRowSelectOptions: [
{
label: "abc",
value: "abc",
},
],
};
expect(
getSelectOptions(true, -1, columnProperties as ColumnProperties),
).toEqual([
{
label: "abc",
value: "abc",
},
]);
});
});
describe("convertNumToCompactString", () => {
it("formats a number in thousands (K)", () => {
expect(convertNumToCompactString(5000)).toBe("5.0K");
expect(convertNumToCompactString(9999)).toBe("10.0K"); // Rounding
expect(convertNumToCompactString(123456)).toBe("123.5K"); // Rounding with precision
});
it("formats a number in millions (M)", () => {
expect(convertNumToCompactString(1500000)).toBe("1.5M");
expect(convertNumToCompactString(9999999)).toBe("10.0M"); // Rounding
expect(convertNumToCompactString(123456789)).toBe("123.5M"); // Rounding with precision
});
it("formats a number less than 1000 as is", () => {
expect(convertNumToCompactString(42)).toBe("42");
expect(convertNumToCompactString(999)).toBe("999");
});
});
|
2,438 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/helpers.test.ts | import { fn_keys, stringifyFnsInObject } from "./helpers";
describe("stringifyFnsInObject", () => {
it("includes full path of key having a function in the parent object", () => {
const obj = {
key1: "value",
key2: {
key3: {
fnKey: () => {},
},
},
};
const result = stringifyFnsInObject(obj);
expect(result[fn_keys]).toEqual(["key2.key3.fnKey"]);
expect(result).toEqual({
__fn_keys__: ["key2.key3.fnKey"],
key1: "value",
key2: {
key3: {
fnKey: "() => { }",
},
},
});
});
it("includes an array index if a function is present inside an array", () => {
const obj = {
key1: "value",
key2: {
key3: {
key4: ["string1", () => {}, "string3"],
},
},
};
const result = stringifyFnsInObject(obj);
expect(result[fn_keys]).toEqual(["key2.key3.key4.[1]"]);
expect(result).toEqual({
__fn_keys__: ["key2.key3.key4.[1]"],
key1: "value",
key2: {
key3: {
key4: ["string1", "() => { }", "string3"],
},
},
});
});
it("includes an array index if a function is present inside a nested object inside an array", () => {
const obj = {
key1: "value",
key2: {
key3: {
key4: ["string1", { key5: () => {}, key6: "value" }, "string3"],
},
},
};
const result = stringifyFnsInObject(obj);
expect(result[fn_keys]).toEqual(["key2.key3.key4.[1].key5"]);
expect(result).toEqual({
__fn_keys__: ["key2.key3.key4.[1].key5"],
key1: "value",
key2: {
key3: {
key4: ["string1", { key5: "() => { }", key6: "value" }, "string3"],
},
},
});
});
it("includes a nested array index if a function is present inside a nested array inside an array", () => {
const obj = {
key1: "value",
key2: {
key3: {
key4: ["string1", [() => {}], "string3"],
},
},
};
const result = stringifyFnsInObject(obj);
expect(result[fn_keys]).toEqual(["key2.key3.key4.[1].[0]"]);
expect(result).toEqual({
__fn_keys__: ["key2.key3.key4.[1].[0]"],
key1: "value",
key2: {
key3: {
key4: ["string1", ["() => { }"], "string3"],
},
},
});
});
});
|
2,450 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/JSObject/test.ts | import type { ConfigTree, UnEvalTree } from "entities/DataTree/dataTreeTypes";
import { getUpdatedLocalUnEvalTreeAfterJSUpdates } from ".";
describe("updateJSCollectionInUnEvalTree", function () {
it("updates async value of jsAction", () => {
const jsUpdates = {
JSObject1: {
parsedBody: {
body: "export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\tmyFun1: () => {\n\t\t//write code here\n\t\t\n\t},\n\tmyFun2: () => {\n\t\t//use async-await or promises\n\t\tyeso\n\t}\n}",
actions: [
{
name: "myFun1",
body: "() => {}",
arguments: [],
},
{
name: "myFun2",
body: "() => {\n yeso;\n}",
arguments: [],
},
],
variables: [
{
name: "myVar1",
value: "[]",
},
{
name: "myVar2",
value: "{}",
},
],
},
id: "64013546b956c26882acc587",
},
};
const JSObject1Config = {
JSObject1: {
actionId: "64013546b956c26882acc587",
meta: {
myFun1: {
arguments: [],
confirmBeforeExecute: false,
},
myFun2: {
arguments: [],
confirmBeforeExecute: false,
},
},
name: "JSObject1",
pluginType: "JS",
ENTITY_TYPE: "JSACTION",
bindingPaths: {
body: "SMART_SUBSTITUTE",
myVar1: "SMART_SUBSTITUTE",
myVar2: "SMART_SUBSTITUTE",
myFun1: "SMART_SUBSTITUTE",
myFun2: "SMART_SUBSTITUTE",
},
reactivePaths: {
body: "SMART_SUBSTITUTE",
myVar1: "SMART_SUBSTITUTE",
myVar2: "SMART_SUBSTITUTE",
myFun1: "SMART_SUBSTITUTE",
myFun2: "SMART_SUBSTITUTE",
},
dynamicBindingPathList: [
{
key: "body",
},
{
key: "myVar1",
},
{
key: "myVar2",
},
{
key: "myFun1",
},
{
key: "myFun2",
},
],
variables: ["myVar1", "myVar2"],
dependencyMap: {
body: ["myFun1", "myFun2"],
},
},
};
const JSObject1 = {
myVar1: "[]",
myVar2: "{}",
myFun1: new String("() => {}"),
myFun2: new String("async () => {\n yeso;\n}"),
body: "export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\tmyFun1: () => {\n\t\t//write code here\n\t\t\n\t},\n\tmyFun2: () => {\n\t\t//use async-await or promises\n\t\tyeso\n\t}\n}",
ENTITY_TYPE: "JSACTION",
};
(JSObject1["myFun1"] as any).data = {};
(JSObject1["myFun2"] as any).data = {};
const localUnEvalTree = {
JSObject1,
} as unknown as UnEvalTree;
const actualResult = getUpdatedLocalUnEvalTreeAfterJSUpdates(
jsUpdates,
localUnEvalTree,
JSObject1Config as unknown as ConfigTree,
);
const expectedJSObject = {
myVar1: "[]",
myVar2: "{}",
myFun1: new String("() => {}"),
myFun2: new String("() => {\n yeso;\n}"),
body: "export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\tmyFun1: () => {\n\t\t//write code here\n\t\t\n\t},\n\tmyFun2: () => {\n\t\t//use async-await or promises\n\t\tyeso\n\t}\n}",
ENTITY_TYPE: "JSACTION",
};
(expectedJSObject["myFun1"] as any).data = {};
(expectedJSObject["myFun2"] as any).data = {};
const expectedResult = {
JSObject1: expectedJSObject,
};
expect(expectedResult).toStrictEqual(actualResult);
});
});
|
2,452 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/JSObject | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/JSObject/__test__/JSVariableFactory.test.ts | import ExecutionMetaData from "workers/Evaluation/fns/utils/ExecutionMetaData";
import type { JSActionEntity } from "@appsmith/entities/DataTree/types";
import TriggerEmitter, {
jsVariableUpdatesHandlerWrapper,
} from "workers/Evaluation/fns/utils/TriggerEmitter";
import JSObjectCollection from "../Collection";
const applyJSVariableUpdatesToEvalTreeMock = jest.fn();
jest.mock("../JSVariableUpdates.ts", () => ({
...jest.requireActual("../JSVariableUpdates.ts"),
applyJSVariableUpdatesToEvalTree: (...args: any[]) => {
applyJSVariableUpdatesToEvalTreeMock(args);
},
}));
jest.mock("../../../../utils/MessageUtil.ts", () => ({
...jest.requireActual("../../../../utils/MessageUtil.ts"),
sendMessage: jest.fn(),
}));
TriggerEmitter.on(
"process_js_variable_updates",
jsVariableUpdatesHandlerWrapper,
);
describe("JSVariableFactory", () => {
it("trigger setters with JSVariableUpdates enabled", async () => {
const jsObject = {
number: 1,
string: "aa",
object: { a: 1 },
array: [],
map: new Map(),
set: new Set(),
weakMap: new WeakMap(),
weakSet: new WeakSet(),
} as unknown as JSActionEntity;
Object.entries(jsObject).forEach(([k, v]) =>
JSObjectCollection.setVariableValue(v, `JSObject1.${k}`),
);
const proxiedJSObject =
JSObjectCollection.getVariablesForEvaluationContext("JSObject1");
ExecutionMetaData.setExecutionMetaData({
enableJSVarUpdateTracking: true,
});
proxiedJSObject.number = 5;
proxiedJSObject.string = "hello world";
proxiedJSObject.object.a = { b: 2 };
proxiedJSObject.array.push("hello");
proxiedJSObject.map.set("a", 1);
proxiedJSObject.set.add("hello");
await new Promise((resolve) => setTimeout(resolve, 100));
expect(applyJSVariableUpdatesToEvalTreeMock).toBeCalledTimes(1);
expect(applyJSVariableUpdatesToEvalTreeMock).toBeCalledWith([
{
"JSObject1.number": {
method: "SET",
path: "JSObject1.number",
value: 5,
},
"JSObject1.string": {
method: "SET",
path: "JSObject1.string",
value: "hello world",
},
"JSObject1.object": {
method: "GET",
path: "JSObject1.object",
},
"JSObject1.array": {
method: "GET",
path: "JSObject1.array",
},
"JSObject1.map": {
method: "GET",
path: "JSObject1.map",
},
"JSObject1.set": {
method: "GET",
path: "JSObject1.set",
},
},
]);
applyJSVariableUpdatesToEvalTreeMock.mockClear();
});
it("trigger setters with JSVariableUpdates disabled", async () => {
const jsObject = {
number: 1,
string: "aa",
object: { a: 1 },
array: [],
map: new Map(),
set: new Set(),
weakMap: new WeakMap(),
weakSet: new WeakSet(),
} as unknown as JSActionEntity;
Object.entries(jsObject).forEach(([k, v]) =>
JSObjectCollection.setVariableValue(v, `JSObject1.${k}`),
);
const proxiedJSObject =
JSObjectCollection.getVariablesForEvaluationContext("JSObject1");
ExecutionMetaData.setExecutionMetaData({
enableJSVarUpdateTracking: false,
});
proxiedJSObject.number = 5;
proxiedJSObject.string = "hello world";
proxiedJSObject.object.a = { b: 2 };
proxiedJSObject.array.push("hello");
proxiedJSObject.map.set("a", 1);
proxiedJSObject.set.add("hello");
await new Promise((resolve) => setTimeout(resolve, 100));
expect(applyJSVariableUpdatesToEvalTreeMock).toBeCalledTimes(0);
});
it("trigger getters with JSVariableUpdates enabled", async () => {
const jsObject = {
number: 1,
string: "aa",
object: { a: 1 },
array: [],
map: new Map(),
set: new Set(),
weakMap: new WeakMap(),
weakSet: new WeakSet(),
} as unknown as JSActionEntity;
Object.entries(jsObject).forEach(([k, v]) =>
JSObjectCollection.setVariableValue(v, `JSObject1.${k}`),
);
const proxiedJSObject =
JSObjectCollection.getVariablesForEvaluationContext("JSObject1");
ExecutionMetaData.setExecutionMetaData({
enableJSVarUpdateTracking: true,
});
proxiedJSObject.number;
proxiedJSObject.string;
proxiedJSObject.object.a;
proxiedJSObject.array.push();
proxiedJSObject.map.set;
proxiedJSObject.set.add;
await new Promise((resolve) => setTimeout(resolve, 100));
expect(applyJSVariableUpdatesToEvalTreeMock).toBeCalledWith([
{
"JSObject1.array": {
method: "GET",
path: "JSObject1.array",
},
"JSObject1.map": {
method: "GET",
path: "JSObject1.map",
},
"JSObject1.number": {
method: "GET",
path: "JSObject1.number",
},
"JSObject1.object": {
method: "GET",
path: "JSObject1.object",
},
"JSObject1.set": {
method: "GET",
path: "JSObject1.set",
},
"JSObject1.string": {
method: "GET",
path: "JSObject1.string",
},
},
]);
});
});
|
2,453 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/JSObject | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/JSObject/__test__/mutation.test.ts | import type { DataTree } from "entities/DataTree/dataTreeTypes";
import { ENTITY_TYPE_VALUE } from "entities/DataTree/dataTreeFactory";
import { createEvaluationContext } from "workers/Evaluation/evaluate";
import JSObjectCollection from "../Collection";
import ExecutionMetaData from "workers/Evaluation/fns/utils/ExecutionMetaData";
import TriggerEmitter, {
jsVariableUpdatesHandlerWrapper,
} from "workers/Evaluation/fns/utils/TriggerEmitter";
jest.mock("../../evalTreeWithChanges.ts", () => {
return {
evalTreeWithChanges: () => ({}),
};
});
const applyJSVariableUpdatesToEvalTreeMock = jest.fn();
jest.mock("../JSVariableUpdates.ts", () => ({
...jest.requireActual("../JSVariableUpdates.ts"),
applyJSVariableUpdatesToEvalTree: (...args: any[]) => {
applyJSVariableUpdatesToEvalTreeMock(args);
},
}));
jest.mock("../../../../utils/MessageUtil.ts", () => ({
...jest.requireActual("../../../../utils/MessageUtil.ts"),
sendMessage: jest.fn(),
}));
jest.mock("../../handlers/evalTree", () => {
const evalTree = {
JSObject1: {
var: {},
var2: new Set([1, 2]),
variables: ["var", "var2"],
ENTITY_TYPE: "JSACTION",
},
};
return {
dataTreeEvaluator: {
setupUpdateTreeWithDifferences: () => ({
evalOrder: [],
unEvalUpdates: [],
}),
evalAndValidateSubTree: () => ({ evalMetaUpdates: [] }),
evalTree,
getEvalTree() {
return this.evalTree;
},
oldConfigTree: {
JSObject1: {
variables: ["var", "var2"],
ENTITY_TYPE: "JSACTION",
},
},
},
};
});
TriggerEmitter.on(
"process_js_variable_updates",
jsVariableUpdatesHandlerWrapper,
);
describe("Mutation", () => {
it("Global scope value mutation tracking", async () => {
const dataTree = {
JSObject1: {
var: {},
var2: new Set([1, 2]),
variables: ["var", "var2"],
ENTITY_TYPE: ENTITY_TYPE_VALUE.JSACTION,
},
};
JSObjectCollection.setVariableValue(
dataTree.JSObject1.var,
"JSObject1.var",
);
JSObjectCollection.setVariableValue(
dataTree.JSObject1.var2,
"JSObject1.var2",
);
const evalContext = createEvaluationContext({
dataTree: dataTree as unknown as DataTree,
isTriggerBased: true,
removeEntityFunctions: true,
});
ExecutionMetaData.setExecutionMetaData({
enableJSVarUpdateTracking: true,
});
Object.assign(self, evalContext);
eval(`
JSObject1.var = {};
JSObject1.var.b = {};
JSObject1.var.b.a = [];
JSObject1.var.b.a.push(2);
JSObject1.var2.add(3);
`);
await new Promise((resolve) => setTimeout(resolve, 100));
ExecutionMetaData.setExecutionMetaData({
enableJSVarUpdateTracking: false,
});
expect(applyJSVariableUpdatesToEvalTreeMock).toBeCalledWith([
{
"JSObject1.var": { method: "GET", path: "JSObject1.var" },
"JSObject1.var2": { method: "GET", path: "JSObject1.var2" },
},
]);
});
});
|
2,454 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/__tests__/Actions.test.ts | import type { ActionEntity } from "@appsmith/entities/DataTree/types";
import type { DataTree } from "entities/DataTree/dataTreeTypes";
import { ENTITY_TYPE_VALUE } from "entities/DataTree/dataTreeFactory";
import { PluginType } from "entities/Action";
import type { EvalContext } from "workers/Evaluation/evaluate";
import { createEvaluationContext } from "workers/Evaluation/evaluate";
import { MessageType } from "utils/MessageUtil";
import {
addDataTreeToContext,
addPlatformFunctionsToEvalContext,
} from "@appsmith/workers/Evaluation/Actions";
import TriggerEmitter, { BatchKey } from "../fns/utils/TriggerEmitter";
jest.mock("lodash/uniqueId");
describe("Add functions", () => {
const workerEventMock = jest.fn();
self.postMessage = (payload: any) => {
workerEventMock(payload);
};
self["$isDataField"] = false;
const dataTree: DataTree = {
action1: {
actionId: "123",
pluginId: "",
data: {},
config: {},
datasourceUrl: "",
pluginType: PluginType.API,
dynamicBindingPathList: [],
name: "action1",
bindingPaths: {},
reactivePaths: {},
isLoading: false,
run: {},
clear: {},
responseMeta: { isExecutionSuccess: false },
ENTITY_TYPE: ENTITY_TYPE_VALUE.ACTION,
dependencyMap: {},
logBlackList: {},
} as ActionEntity,
};
const evalContext = createEvaluationContext({
dataTree,
configTree: {},
isTriggerBased: true,
context: {},
});
addPlatformFunctionsToEvalContext(evalContext);
const messageCreator = (type: string, body: unknown) => ({
messageId: expect.stringContaining(type),
messageType: MessageType.REQUEST,
body,
});
beforeEach(() => {
workerEventMock.mockReset();
self.postMessage = workerEventMock;
});
it("action.clear works", () => {
expect(evalContext.action1.clear()).resolves.toBe({});
const arg = workerEventMock.mock.calls[0][0];
expect(arg).toEqual(
messageCreator("PROCESS_TRIGGER", {
data: {
enableJSFnPostProcessors: true,
enableJSVarUpdateTracking: true,
trigger: {
type: "CLEAR_PLUGIN_ACTION",
payload: {
actionId: "123",
},
},
eventType: undefined,
triggerMeta: {
source: {},
triggerPropertyName: undefined,
},
},
method: "PROCESS_TRIGGER",
}),
);
});
it("navigateTo works", () => {
const pageNameOrUrl = "www.google.com";
const params = "{ param1: value1 }";
const target = "NEW_WINDOW";
expect(evalContext.navigateTo(pageNameOrUrl, params, target)).resolves.toBe(
{},
);
expect(workerEventMock).lastCalledWith(
messageCreator("PROCESS_TRIGGER", {
data: {
enableJSFnPostProcessors: true,
enableJSVarUpdateTracking: true,
trigger: {
type: "NAVIGATE_TO",
payload: {
pageNameOrUrl,
params,
target,
},
},
eventType: undefined,
triggerMeta: {
source: {},
triggerPropertyName: undefined,
},
},
method: "PROCESS_TRIGGER",
}),
);
});
it("showAlert works", () => {
const message = "Alert message";
const style = "info";
expect(evalContext.showAlert(message, style)).resolves.toBe({});
expect(workerEventMock).lastCalledWith(
messageCreator("PROCESS_TRIGGER", {
data: {
enableJSFnPostProcessors: true,
enableJSVarUpdateTracking: true,
trigger: {
type: "SHOW_ALERT",
payload: {
message,
style,
},
},
eventType: undefined,
triggerMeta: {
source: {},
triggerPropertyName: undefined,
},
},
method: "PROCESS_TRIGGER",
}),
);
});
it("showModal works", () => {
const modalName = "Modal 1";
expect(evalContext.showModal(modalName)).resolves.toBe({});
expect(workerEventMock).lastCalledWith(
messageCreator("PROCESS_TRIGGER", {
data: {
enableJSFnPostProcessors: true,
enableJSVarUpdateTracking: true,
trigger: {
type: "SHOW_MODAL_BY_NAME",
payload: {
modalName,
},
},
eventType: undefined,
triggerMeta: {
source: {},
triggerPropertyName: undefined,
},
},
method: "PROCESS_TRIGGER",
}),
);
});
it("closeModal works", () => {
const modalName = "Modal 1";
expect(evalContext.closeModal(modalName)).resolves.toBe({});
expect(workerEventMock).lastCalledWith(
messageCreator("PROCESS_TRIGGER", {
data: {
enableJSFnPostProcessors: true,
enableJSVarUpdateTracking: true,
trigger: {
type: "CLOSE_MODAL",
payload: {
modalName,
},
},
eventType: undefined,
triggerMeta: {
source: {},
triggerPropertyName: undefined,
},
},
method: "PROCESS_TRIGGER",
}),
);
});
it("storeValue works", () => {
const key = "some";
const value = "thing";
const persist = false;
const mockStoreUpdates = jest.fn();
TriggerEmitter.on(BatchKey.process_store_updates, mockStoreUpdates);
expect(evalContext.storeValue(key, value, persist)).resolves.toStrictEqual(
{},
);
expect(mockStoreUpdates).toBeCalledWith({
payload: {
key: "some",
persist: false,
value: "thing",
},
type: "STORE_VALUE",
});
TriggerEmitter.removeListener(
BatchKey.process_store_updates,
mockStoreUpdates,
);
mockStoreUpdates.mockClear();
});
it("removeValue works", () => {
const key = "some";
const mockStoreUpdates = jest.fn();
TriggerEmitter.on(BatchKey.process_store_updates, mockStoreUpdates);
expect(evalContext.removeValue(key)).resolves.toStrictEqual({});
expect(mockStoreUpdates).toBeCalledWith({
payload: {
key,
},
type: "REMOVE_VALUE",
});
TriggerEmitter.removeListener(
BatchKey.process_store_updates,
mockStoreUpdates,
);
});
it("clearStore works", async () => {
const mockStoreUpdates = jest.fn();
TriggerEmitter.on(BatchKey.process_store_updates, mockStoreUpdates);
expect(evalContext.clearStore()).resolves.toStrictEqual({});
expect(mockStoreUpdates).toBeCalledWith({
payload: null,
type: "CLEAR_STORE",
});
TriggerEmitter.removeListener(
BatchKey.process_store_updates,
mockStoreUpdates,
);
});
it("download works", () => {
const data = "file";
const name = "downloadedFile.txt";
const type = "text";
expect(evalContext.download(data, name, type)).resolves.toBe({});
expect(workerEventMock).lastCalledWith(
messageCreator("PROCESS_TRIGGER", {
data: {
enableJSFnPostProcessors: true,
enableJSVarUpdateTracking: true,
trigger: {
type: "DOWNLOAD",
payload: {
data,
name,
type,
},
},
eventType: undefined,
triggerMeta: {
source: {},
triggerPropertyName: undefined,
},
},
method: "PROCESS_TRIGGER",
}),
);
});
it("copyToClipboard works", () => {
const data = "file";
expect(evalContext.copyToClipboard(data)).resolves.toBe({});
expect(workerEventMock).lastCalledWith(
messageCreator("PROCESS_TRIGGER", {
data: {
enableJSFnPostProcessors: true,
enableJSVarUpdateTracking: true,
trigger: {
type: "COPY_TO_CLIPBOARD",
payload: {
data,
options: { debug: undefined, format: undefined },
},
},
eventType: undefined,
triggerMeta: {
source: {},
triggerPropertyName: undefined,
},
},
method: "PROCESS_TRIGGER",
}),
);
});
it("resetWidget works", () => {
const widgetName = "widget1";
const resetChildren = true;
expect(evalContext.resetWidget(widgetName, resetChildren)).resolves.toBe(
{},
);
expect(workerEventMock).lastCalledWith(
messageCreator("PROCESS_TRIGGER", {
data: {
enableJSFnPostProcessors: true,
enableJSVarUpdateTracking: true,
trigger: {
type: "RESET_WIDGET_META_RECURSIVE_BY_NAME",
payload: {
widgetName,
resetChildren,
},
},
eventType: undefined,
triggerMeta: {
source: {},
triggerPropertyName: undefined,
},
},
method: "PROCESS_TRIGGER",
}),
);
});
});
const dataTree = {
Text1: {
widgetName: "Text1",
displayName: "Text",
type: "TEXT_WIDGET",
hideCard: false,
animateLoading: true,
overflow: "SCROLL",
fontFamily: "Nunito Sans",
parentColumnSpace: 15.0625,
dynamicTriggerPathList: [],
leftColumn: 4,
dynamicBindingPathList: [],
shouldTruncate: false,
text: '"2022-11-27T21:36:00.128Z"',
key: "gt93hhlp15",
isDeprecated: false,
rightColumn: 29,
textAlign: "LEFT",
dynamicHeight: "FIXED",
widgetId: "ajg9fjegvr",
isVisible: true,
fontStyle: "BOLD",
textColor: "#231F20",
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
borderRadius: "0.375rem",
maxDynamicHeight: 9000,
fontSize: "1rem",
minDynamicHeight: 4,
value: '"2022-11-27T21:36:00.128Z"',
defaultProps: {},
defaultMetaProps: [],
logBlackList: {
value: true,
},
meta: {},
propertyOverrideDependency: {},
overridingPropertyPaths: {},
bindingPaths: {
text: "TEMPLATE",
isVisible: "TEMPLATE",
},
reactivePaths: {
value: "TEMPLATE",
fontFamily: "TEMPLATE",
},
triggerPaths: {},
validationPaths: {},
ENTITY_TYPE: "WIDGET",
privateWidgets: {},
__evaluation__: {
errors: {},
evaluatedValues: {},
},
backgroundColor: "",
borderColor: "",
},
appsmith: {
store: {},
geolocation: {
canBeRequested: true,
currentPosition: {},
},
mode: "EDIT",
ENTITY_TYPE: "APPSMITH",
},
Api2: {
run: {},
clear: {},
name: "Api2",
pluginType: "API",
config: {},
dynamicBindingPathList: [
{
key: "config.path",
},
],
responseMeta: {
isExecutionSuccess: false,
},
ENTITY_TYPE: "ACTION",
isLoading: false,
bindingPaths: {
"config.path": "TEMPLATE",
"config.body": "SMART_SUBSTITUTE",
"config.pluginSpecifiedTemplates[1].value": "SMART_SUBSTITUTE",
"config.pluginSpecifiedTemplates[2].value.limitBased.limit.value":
"SMART_SUBSTITUTE",
},
reactivePaths: {
data: "TEMPLATE",
isLoading: "TEMPLATE",
datasourceUrl: "TEMPLATE",
"config.path": "TEMPLATE",
"config.body": "SMART_SUBSTITUTE",
"config.pluginSpecifiedTemplates[1].value": "SMART_SUBSTITUTE",
},
dependencyMap: {
"config.body": ["config.pluginSpecifiedTemplates[0].value"],
},
logBlackList: {},
datasourceUrl: "",
__evaluation__: {
errors: {
config: [],
},
evaluatedValues: {
"config.path": "/users/undefined",
config: {
timeoutInMillisecond: 10000,
paginationType: "NONE",
path: "/users/test",
headers: [],
encodeParamsToggle: true,
queryParameters: [],
bodyFormData: [],
httpMethod: "GET",
selfReferencingDataPaths: [],
pluginSpecifiedTemplates: [
{
value: true,
},
],
formData: {
apiContentType: "none",
},
},
},
},
},
JSObject1: {
name: "JSObject1",
actionId: "637cda3b2f8e175c6f5269d5",
pluginType: "JS",
ENTITY_TYPE: "JSACTION",
body: "export default {\n\tstoreTest2: () => {\n\t\tlet values = [\n\t\t\t\t\tstoreValue('val1', 'number 1'),\n\t\t\t\t\tstoreValue('val2', 'number 2'),\n\t\t\t\t\tstoreValue('val3', 'number 3'),\n\t\t\t\t\tstoreValue('val4', 'number 4')\n\t\t\t\t];\n\t\treturn Promise.all(values)\n\t\t\t.then(() => {\n\t\t\tshowAlert(JSON.stringify(appsmith.store))\n\t\t})\n\t\t\t.catch((err) => {\n\t\t\treturn showAlert('Could not store values in store ' + err.toString());\n\t\t})\n\t},\n\tnewFunction: function() {\n\t\tJSObject1.storeTest()\n\t}\n}",
meta: {
newFunction: {
arguments: [],
isAsync: false,
confirmBeforeExecute: false,
},
storeTest2: {
arguments: [],
isAsync: true,
confirmBeforeExecute: false,
},
},
bindingPaths: {
body: "SMART_SUBSTITUTE",
newFunction: "SMART_SUBSTITUTE",
storeTest2: "SMART_SUBSTITUTE",
},
reactivePaths: {
body: "SMART_SUBSTITUTE",
newFunction: "SMART_SUBSTITUTE",
storeTest2: "SMART_SUBSTITUTE",
},
dynamicBindingPathList: [
{
key: "body",
},
{
key: "newFunction",
},
{
key: "storeTest2",
},
],
variables: [],
dependencyMap: {
body: ["newFunction", "storeTest2"],
},
__evaluation__: {
errors: {
storeTest2: [],
newFunction: [],
body: [],
},
},
},
};
const configTree = {};
describe("Test addDataTreeToContext method", () => {
const evalContext: EvalContext = {};
beforeAll(() => {
addDataTreeToContext({
EVAL_CONTEXT: evalContext,
dataTree: dataTree as unknown as DataTree,
configTree,
isTriggerBased: true,
});
addPlatformFunctionsToEvalContext(evalContext);
});
it("1. Assert platform actions are added", () => {
const frameworkActions = {
navigateTo: true,
showAlert: true,
showModal: true,
closeModal: true,
storeValue: true,
removeValue: true,
clearStore: true,
download: true,
copyToClipboard: true,
resetWidget: true,
postWindowMessage: true,
};
for (const actionName of Object.keys(frameworkActions)) {
expect(evalContext).toHaveProperty(actionName);
expect(typeof evalContext[actionName]).toBe("function");
}
});
it("2. Assert Api has run and clear method", () => {
expect(evalContext.Api2).toHaveProperty("run");
expect(evalContext.Api2).toHaveProperty("clear");
expect(typeof evalContext.Api2.run).toBe("function");
expect(typeof evalContext.Api2.clear).toBe("function");
});
it("3. Assert input dataTree is not mutated", () => {
expect(typeof dataTree.Api2.run).not.toBe("function");
});
});
|
2,456 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/__tests__/errorModifier.test.ts | import type { DataTree } from "entities/DataTree/dataTreeTypes";
import {
ActionInDataFieldErrorModifier,
TypeErrorModifier,
errorModifier,
} from "../errorModifier";
import DependencyMap from "entities/DependencyMap";
import { APP_MODE } from "entities/App";
describe("Test error modifier", () => {
const dataTree = {
Api2: {
run: {},
clear: {},
name: "Api2",
pluginType: "API",
config: {},
dynamicBindingPathList: [
{
key: "config.path",
},
],
responseMeta: {
isExecutionSuccess: false,
},
ENTITY_TYPE: "ACTION",
isLoading: false,
bindingPaths: {
"config.path": "TEMPLATE",
"config.body": "SMART_SUBSTITUTE",
"config.pluginSpecifiedTemplates[1].value": "SMART_SUBSTITUTE",
"config.pluginSpecifiedTemplates[2].value.limitBased.limit.value":
"SMART_SUBSTITUTE",
},
reactivePaths: {
data: "TEMPLATE",
isLoading: "TEMPLATE",
datasourceUrl: "TEMPLATE",
"config.path": "TEMPLATE",
"config.body": "SMART_SUBSTITUTE",
"config.pluginSpecifiedTemplates[1].value": "SMART_SUBSTITUTE",
},
dependencyMap: {
"config.body": ["config.pluginSpecifiedTemplates[0].value"],
},
logBlackList: {},
datasourceUrl: "",
__evaluation__: {
errors: {
config: [],
},
evaluatedValues: {
"config.path": "/users/undefined",
config: {
timeoutInMillisecond: 10000,
paginationType: "NONE",
path: "/users/test",
headers: [],
encodeParamsToggle: true,
queryParameters: [],
bodyFormData: [],
httpMethod: "GET",
selfReferencingDataPaths: [],
pluginSpecifiedTemplates: [
{
value: true,
},
],
formData: {
apiContentType: "none",
},
},
},
},
},
JSObject1: {
name: "JSObject1",
actionId: "637cda3b2f8e175c6f5269d5",
pluginType: "JS",
ENTITY_TYPE: "JSACTION",
body: "export default {\n\tstoreTest2: () => {\n\t\tlet values = [\n\t\t\t\t\tstoreValue('val1', 'number 1'),\n\t\t\t\t\tstoreValue('val2', 'number 2'),\n\t\t\t\t\tstoreValue('val3', 'number 3'),\n\t\t\t\t\tstoreValue('val4', 'number 4')\n\t\t\t\t];\n\t\treturn Promise.all(values)\n\t\t\t.then(() => {\n\t\t\tshowAlert(JSON.stringify(appsmith.store))\n\t\t})\n\t\t\t.catch((err) => {\n\t\t\treturn showAlert('Could not store values in store ' + err.toString());\n\t\t})\n\t},\n\tnewFunction: function() {\n\t\tJSObject1.storeTest()\n\t}\n}",
meta: {
newFunction: {
arguments: [],
isAsync: false,
confirmBeforeExecute: false,
},
storeTest2: {
arguments: [],
isAsync: true,
confirmBeforeExecute: false,
},
},
bindingPaths: {
body: "SMART_SUBSTITUTE",
newFunction: "SMART_SUBSTITUTE",
storeTest2: "SMART_SUBSTITUTE",
},
reactivePaths: {
body: "SMART_SUBSTITUTE",
newFunction: "SMART_SUBSTITUTE",
storeTest2: "SMART_SUBSTITUTE",
},
dynamicBindingPathList: [
{
key: "body",
},
{
key: "newFunction",
},
{
key: "storeTest2",
},
],
variables: [],
dependencyMap: {
body: ["newFunction", "storeTest2"],
},
__evaluation__: {
errors: {
storeTest2: [],
newFunction: [],
body: [],
},
},
},
} as unknown as DataTree;
beforeAll(() => {
const dependencyMap = new DependencyMap();
errorModifier.init(APP_MODE.EDIT);
errorModifier.updateAsyncFunctions(dataTree, {}, dependencyMap);
});
it("TypeError for defined Api in data field ", () => {
const error = new Error();
error.name = "TypeError";
error.message = "Api2.run is not a function";
const { errorMessage: result } = errorModifier.run(
error,
{ userScript: "", source: "" },
[ActionInDataFieldErrorModifier, TypeErrorModifier],
);
expect(result).toEqual({
name: "ValidationError",
message:
"Please remove any direct/indirect references to Api2.run() and try again. Data fields cannot execute framework actions.",
});
});
it("TypeError for undefined Api in data field ", () => {
const error = new Error();
error.name = "TypeError";
error.message = "Api1.run is not a function";
const { errorMessage: result } = errorModifier.run(
error,
{ userScript: "", source: "" },
[ActionInDataFieldErrorModifier, TypeErrorModifier],
);
expect(result).toEqual({
name: "TypeError",
message: "Api1.run is not a function",
});
});
it("ReferenceError for platform function in data field", () => {
const error = new Error();
error.name = "ReferenceError";
error.message = "storeValue is not defined";
const { errorMessage: result } = errorModifier.run(
error,
{ userScript: "", source: "" },
[ActionInDataFieldErrorModifier, TypeErrorModifier],
);
expect(result).toEqual({
name: "ValidationError",
message:
"Please remove any direct/indirect references to storeValue() and try again. Data fields cannot execute framework actions.",
});
});
it("ReferenceError for undefined function in data field", () => {
const error = new Error();
error.name = "ReferenceError";
error.message = "storeValue2 is not defined";
const { errorMessage: result } = errorModifier.run(
error,
{ userScript: "", source: "" },
[ActionInDataFieldErrorModifier, TypeErrorModifier],
);
expect(result).toEqual({
name: error.name,
message: error.message,
});
});
});
|
2,457 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/__tests__/evaluate.test.ts | import evaluate, { evaluateAsync } from "workers/Evaluation/evaluate";
import type { WidgetEntity } from "@appsmith/entities/DataTree/types";
import type { DataTree } from "entities/DataTree/dataTreeTypes";
import { ENTITY_TYPE_VALUE } from "entities/DataTree/dataTreeFactory";
import { RenderModes } from "constants/WidgetConstants";
import setupEvalEnv from "../handlers/setupEvalEnv";
import { resetJSLibraries } from "workers/common/JSLibrary/resetJSLibraries";
import { EVAL_WORKER_ACTIONS } from "@appsmith/workers/Evaluation/evalWorkerActions";
import { convertAllDataTypesToString } from "../errorModifier";
describe("evaluateSync", () => {
const widget: WidgetEntity = {
bottomRow: 0,
isLoading: false,
leftColumn: 0,
parentColumnSpace: 0,
parentRowSpace: 0,
renderMode: RenderModes.CANVAS,
rightColumn: 0,
topRow: 0,
type: "INPUT_WIDGET_V2",
version: 0,
widgetId: "",
widgetName: "",
text: "value",
ENTITY_TYPE: ENTITY_TYPE_VALUE.WIDGET,
bindingPaths: {},
reactivePaths: {},
triggerPaths: {},
validationPaths: {},
logBlackList: {},
overridingPropertyPaths: {},
privateWidgets: {},
propertyOverrideDependency: {},
meta: {},
};
const dataTree: DataTree = {
Input1: widget,
};
beforeAll(() => {
setupEvalEnv({
method: EVAL_WORKER_ACTIONS.SETUP,
data: {
cloudHosting: false,
},
});
resetJSLibraries();
});
it("unescapes string before evaluation", () => {
const js = '\\"Hello!\\"';
const response = evaluate(js, {}, false);
expect(response.result).toBe("Hello!");
});
it("evaluate string post unescape in v1", () => {
const js = '[1, 2, 3].join("\\\\n")';
const response = evaluate(js, {}, false);
expect(response.result).toBe("1\n2\n3");
});
it("evaluate string without unescape in v2", () => {
self.evaluationVersion = 2;
const js = '[1, 2, 3].join("\\n")';
const response = evaluate(js, {}, false);
expect(response.result).toBe("1\n2\n3");
});
it("throws error for undefined js", () => {
// @ts-expect-error: Types are not available
expect(() => evaluate(undefined, {})).toThrow(TypeError);
});
it("Returns for syntax errors", () => {
const response1 = evaluate("wrongJS", {}, false);
expect(response1).toStrictEqual({
result: undefined,
errors: [
{
errorMessage: {
name: "ReferenceError",
message: "wrongJS is not defined",
},
errorType: "PARSE",
kind: { category: undefined, rootcause: undefined },
raw: `
function $$closedFn () {
const $$result = wrongJS
return $$result
}
$$closedFn.call(THIS_CONTEXT)
`,
severity: "error",
originalBinding: "wrongJS",
},
],
});
const response2 = evaluate("{}.map()", {}, false);
expect(response2).toStrictEqual({
result: undefined,
errors: [
{
errorMessage: {
name: "TypeError",
message: "{}.map is not a function",
},
errorType: "PARSE",
kind: {
category: undefined,
rootcause: undefined,
},
raw: `
function $$closedFn () {
const $$result = {}.map()
return $$result
}
$$closedFn.call(THIS_CONTEXT)
`,
severity: "error",
originalBinding: "{}.map()",
},
],
});
});
it("evaluates value from data tree", () => {
const js = "Input1.text";
const response = evaluate(js, dataTree, false);
expect(response.result).toBe("value");
});
it("disallows unsafe function calls", () => {
const js = "setImmediate(() => {}, 100)";
const response = evaluate(js, dataTree, false);
expect(response).toStrictEqual({
result: undefined,
errors: [
{
errorMessage: {
name: "ReferenceError",
message: "setImmediate is not defined",
},
errorType: "PARSE",
kind: {
category: undefined,
rootcause: undefined,
},
raw: `
function $$closedFn () {
const $$result = setImmediate(() => {}, 100)
return $$result
}
$$closedFn.call(THIS_CONTEXT)
`,
severity: "error",
originalBinding: "setImmediate(() => {}, 100)",
},
],
});
});
it("has access to extra library functions", () => {
const js = "_.add(1,2)";
const response = evaluate(js, dataTree, false);
expect(response.result).toBe(3);
});
it("evaluates functions with callback data", () => {
const js = "(arg1, arg2) => arg1.value + arg2";
const callbackData = [{ value: "test" }, "1"];
const response = evaluate(js, dataTree, false, {}, callbackData);
expect(response.result).toBe("test1");
});
it("handles EXPRESSIONS with new lines", () => {
let js = "\n";
let response = evaluate(js, dataTree, false);
expect(response.errors.length).toBe(0);
js = "\n\n\n";
response = evaluate(js, dataTree, false);
expect(response.errors.length).toBe(0);
});
it("handles TRIGGERS with new lines", () => {
let js = "\n";
let response = evaluate(js, dataTree, false, undefined, undefined);
expect(response.errors.length).toBe(0);
js = "\n\n\n";
response = evaluate(js, dataTree, false, undefined, undefined);
expect(response.errors.length).toBe(0);
});
it("handles ANONYMOUS_FUNCTION with new lines", () => {
let js = "\n";
let response = evaluate(js, dataTree, false, undefined, undefined);
expect(response.errors.length).toBe(0);
js = "\n\n\n";
response = evaluate(js, dataTree, false, undefined, undefined);
expect(response.errors.length).toBe(0);
});
it("has access to this context", () => {
const js = "this.contextVariable";
const thisContext = { contextVariable: "test" };
const response = evaluate(js, dataTree, false, { thisContext });
expect(response.result).toBe("test");
// there should not be any error when accessing "this" variables
expect(response.errors).toHaveLength(0);
});
it("has access to additional global context", () => {
const js = "contextVariable";
const globalContext = { contextVariable: "test" };
const response = evaluate(js, dataTree, false, { globalContext });
expect(response.result).toBe("test");
expect(response.errors).toHaveLength(0);
});
});
describe("evaluateAsync", () => {
it("runs and completes", async () => {
const js = "(() => new Promise((resolve) => { resolve(123) }))()";
self.postMessage = jest.fn();
const response = await evaluateAsync(js, {}, {});
expect(response).toStrictEqual({
errors: [],
result: 123,
});
});
it("runs and returns errors", async () => {
jest.restoreAllMocks();
const js = "(() => new Promise((resolve) => { randomKeyword }))()";
self.postMessage = jest.fn();
const result = await evaluateAsync(js, {}, {});
expect(result).toStrictEqual({
errors: [
{
errorMessage: {
name: "ReferenceError",
message: "randomKeyword is not defined",
},
errorType: "PARSE",
originalBinding: expect.stringContaining("Promise"),
raw: expect.stringContaining("Promise"),
severity: "error",
},
],
result: undefined,
});
});
});
describe("convertAllDataTypesToString", () => {
const cases = [
{ index: 0, input: 0, expected: "0" },
{ index: 1, input: -1, expected: "-1" },
{ index: 2, input: 1, expected: "1" },
{ index: 3, input: 784630, expected: "784630" },
{ index: 4, input: true, expected: "true" },
{ index: 5, input: false, expected: "false" },
{ index: 6, input: null, expected: "null" },
{ index: 7, input: undefined, expected: undefined },
{ index: 8, input: "hello world!", expected: '"hello world!"' },
{ index: 9, input: `that's all folks!`, expected: '"that\'s all folks!"' },
{ index: 10, input: [], expected: "[]" },
{ index: 11, input: {}, expected: "{}" },
{ index: 12, input: [1, 2, 3, 4], expected: "[1,2,3,4]" },
{
index: 13,
input: [1, [2, 3], [4, [5, [6], 7]], 8],
expected: "[1,[2,3],[4,[5,[6],7]],8]",
},
{
index: 15,
input: { a: 1, b: 0, c: false, d: { e: { f: 8 } } },
expected: '{"a":1,"b":0,"c":false,"d":{"e":{"f":8}}}',
},
// Reason - need to test empty arrow function
// eslint-disable-next-line @typescript-eslint/no-empty-function
{ index: 16, input: () => {}, expected: "() => { }" },
];
test.each(cases.map((x) => [x.index, x.input, x.expected]))(
"test case %d",
(_, input, expected) => {
const result = convertAllDataTypesToString(input);
expect(result).toStrictEqual(expected);
},
);
});
|
2,458 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/__tests__/evaluation.test.ts | import type {
WidgetEntity,
WidgetEntityConfig,
ActionEntityConfig,
ActionEntity,
} from "@appsmith/entities/DataTree/types";
import type { UnEvalTree, ConfigTree } from "entities/DataTree/dataTreeTypes";
import {
ENTITY_TYPE_VALUE,
EvaluationSubstitutionType,
} from "entities/DataTree/dataTreeFactory";
import type { WidgetTypeConfigMap } from "WidgetProvider/factory";
import { RenderModes } from "constants/WidgetConstants";
import { PluginType } from "entities/Action";
import DataTreeEvaluator from "workers/common/DataTreeEvaluator";
import { ValidationTypes } from "constants/WidgetValidation";
import WidgetFactory from "WidgetProvider/factory";
import { generateDataTreeWidget } from "entities/DataTree/dataTreeWidget";
import { sortObjectWithArray } from "../../../utils/treeUtils";
import klona from "klona";
const klonaFullSpy = jest.fn();
jest.mock("klona/full", () => ({
klona: (arg: any) => {
klonaFullSpy(arg);
return klona.klona(arg);
},
}));
const WIDGET_CONFIG_MAP: WidgetTypeConfigMap = {
CONTAINER_WIDGET: {
defaultProperties: {},
derivedProperties: {},
metaProperties: {},
},
TEXT_WIDGET: {
defaultProperties: {},
derivedProperties: {
value: "{{ this.text }}",
},
metaProperties: {},
},
BUTTON_WIDGET: {
defaultProperties: {},
derivedProperties: {},
metaProperties: {},
},
INPUT_WIDGET_V2: {
defaultProperties: {
text: "defaultText",
},
derivedProperties: {
isValid:
'{{\n function(){\n let parsedRegex = null;\n if (this.regex) {\n /*\n * break up the regexp pattern into 4 parts: given regex, regex prefix , regex pattern, regex flags\n * Example /test/i will be split into ["/test/gi", "/", "test", "gi"]\n */\n const regexParts = this.regex.match(/(\\/?)(.+)\\1([a-z]*)/i);\n if (!regexParts) {\n parsedRegex = new RegExp(this.regex);\n } else {\n /*\n * if we don\'t have a regex flags (gmisuy), convert provided string into regexp directly\n /*\n if (regexParts[3] && !/^(?!.*?(.).*?\\1)[gmisuy]+$/.test(regexParts[3])) {\n parsedRegex = RegExp(this.regex);\n }\n /*\n * if we have a regex flags, use it to form regexp\n */\n parsedRegex = new RegExp(regexParts[2], regexParts[3]);\n }\n }\n if (this.inputType === "EMAIL") {\n const emailRegex = new RegExp(/^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/);\n return emailRegex.test(this.text);\n }\n else if (this.inputType === "NUMBER") {\n return !isNaN(this.text)\n }\n else if (this.isRequired) {\n if(this.text && this.text.length) {\n if (parsedRegex) {\n return parsedRegex.test(this.text)\n } else {\n return true;\n }\n } else {\n return false;\n }\n } if (parsedRegex) {\n return parsedRegex.test(this.text)\n } else {\n return true;\n }\n }()\n }}',
value: "{{this.text}}",
},
metaProperties: {
isFocused: false,
isDirty: false,
},
},
CHECKBOX_WIDGET: {
defaultProperties: {
isChecked: "defaultCheckedState",
},
derivedProperties: {
value: "{{this.isChecked}}",
},
metaProperties: {},
},
SELECT_WIDGET: {
defaultProperties: {
selectedOption: "defaultOptionValue",
filterText: "",
},
derivedProperties: {
selectedOptionLabel: `{{_.isPlainObject(this.selectedOption) ? this.selectedOption?.label : this.selectedOption}}`,
selectedOptionValue: `{{_.isPlainObject(this.selectedOption) ? this.selectedOption?.value : this.selectedOption}}`,
isValid: `{{this.isRequired ? !!this.selectedOptionValue || this.selectedOptionValue === 0 : true}}`,
},
metaProperties: {
selectedOption: undefined,
filterText: "",
},
},
RADIO_GROUP_WIDGET: {
defaultProperties: {
selectedOptionValue: "defaultOptionValue",
},
derivedProperties: {
selectedOption:
"{{_.find(this.options, { value: this.selectedOptionValue })}}",
isValid: "{{ this.isRequired ? !!this.selectedOptionValue : true }}",
value: "{{this.selectedOptionValue}}",
},
metaProperties: {},
},
IMAGE_WIDGET: {
defaultProperties: {},
derivedProperties: {},
metaProperties: {},
},
TABLE_WIDGET: {
defaultProperties: {
searchText: "defaultSearchText",
selectedRowIndex: "defaultSelectedRow",
selectedRowIndices: "defaultSelectedRow",
},
derivedProperties: {
selectedRow: `{{ _.get(this.filteredTableData, this.selectedRowIndex, _.mapValues(this.filteredTableData[0], () => undefined)) }}`,
selectedRows: `{{ this.filteredTableData.filter((item, i) => selectedRowIndices.includes(i) }); }}`,
},
metaProperties: {
pageNo: 1,
selectedRows: [],
},
},
TABLE_WIDGET_V2: {
defaultProperties: {
searchText: "defaultSearchText",
selectedRowIndex: "defaultSelectedRow",
selectedRowIndices: "defaultSelectedRow",
},
derivedProperties: {
selectedRow: `{{ _.get(this.filteredTableData, this.selectedRowIndex, _.mapValues(this.filteredTableData[0], () => undefined)) }}`,
selectedRows: `{{ this.filteredTableData.filter((item, i) => selectedRowIndices.includes(i) }); }}`,
},
metaProperties: {
pageNo: 1,
selectedRow: {},
selectedRows: [],
},
},
VIDEO_WIDGET: {
defaultProperties: {},
derivedProperties: {},
metaProperties: {
playState: "NOT_STARTED",
},
},
FILE_PICKER_WIDGET: {
defaultProperties: {},
derivedProperties: {
isValid: "{{ this.isRequired ? this.files.length > 0 : true }}",
value: "{{this.files}}",
},
metaProperties: {
files: [],
uploadedFileData: {},
},
},
DATE_PICKER_WIDGET: {
defaultProperties: {
selectedDate: "defaultDate",
},
derivedProperties: {
isValid: "{{ this.isRequired ? !!this.selectedDate : true }}",
value: "{{ this.selectedDate }}",
},
metaProperties: {},
},
DATE_PICKER_WIDGET2: {
defaultProperties: {
selectedDate: "defaultDate",
},
derivedProperties: {
isValid: "{{ this.isRequired ? !!this.selectedDate : true }}",
value: "{{ this.selectedDate }}",
},
metaProperties: {},
},
TABS_WIDGET: {
defaultProperties: {},
derivedProperties: {
selectedTab:
"{{_.find(this.tabs, { widgetId: this.selectedTabWidgetId }).label}}",
},
metaProperties: {},
},
MODAL_WIDGET: {
defaultProperties: {},
derivedProperties: {},
metaProperties: {},
},
RICH_TEXT_EDITOR_WIDGET: {
defaultProperties: {
text: "defaultText",
},
derivedProperties: {
value: "{{this.text}}",
},
metaProperties: {},
},
CHART_WIDGET: {
defaultProperties: {},
derivedProperties: {},
metaProperties: {},
},
FORM_WIDGET: {
defaultProperties: {},
derivedProperties: {},
metaProperties: {},
},
FORM_BUTTON_WIDGET: {
defaultProperties: {},
derivedProperties: {},
metaProperties: {},
},
MAP_WIDGET: {
defaultProperties: {
markers: "defaultMarkers",
center: "mapCenter",
},
derivedProperties: {},
metaProperties: {},
},
CANVAS_WIDGET: {
defaultProperties: {},
derivedProperties: {},
metaProperties: {},
},
ICON_WIDGET: {
defaultProperties: {},
derivedProperties: {},
metaProperties: {},
},
SKELETON_WIDGET: {
defaultProperties: {},
derivedProperties: {},
metaProperties: {},
},
};
const BASE_WIDGET = {
widgetId: "randomID",
widgetName: "randomWidgetName",
bottomRow: 0,
isLoading: false,
leftColumn: 0,
parentColumnSpace: 0,
parentRowSpace: 0,
renderMode: RenderModes.CANVAS,
rightColumn: 0,
topRow: 0,
type: "SKELETON_WIDGET",
parentId: "0",
version: 1,
ENTITY_TYPE: ENTITY_TYPE_VALUE.WIDGET,
meta: {},
} as unknown as WidgetEntity;
const BASE_WIDGET_CONFIG = {
logBlackList: {},
widgetId: "randomID",
type: "SKELETON_WIDGET",
ENTITY_TYPE: ENTITY_TYPE_VALUE.WIDGET,
} as unknown as WidgetEntityConfig;
export const BASE_ACTION: ActionEntity = {
clear: {},
actionId: "randomId",
datasourceUrl: "",
config: {
timeoutInMillisecond: 10,
},
isLoading: false,
run: {},
data: {},
responseMeta: { isExecutionSuccess: false },
ENTITY_TYPE: ENTITY_TYPE_VALUE.ACTION,
};
export const BASE_ACTION_CONFIG: ActionEntityConfig = {
actionId: "randomId",
logBlackList: {},
pluginId: "",
name: "randomActionName",
dynamicBindingPathList: [],
pluginType: PluginType.API,
ENTITY_TYPE: ENTITY_TYPE_VALUE.ACTION,
bindingPaths: {},
reactivePaths: {
isLoading: EvaluationSubstitutionType.TEMPLATE,
data: EvaluationSubstitutionType.TEMPLATE,
},
dependencyMap: {},
};
const metaMock = jest.spyOn(WidgetFactory, "getWidgetMetaPropertiesMap");
const mockDefault = jest.spyOn(WidgetFactory, "getWidgetDefaultPropertiesMap");
const mockDerived = jest.spyOn(WidgetFactory, "getWidgetDerivedPropertiesMap");
const initialdependencies = {
Dropdown1: [
"Dropdown1.defaultOptionValue",
"Dropdown1.filterText",
"Dropdown1.isValid",
"Dropdown1.meta",
"Dropdown1.selectedOption",
"Dropdown1.selectedOptionLabel",
"Dropdown1.selectedOptionValue",
],
"Dropdown1.isValid": ["Dropdown1.selectedOptionValue"],
"Dropdown1.filterText": ["Dropdown1.meta.filterText"],
"Dropdown1.meta": [
"Dropdown1.meta.filterText",
"Dropdown1.meta.selectedOption",
],
"Dropdown1.selectedOption": [
"Dropdown1.defaultOptionValue",
"Dropdown1.meta.selectedOption",
],
"Dropdown1.selectedOptionLabel": ["Dropdown1.selectedOption"],
"Dropdown1.selectedOptionValue": ["Dropdown1.selectedOption"],
Table1: [
"Table1.defaultSearchText",
"Table1.defaultSelectedRow",
"Table1.searchText",
"Table1.selectedRow",
"Table1.selectedRowIndex",
"Table1.selectedRowIndices",
"Table1.selectedRows",
"Table1.tableData",
],
"Table1.searchText": ["Table1.defaultSearchText"],
"Table1.selectedRow": ["Table1.selectedRowIndex"],
"Table1.selectedRowIndex": ["Table1.defaultSelectedRow"],
"Table1.selectedRowIndices": ["Table1.defaultSelectedRow"],
"Table1.selectedRows": [],
"Table1.tableData": ["Text1.text"],
Text1: ["Text1.text", "Text1.value"],
"Text1.value": ["Text1.text"],
Text2: ["Text2.text", "Text2.value"],
"Text2.text": ["Text1.text"],
"Text2.value": ["Text2.text"],
Text3: ["Text3.text", "Text3.value"],
"Text3.value": ["Text3.text"],
"Text3.text": ["Text1.text"],
Text4: ["Text4.text", "Text4.value"],
"Text4.text": ["Table1.selectedRow"],
"Text4.value": ["Text4.text"],
};
describe("DataTreeEvaluator", () => {
afterEach(() => {
jest.clearAllMocks();
});
metaMock.mockImplementation((type) => {
return WIDGET_CONFIG_MAP[type].metaProperties;
});
mockDefault.mockImplementation((type) => {
return WIDGET_CONFIG_MAP[type].defaultProperties;
});
mockDerived.mockImplementation((type) => {
return WIDGET_CONFIG_MAP[type].derivedProperties;
});
//Input1
const { configEntity, unEvalEntity } = generateDataTreeWidget(
{
...BASE_WIDGET,
text: undefined,
defaultText: "Default value",
widgetName: "Input1",
type: "INPUT_WIDGET_V2",
reactivePaths: {
defaultText: EvaluationSubstitutionType.TEMPLATE,
isValid: EvaluationSubstitutionType.TEMPLATE,
value: EvaluationSubstitutionType.TEMPLATE,
text: EvaluationSubstitutionType.TEMPLATE,
},
},
{},
new Set(),
);
const input1unEvalEntity = unEvalEntity;
const input1ConfigEntity = configEntity;
//Text1
const unEvalTree: UnEvalTree = {
Text1: generateDataTreeWidget(
{
...BASE_WIDGET_CONFIG,
...BASE_WIDGET,
widgetName: "Text1",
text: "Label",
type: "TEXT_WIDGET",
},
{},
new Set(),
).unEvalEntity,
Text2: generateDataTreeWidget(
{
...BASE_WIDGET_CONFIG,
...BASE_WIDGET,
widgetName: "Text2",
text: "{{Text1.text}}",
dynamicBindingPathList: [{ key: "text" }],
type: "TEXT_WIDGET",
},
{},
new Set(),
).unEvalEntity,
Text3: generateDataTreeWidget(
{
...BASE_WIDGET_CONFIG,
...BASE_WIDGET,
widgetName: "Text3",
text: "{{Text1.text}}",
dynamicBindingPathList: [{ key: "text" }],
type: "TEXT_WIDGET",
},
{},
new Set(),
).unEvalEntity,
Dropdown1: generateDataTreeWidget(
{
...BASE_WIDGET_CONFIG,
...BASE_WIDGET,
widgetName: "Dropdown1",
options: [
{
label: "test",
value: "valueTest",
},
{
label: "test2",
value: "valueTest2",
},
],
type: "SELECT_WIDGET",
},
{},
new Set(),
).unEvalEntity,
Table1: generateDataTreeWidget(
{
...BASE_WIDGET_CONFIG,
...BASE_WIDGET,
widgetName: "Table1",
tableData:
"{{Api1.data.map(datum => ({ ...datum, raw: Text1.text }) )}}",
dynamicBindingPathList: [{ key: "tableData" }],
type: "TABLE_WIDGET",
searchText: undefined,
selectedRowIndex: undefined,
selectedRowIndices: undefined,
},
{},
new Set(),
).unEvalEntity,
Text4: generateDataTreeWidget(
{
...BASE_WIDGET_CONFIG,
...BASE_WIDGET,
text: "{{Table1.selectedRow.test}}",
widgetName: "Text4",
dynamicBindingPathList: [{ key: "text" }],
type: "TEXT_WIDGET",
reactivePaths: {
text: EvaluationSubstitutionType.TEMPLATE,
},
validationPaths: {
text: { type: ValidationTypes.TEXT },
},
},
{},
new Set(),
).unEvalEntity,
};
const configTree: ConfigTree = {
Text1: generateDataTreeWidget(
{
...BASE_WIDGET_CONFIG,
...BASE_WIDGET,
widgetName: "Text1",
text: "Label",
type: "TEXT_WIDGET",
},
{},
new Set(),
).configEntity,
Text2: generateDataTreeWidget(
{
...BASE_WIDGET_CONFIG,
...BASE_WIDGET,
widgetName: "Text2",
text: "{{Text1.text}}",
dynamicBindingPathList: [{ key: "text" }],
type: "TEXT_WIDGET",
},
{},
new Set(),
).configEntity,
Text3: generateDataTreeWidget(
{
...BASE_WIDGET_CONFIG,
...BASE_WIDGET,
widgetName: "Text3",
text: "{{Text1.text}}",
dynamicBindingPathList: [{ key: "text" }],
type: "TEXT_WIDGET",
},
{},
new Set(),
).configEntity,
Dropdown1: generateDataTreeWidget(
{
...BASE_WIDGET_CONFIG,
...BASE_WIDGET,
widgetName: "Dropdown1",
options: [
{
label: "test",
value: "valueTest",
},
{
label: "test2",
value: "valueTest2",
},
],
type: "SELECT_WIDGET",
},
{},
new Set(),
).configEntity,
Table1: generateDataTreeWidget(
{
...BASE_WIDGET_CONFIG,
...BASE_WIDGET,
widgetName: "Table1",
tableData:
"{{Api1.data.map(datum => ({ ...datum, raw: Text1.text }) )}}",
dynamicBindingPathList: [{ key: "tableData" }],
type: "TABLE_WIDGET",
},
{},
new Set(),
).configEntity,
Text4: generateDataTreeWidget(
{
...BASE_WIDGET_CONFIG,
...BASE_WIDGET,
widgetName: "Text4",
text: "{{Table1.selectedRow.test}}",
dynamicBindingPathList: [{ key: "text" }],
type: "TEXT_WIDGET",
reactivePaths: {
text: EvaluationSubstitutionType.TEMPLATE,
},
validationPaths: {
text: { type: ValidationTypes.TEXT },
},
dynamicTriggerPathList: [],
},
{},
new Set(),
).configEntity,
};
const evaluator = new DataTreeEvaluator(WIDGET_CONFIG_MAP);
it("Checks the number of clone operations in first tree flow", () => {
evaluator.setupFirstTree(unEvalTree, configTree);
evaluator.evalAndValidateFirstTree();
// Hard check to not regress on the number of clone operations. Try to improve this number.
expect(klonaFullSpy).toBeCalledTimes(41);
});
it("Evaluates a binding in first run", () => {
const evaluation = evaluator.evalTree;
const dependencies = evaluator.dependencies;
expect(evaluation).toHaveProperty("Text1.text", "Label");
expect(evaluation).toHaveProperty("Text2.text", "Label");
expect(evaluation).toHaveProperty("Text3.text", "Label");
expect(sortObjectWithArray(dependencies)).toStrictEqual(
initialdependencies,
);
});
it("Evaluates a value change in update run", () => {
const updatedUnEvalTree = {
...unEvalTree,
Text1: {
...unEvalTree.Text1,
text: "Hey there",
},
};
const updatedConfigTree = {
...configTree,
Text: {
...configTree.Text1,
},
};
const { evalOrder, unEvalUpdates } = evaluator.setupUpdateTree(
updatedUnEvalTree,
updatedConfigTree,
);
evaluator.evalAndValidateSubTree(
evalOrder,
updatedConfigTree,
unEvalUpdates,
);
const dataTree = evaluator.evalTree;
expect(dataTree).toHaveProperty("Text1.text", "Hey there");
expect(dataTree).toHaveProperty("Text2.text", "Hey there");
expect(dataTree).toHaveProperty("Text3.text", "Hey there");
});
it("Evaluates a dependency change in update run", () => {
const updatedUnEvalTree = {
...unEvalTree,
Text3: {
...unEvalTree.Text3,
text: "Label 3",
},
};
const updatedConfigTree = {
...configTree,
Text3: {
...configTree.Text3,
dynamicBindingPathList: [],
},
};
const expectedDependencies = {
...initialdependencies,
// Binding has been removed
["Text3.text"]: [],
};
const { evalOrder, unEvalUpdates } = evaluator.setupUpdateTree(
updatedUnEvalTree,
updatedConfigTree,
);
evaluator.evalAndValidateSubTree(
evalOrder,
updatedConfigTree,
unEvalUpdates,
);
const dataTree = evaluator.evalTree;
const updatedDependencies = evaluator.dependencies;
expect(dataTree).toHaveProperty("Text1.text", "Label");
expect(dataTree).toHaveProperty("Text2.text", "Label");
expect(dataTree).toHaveProperty("Text3.text", "Label 3");
expect(sortObjectWithArray(updatedDependencies)).toStrictEqual(
expectedDependencies,
);
});
it("Overrides with default value", () => {
const updatedUnEvalTree = {
...unEvalTree,
Input1: input1unEvalEntity,
};
const updatedConfigTree = {
...configTree,
Input1: input1ConfigEntity,
};
const expectedDependencies = {
...initialdependencies,
Input1: [
"Input1.defaultText",
"Input1.isValid",
"Input1.text",
"Input1.value",
],
"Input1.isValid": ["Input1.text"],
"Input1.text": ["Input1.defaultText"],
"Input1.value": ["Input1.text"],
};
const { evalOrder, unEvalUpdates } = evaluator.setupUpdateTree(
updatedUnEvalTree,
updatedConfigTree,
);
evaluator.evalAndValidateSubTree(
evalOrder,
updatedConfigTree,
unEvalUpdates,
);
const dataTree = evaluator.evalTree;
expect(dataTree).toHaveProperty("Input1.text", "Default value");
expect(sortObjectWithArray(evaluator.dependencies)).toStrictEqual(
expectedDependencies,
);
});
it("Evaluates for value changes in nested diff paths", () => {
const bindingPaths = {
options: EvaluationSubstitutionType.TEMPLATE,
defaultOptionValue: EvaluationSubstitutionType.TEMPLATE,
isRequired: EvaluationSubstitutionType.TEMPLATE,
isVisible: EvaluationSubstitutionType.TEMPLATE,
isDisabled: EvaluationSubstitutionType.TEMPLATE,
};
const updatedUnEvalTree = {
...unEvalTree,
Dropdown2: {
...BASE_WIDGET,
widgetName: "Dropdown2",
options: [
{
label: "newValue",
value: "valueTest",
},
{
label: "test2",
value: "valueTest2",
},
],
type: "SELECT_WIDGET",
},
} as unknown as UnEvalTree;
const updatedConfigTree = {
...configTree,
Dropdown2: {
...BASE_WIDGET_CONFIG,
type: "SELECT_WIDGET",
bindingPaths,
reactivePaths: {
...bindingPaths,
isValid: EvaluationSubstitutionType.TEMPLATE,
selectedOption: EvaluationSubstitutionType.TEMPLATE,
selectedOptionValue: EvaluationSubstitutionType.TEMPLATE,
selectedOptionLabel: EvaluationSubstitutionType.TEMPLATE,
},
propertyOverrideDependency: {},
validationPaths: {},
},
} as unknown as ConfigTree;
const expectedDependencies = { ...initialdependencies };
const { evalOrder, unEvalUpdates } = evaluator.setupUpdateTree(
updatedUnEvalTree,
updatedConfigTree,
);
evaluator.evalAndValidateSubTree(
evalOrder,
updatedConfigTree,
unEvalUpdates,
);
const dataTree = evaluator.evalTree;
const updatedDependencies = evaluator.dependencies;
expect(dataTree).toHaveProperty("Dropdown2.options.0.label", "newValue");
expect(sortObjectWithArray(updatedDependencies)).toStrictEqual(
expectedDependencies,
);
});
it("Adds an entity with a complicated binding", () => {
const updatedUnEvalTree = {
...unEvalTree,
Api1: {
...BASE_ACTION,
data: [
{
test: "Hey",
},
{
test: "Ho",
},
],
},
} as unknown as UnEvalTree;
const updatedConfigTree = {
...configTree,
Api1: {
...BASE_ACTION_CONFIG,
name: "Api1",
},
} as unknown as ConfigTree;
const { evalOrder, unEvalUpdates } = evaluator.setupUpdateTree(
updatedUnEvalTree,
updatedConfigTree,
);
evaluator.evalAndValidateSubTree(
evalOrder,
updatedConfigTree,
unEvalUpdates,
);
const dataTree = evaluator.evalTree;
const updatedDependencies = evaluator.dependencies;
expect(dataTree).toHaveProperty("Table1.tableData", [
{
test: "Hey",
raw: "Label",
},
{
test: "Ho",
raw: "Label",
},
]);
expect(sortObjectWithArray(updatedDependencies)).toStrictEqual({
Api1: ["Api1.data"],
...initialdependencies,
"Table1.tableData": ["Api1.data", "Text1.text"],
"Text3.text": ["Text1.text"],
});
});
it("Selects a row", () => {
const updatedUnEvalTree = {
...unEvalTree,
Table1: {
...unEvalTree.Table1,
selectedRowIndex: 0,
selectedRow: {
test: "Hey",
raw: "Label",
},
},
Api1: {
...BASE_ACTION,
data: [
{
test: "Hey",
},
{
test: "Ho",
},
],
},
} as unknown as UnEvalTree;
const updatedConfigTree = {
...configTree,
Table1: {
...configTree.Table1,
},
Api1: {
...BASE_ACTION_CONFIG,
name: "Api1",
},
} as unknown as ConfigTree;
const { evalOrder, unEvalUpdates } = evaluator.setupUpdateTree(
updatedUnEvalTree,
updatedConfigTree,
);
evaluator.evalAndValidateSubTree(
evalOrder,
updatedConfigTree,
unEvalUpdates,
);
const dataTree = evaluator.evalTree;
const updatedDependencies = evaluator.dependencies;
expect(dataTree).toHaveProperty("Table1.tableData", [
{
test: "Hey",
raw: "Label",
},
{
test: "Ho",
raw: "Label",
},
]);
expect(dataTree).toHaveProperty("Text4.text", "Hey");
expect(sortObjectWithArray(updatedDependencies)).toStrictEqual({
Api1: ["Api1.data"],
...initialdependencies,
"Table1.selectedRow": [],
"Table1.tableData": ["Api1.data", "Text1.text"],
"Text3.text": ["Text1.text"],
});
});
it("Honors predefined action dependencyMap", () => {
const updatedTree1 = {
...unEvalTree,
Text1: {
...unEvalTree.Text1,
text: "Test",
},
Api2: {
...BASE_ACTION,
config: {
...BASE_ACTION.config,
body: "",
pluginSpecifiedTemplates: [
{
value: false,
},
],
},
},
};
const updatedConfigTree1 = {
...configTree,
Text1: {
...configTree.Text1,
},
Api2: {
...BASE_ACTION_CONFIG,
name: "Api2",
dependencyMap: {
"config.body": ["config.pluginSpecifiedTemplates[0].value"],
},
reactivePaths: {
...BASE_ACTION_CONFIG.reactivePaths,
"config.body": EvaluationSubstitutionType.TEMPLATE,
},
},
} as unknown as ConfigTree;
const { evalOrder, unEvalUpdates } = evaluator.setupUpdateTree(
updatedTree1,
updatedConfigTree1,
);
evaluator.evalAndValidateSubTree(
evalOrder,
updatedConfigTree1,
unEvalUpdates,
);
expect(evaluator.dependencies["Api2.config.body"]).toStrictEqual([
"Api2.config.pluginSpecifiedTemplates[0].value",
]);
const updatedTree2 = {
...updatedTree1,
Api2: {
...updatedTree1.Api2,
config: {
...updatedTree1.Api2.config,
body: "{ 'name': {{ Text1.text }} }",
},
},
};
const updatedConfigTree2 = {
...updatedConfigTree1,
Api2: {
...updatedConfigTree1.Api2,
dynamicBindingPathList: [
{
key: "config.body",
},
],
},
};
const { evalOrder: newEvalOrder, unEvalUpdates: unEvalUpdates2 } =
evaluator.setupUpdateTree(updatedTree2, updatedConfigTree2);
evaluator.evalAndValidateSubTree(
newEvalOrder,
updatedConfigTree2,
unEvalUpdates2,
);
const dataTree = evaluator.evalTree;
expect(evaluator.dependencies["Api2.config.body"]).toStrictEqual([
"Api2.config.pluginSpecifiedTemplates[0].value",
"Text1.text",
]);
// @ts-expect-error: Types are not available
expect(dataTree.Api2.config.body).toBe("{ 'name': Test }");
const updatedTree3 = {
...updatedTree2,
Api2: {
...updatedTree2.Api2,
config: {
...updatedTree2.Api2.config,
pluginSpecifiedTemplates: [
{
value: true,
},
],
},
},
};
const updatedConfigTree3 = {
...updatedConfigTree2,
Api2: {
...updatedConfigTree2.Api2,
reactivePaths: {
...updatedConfigTree2.Api2.reactivePaths,
"config.body": EvaluationSubstitutionType.SMART_SUBSTITUTE,
},
},
};
const { evalOrder: newEvalOrder2, unEvalUpdates: unEvalUpdates3 } =
evaluator.setupUpdateTree(updatedTree3, updatedConfigTree3);
evaluator.evalAndValidateSubTree(
newEvalOrder2,
updatedConfigTree3,
unEvalUpdates3,
);
const dataTree3 = evaluator.evalTree;
expect(evaluator.dependencies["Api2.config.body"]).toStrictEqual([
"Api2.config.pluginSpecifiedTemplates[0].value",
"Text1.text",
]);
// @ts-expect-error: Types are not available
expect(dataTree3.Api2.config.body).toBe("{ 'name': \"Test\" }");
});
it("Prevents data mutation in eval cycle", () => {
const { configEntity, unEvalEntity } = generateDataTreeWidget(
{
...BASE_WIDGET_CONFIG,
...BASE_WIDGET,
widgetName: "TextX",
text: "{{Text1.text = 123}}",
dynamicBindingPathList: [{ key: "text" }],
type: "TEXT_WIDGET",
},
{},
new Set(),
);
const updatedUnEvalTree = {
...unEvalTree,
TextX: unEvalEntity,
};
const updatedConfigTree = {
...configTree,
TextX: configEntity,
};
const { evalOrder, unEvalUpdates } = evaluator.setupUpdateTree(
updatedUnEvalTree,
updatedConfigTree,
);
expect(evalOrder).toContain("TextX.text");
evaluator.evalAndValidateSubTree(
evalOrder,
updatedConfigTree,
unEvalUpdates,
);
const dataTree = evaluator.evalTree;
expect(dataTree).toHaveProperty("TextX.text", 123);
expect(dataTree).toHaveProperty("Text1.text", "Label");
});
it("Checks the number of clone operations performed in update tree flow", () => {
const { configEntity, unEvalEntity } = generateDataTreeWidget(
{
...BASE_WIDGET_CONFIG,
...BASE_WIDGET,
widgetName: "TextY",
text: "{{Text1.text = 123}}",
dynamicBindingPathList: [{ key: "text" }],
type: "TEXT_WIDGET",
},
{},
new Set(),
);
const updatedUnEvalTree = {
...unEvalTree,
TextY: unEvalEntity,
};
const updatedConfigTree = {
...configTree,
TextY: configEntity,
};
const { evalOrder, unEvalUpdates } = evaluator.setupUpdateTree(
updatedUnEvalTree,
updatedConfigTree,
);
expect(evalOrder).toContain("TextY.text");
expect(evalOrder.length).toBe(2);
evaluator.evalAndValidateSubTree(
evalOrder,
updatedConfigTree,
unEvalUpdates,
);
// Hard check to not regress on the number of clone operations. Try to improve this number.
expect(klonaFullSpy).toBeCalledTimes(7);
});
});
|
2,459 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/__tests__/evaluationSubstitution.test.ts | import { substituteDynamicBindingWithValues } from "workers/Evaluation/evaluationSubstitution";
import { EvaluationSubstitutionType } from "entities/DataTree/dataTreeFactory";
describe("substituteDynamicBindingWithValues", () => {
describe("template substitution", () => {
it("substitutes strings values", () => {
const binding = "Hello {{name}}";
const subBindings = ["Hello ", "{{name}}"];
const subValues = ["Hello ", "Tester"];
const expected = "Hello Tester";
const result = substituteDynamicBindingWithValues(
binding,
subBindings,
subValues,
EvaluationSubstitutionType.TEMPLATE,
);
expect(result).toBe(expected);
});
it("substitute number values", () => {
const binding = "My age is {{age}}";
const subBindings = ["My age is ", "{{age}}"];
const subValues = ["My age is ", 16];
const expected = "My age is 16";
const result = substituteDynamicBindingWithValues(
binding,
subBindings,
subValues,
EvaluationSubstitutionType.TEMPLATE,
);
expect(result).toBe(expected);
});
it("substitute objects/ arrays values", () => {
const binding = "Response was {{response}}";
const subBindings = ["Response was ", "{{response}}"];
const subValues = ["Response was ", { message: "Unauthorised user" }];
const expected = 'Response was {\\"message\\":\\"Unauthorised user\\"}';
const result = substituteDynamicBindingWithValues(
binding,
subBindings,
subValues,
EvaluationSubstitutionType.TEMPLATE,
);
expect(result).toBe(expected);
});
it("substitute multiple values values", () => {
const binding =
"My name is {{name}}. My age is {{age}}. Response: {{response}}";
const subBindings = [
"My name is ",
"{{name}}",
". My age is ",
"{{age}}",
". Response: ",
"{{response}}",
];
const subValues = [
"My name is ",
"Tester",
". My age is ",
16,
". Response: ",
{ message: "Unauthorised user" },
];
const expected =
'My name is Tester. My age is 16. Response: {\\"message\\":\\"Unauthorised user\\"}';
const result = substituteDynamicBindingWithValues(
binding,
subBindings,
subValues,
EvaluationSubstitutionType.TEMPLATE,
);
expect(result).toBe(expected);
});
});
describe("parameter substitution", () => {
it("replaces bindings with $variables", () => {
const binding = "SELECT * from {{tableName}} LIMIT {{limit}}";
const subBindings = [
"SELECT * from ",
"{{tableName}}",
" LIMIT ",
"{{limit}}",
];
const subValues = ["SELECT * from ", "users", " LIMIT ", 10];
const expected = {
value: "SELECT * from $1 LIMIT $2",
parameters: {
$1: "users",
$2: 10,
},
};
const result = substituteDynamicBindingWithValues(
binding,
subBindings,
subValues,
EvaluationSubstitutionType.PARAMETER,
);
expect(result).toHaveProperty("value");
// @ts-expect-error: Types are not available
expect(result.value).toBe(expected.value);
// @ts-expect-error: Types are not available
expect(result.parameters).toStrictEqual(expected.parameters);
});
it("removed quotes around bindings", () => {
const binding =
'SELECT * from users WHERE lastname = "{{lastname}}" LIMIT {{limit}}';
const subBindings = [
'SELECT * from users WHERE lastname = "',
"{{lastname}}",
'" LIMIT ',
"{{limit}}",
];
const subValues = [
'SELECT * from users WHERE lastname = "',
"Smith",
'" LIMIT ',
10,
];
const expected = {
value: "SELECT * from users WHERE lastname = $1 LIMIT $2",
parameters: {
$1: "Smith",
$2: 10,
},
};
const result = substituteDynamicBindingWithValues(
binding,
subBindings,
subValues,
EvaluationSubstitutionType.PARAMETER,
);
expect(result).toHaveProperty("value");
// @ts-expect-error: Types are not available
expect(result.value).toBe(expected.value);
// @ts-expect-error: Types are not available
expect(result.parameters).toStrictEqual(expected.parameters);
});
it("stringifies objects and arrays", () => {
const binding = "SELECT * from {{testObject}} WHERE {{testArray}}";
const subBindings = [
"SELECT * from ",
"{{testObject}}",
" WHERE ",
"{{testArray}}",
];
const subValues = [
"SELECT * from ",
{ name: "tester" },
" WHERE ",
[42, "meaning", false],
];
const expected = {
value: "SELECT * from $1 WHERE $2",
parameters: {
$1: `{\n \"name\": \"tester\"\n}`,
$2: `[\n 42,\n \"meaning\",\n false\n]`,
},
};
const result = substituteDynamicBindingWithValues(
binding,
subBindings,
subValues,
EvaluationSubstitutionType.PARAMETER,
);
expect(result).toHaveProperty("value");
// @ts-expect-error: Types are not available
expect(result.value).toBe(expected.value);
// @ts-expect-error: Types are not available
expect(result.parameters).toStrictEqual(expected.parameters);
});
});
describe("smart substitution", () => {
it("substitutes strings, numbers, boolean, undefined, null values correctly", () => {
const binding = `{
"name": {{name}},
"age": {{age}},
"isHuman": {{isHuman}},
"wrongBinding": {{wrongBinding}},
"emptyBinding": {{emptyBinding}},
}`;
const subBindings = [
'{\n "name": ',
"{{name}}",
',\n "age": ',
"{{age}}",
',\n "isHuman": ',
"{{isHuman}}",
',\n "wrongBinding": ',
"{{wrongBinding}}",
',\n "emptyBinding": ',
"{{emptyBinding}}",
",\n }",
];
const subValues = [
'{\n "name": ',
"Tester",
',\n "age": ',
42,
',\n "isHuman": ',
false,
',\n "wrongBinding": ',
undefined,
',\n "emptyBinding": ',
null,
",\n }",
];
const expected = `{
"name": "Tester",
"age": 42,
"isHuman": false,
"wrongBinding": undefined,
"emptyBinding": null,
}`;
const result = substituteDynamicBindingWithValues(
binding,
subBindings,
subValues,
EvaluationSubstitutionType.SMART_SUBSTITUTE,
);
expect(result).toBe(expected);
});
it("substitute objects/ arrays values", () => {
const binding = `{\n "data": {{formData}}\n}`;
const subBindings = ["{\n data: ", "{{formData}}", "\n}"];
const subValues = [
'{\n "data": ',
{
name: "Tester",
age: 42,
isHuman: false,
wrongBinding: undefined,
emptyBinding: null,
},
"\n}",
];
const expected =
'{\n "data": {\n "name": "Tester",\n "age": 42,\n "isHuman": false,\n "emptyBinding": null\n}\n}';
const result = substituteDynamicBindingWithValues(
binding,
subBindings,
subValues,
EvaluationSubstitutionType.SMART_SUBSTITUTE,
);
expect(result).toBe(expected);
});
it("substitute correctly when quotes are surrounding the binding", () => {
const binding = `{
"name": "{{name}}",
"age": "{{age}}",
isHuman: {{isHuman}},
"wrongBinding": {{wrongBinding}},
"emptyBinding": "{{emptyBinding}}",
}`;
const subBindings = [
'{\n "name": "',
"{{name}}",
'",\n "age": "',
"{{age}}",
'",\n isHuman: ',
"{{isHuman}}",
',\n "wrongBinding": ',
"{{wrongBinding}}",
',\n "emptyBinding": "',
"{{emptyBinding}}",
'",\n }',
];
const subValues = [
'{\n "name": "',
"Tester",
'",\n "age": "',
42,
'",\n isHuman: ',
false,
',\n "wrongBinding": ',
undefined,
',\n "emptyBinding": "',
null,
'",\n }',
];
const expected = `{
"name": "Tester",
"age": 42,
isHuman: false,
"wrongBinding": undefined,
"emptyBinding": null,
}`;
const result = substituteDynamicBindingWithValues(
binding,
subBindings,
subValues,
EvaluationSubstitutionType.SMART_SUBSTITUTE,
);
expect(result).toBe(expected);
});
it("escapes strings before substitution", () => {
const binding = `{\n "paragraph": {{paragraph}},\n}`;
const subBindings = ['{\n "paragraph": ', "{{paragraph}}", ",\n}"];
const subValues = [
'{\n "paragraph": ',
`This is a \f string \b with \n many different " characters that are not \n all. these \r\t`,
",\n}",
];
const expected = `{\n "paragraph": "This is a \\f string \\b with \\n many different \\" characters that are not \\n all. these \\r\\t",\n}`;
const result = substituteDynamicBindingWithValues(
binding,
subBindings,
subValues,
EvaluationSubstitutionType.SMART_SUBSTITUTE,
);
expect(result).toBe(expected);
});
it("throws error when only binding is provided in parameter substitution", () => {
const binding = `{{ appsmith }}`;
const subBindings = ["{{appsmith}}"];
const subValues = [{ test: "object" }];
expect(() =>
substituteDynamicBindingWithValues(
binding,
subBindings,
subValues,
EvaluationSubstitutionType.PARAMETER,
),
).toThrowError();
});
});
});
|
2,460 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/__tests__/formEval.test.ts | import {
extractFetchDynamicValueFormConfigs,
extractQueueOfValuesToBeFetched,
} from "sagas/helper";
describe("Fetch dynamic values", () => {
const testInput = {
identifier1: {
visible: true,
enabled: false,
fetchDynamicValues: {
allowedToFetch: true,
isLoading: true,
hasStarted: true,
hasFetchFailed: true,
data: [],
config: {
params: {
key1: "value1",
},
},
evaluatedConfig: {
params: {
key1: "value1",
},
},
},
},
identifier2: {
enabled: true,
},
identifier3: {
fetchDynamicValues: {
allowedToFetch: false,
isLoading: true,
hasStarted: true,
hasFetchFailed: true,
data: [],
config: {
params: {
key1: "value1",
},
},
evaluatedConfig: {
params: {
key1: "value1",
},
},
},
},
};
it("extract dynamic configs from form evaluation output", () => {
const testOutput = {
identifier1: {
visible: true,
enabled: false,
fetchDynamicValues: {
allowedToFetch: true,
isLoading: true,
hasStarted: true,
hasFetchFailed: true,
data: [],
config: {
params: {
key1: "value1",
},
},
evaluatedConfig: {
params: {
key1: "value1",
},
},
},
},
identifier3: {
fetchDynamicValues: {
allowedToFetch: false,
isLoading: true,
hasStarted: true,
hasFetchFailed: true,
data: [],
config: {
params: {
key1: "value1",
},
},
evaluatedConfig: {
params: {
key1: "value1",
},
},
},
},
};
expect(extractFetchDynamicValueFormConfigs(testInput)).toEqual(testOutput);
});
it("extract config of values that are allowed to fetch from url", () => {
const testOutput = {
identifier1: {
visible: true,
enabled: false,
fetchDynamicValues: {
allowedToFetch: true,
isLoading: true,
hasStarted: true,
hasFetchFailed: true,
data: [],
config: {
params: {
key1: "value1",
},
},
evaluatedConfig: {
params: {
key1: "value1",
},
},
},
},
};
expect(extractQueueOfValuesToBeFetched(testInput)).toEqual(testOutput);
});
});
|
2,461 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts | /* eslint-disable @typescript-eslint/no-empty-function */
import { applyChange } from "deep-diff";
import produce from "immer";
import { range } from "lodash";
import moment from "moment";
import { parseUpdatesAndDeleteUndefinedUpdates } from "sagas/EvaluationSaga.utils";
import { EvalErrorTypes } from "utils/DynamicBindingUtils";
import {
generateOptimisedUpdates,
generateSerialisedUpdates,
} from "../helpers";
export const smallDataSet = [
{
address: "Paseo de Soledad Tur 245 Puerta 4 \nValencia, 50285",
company: "Gonzalez Inc",
},
{
address: "Ronda Rosalina Menéndez 72\nCuenca, 38057",
company: "Gallego, Pedrosa and Conesa",
},
{
address: "833 جزيني Gateway\nمشفقland, AL 63852",
company: "اهرام-الحويطات",
},
];
//size of about 300 elements
const largeDataSet = range(100).flatMap(() => smallDataSet) as any;
const oldState = {
Table1: {
ENTITY_TYPE: "WIDGET",
primaryColumns: {
customColumn2: {
isDisabled: false,
},
},
tableData: [],
filteredTableData: smallDataSet,
selectedRows: [],
pageSize: 0,
triggerRowSelection: false,
type: "TABLE_WIDGET_V2",
__evaluation__: {
errors: {
transientTableData: [],
tableData: [],
processedTableData: [],
},
evaluatedValues: {
filteredTableData: smallDataSet,
transientTableData: {},
tableData: [],
processedTableData: [],
"primaryColumns.customColumn2.isDisabled": false,
},
},
},
Select1: {
value: "",
ENTITY_TYPE: "WIDGET",
options: [
{
label: "[email protected]",
value: 1,
},
{
label: "[email protected]",
value: 2,
},
],
type: "SELECT_WIDGET",
__evaluation__: {
errors: {
options: [],
},
evaluatedValues: {
"meta.value": "",
value: "",
},
},
},
};
describe("generateOptimisedUpdates", () => {
describe("regular diff", () => {
test("should generate regular diff updates when a simple property changes in the widget property segment", () => {
const newState = produce(oldState, (draft) => {
draft.Table1.pageSize = 17;
});
const updates = generateOptimisedUpdates(oldState, newState);
expect(updates).toEqual([
{ kind: "E", path: ["Table1", "pageSize"], lhs: 0, rhs: 17 },
]);
});
test("should generate regular diff updates when a simple property changes in the __evaluation__ segment ", () => {
const validationError = "Some validation error";
const newState = produce(oldState, (draft) => {
draft.Table1.__evaluation__.evaluatedValues.tableData =
validationError as any;
});
const updates = generateOptimisedUpdates(oldState, newState);
expect(updates).toEqual([
{
kind: "E",
path: ["Table1", "__evaluation__", "evaluatedValues", "tableData"],
lhs: [],
rhs: validationError,
},
]);
});
describe("ignore invalid moment updates", () => {
test("should generate a null update when it sees an invalid moment object", () => {
const newState = produce(oldState, (draft) => {
draft.Table1.pageSize = moment("invalid value") as any;
});
const updates = generateOptimisedUpdates(oldState, newState);
expect(updates).toEqual([
{ kind: "E", path: ["Table1", "pageSize"], lhs: 0, rhs: null },
]);
});
test("should generate a regular update when it sees a valid moment object", () => {
const validMoment = moment();
const newState = produce(oldState, (draft) => {
draft.Table1.pageSize = validMoment as any;
});
const updates = generateOptimisedUpdates(oldState, newState);
expect(updates).toEqual([
{ kind: "E", path: ["Table1", "pageSize"], lhs: 0, rhs: validMoment },
]);
});
test("should generate no diff update when prev state is already null", () => {
const prevState = produce(oldState, (draft) => {
draft.Table1.pageSize = null as any;
draft.Table1.triggerRowSelection = undefined as any;
});
const newState = produce(oldState, (draft) => {
draft.Table1.pageSize = moment("invalid value") as any;
draft.Table1.triggerRowSelection = moment("invalid value") as any;
});
const updates = generateOptimisedUpdates(prevState, newState);
expect(updates).toEqual([
{
kind: "E",
path: ["Table1", "triggerRowSelection"],
lhs: undefined,
rhs: null,
},
]);
});
});
});
describe("diffs with identicalEvalPathsPatches", () => {
test("should not generate any updates when both the states are the same", () => {
const updates = generateOptimisedUpdates(oldState, oldState);
expect(updates).toEqual([]);
const identicalEvalPathsPatches = {
"Table1.__evaluation__.evaluatedValues.['tableData']":
"Table1.tableData",
};
const updatesWithCompressionMap = generateOptimisedUpdates(
oldState,
oldState,
identicalEvalPathsPatches,
);
expect(updatesWithCompressionMap).toEqual([]);
});
test("should generate the correct table data updates and reference state patches", () => {
const identicalEvalPathsPatches = {
"Table1.__evaluation__.evaluatedValues.['tableData']":
"Table1.tableData",
};
const newState = produce(oldState, (draft) => {
draft.Table1.tableData = largeDataSet;
});
const updates = generateOptimisedUpdates(
oldState,
newState,
identicalEvalPathsPatches,
);
expect(updates).toEqual([
{ kind: "N", path: ["Table1", "tableData"], rhs: largeDataSet },
{
kind: "referenceState",
path: ["Table1", "__evaluation__", "evaluatedValues", "tableData"],
referencePath: "Table1.tableData",
},
]);
});
test("should not generate granular updates and generate a patch which replaces the complete collection when any change is made to the large collection ", () => {
const largeDataSetWithSomeSimpleChange = produce(
largeDataSet,
(draft: any) => {
//making a change to the first row of the collection
draft[0].address = "some new address";
//making a change to the second row of the collection
draft[1].address = "some other new address";
},
) as any;
const identicalEvalPathsPatches = {
"Table1.__evaluation__.evaluatedValues.['tableData']":
"Table1.tableData",
};
const evalVal = "some eval value" as any;
const newState = produce(oldState, (draft) => {
//this value eval value should be ignores since we have provided identicalEvalPathsPatches which takes precedence
draft.Table1.__evaluation__.evaluatedValues.tableData = evalVal as any;
draft.Table1.tableData = largeDataSetWithSomeSimpleChange;
});
const updates = generateOptimisedUpdates(
oldState,
newState,
identicalEvalPathsPatches,
);
//should not see evalVal since identical eval path patches takes precedence
expect(JSON.stringify(updates)).not.toContain(evalVal);
expect(updates).toEqual([
{
kind: "N",
path: ["Table1", "tableData"],
//we should not see granular updates but complete replacement
rhs: largeDataSetWithSomeSimpleChange,
},
{
//compression patch
kind: "referenceState",
path: ["Table1", "__evaluation__", "evaluatedValues", "tableData"],
referencePath: "Table1.tableData",
},
]);
});
test("should not generate compression patches when there are no identical eval paths provided ", () => {
const tableDataEvaluationValue = "someValidation error";
const largeDataSetWithSomeSimpleChange = produce(
largeDataSet,
(draft: any) => {
//making a change to the first row of the collection
draft[0].address = "some new address";
//making a change to the second row of the collection
draft[1].address = "some other new address";
},
) as any;
// empty indentical eval paths
const identicalEvalPathsPatches = {};
const newState = produce(oldState, (draft) => {
draft.Table1.tableData = largeDataSetWithSomeSimpleChange;
draft.Table1.__evaluation__.evaluatedValues.tableData =
tableDataEvaluationValue as any;
});
const updates = generateOptimisedUpdates(
oldState,
newState,
identicalEvalPathsPatches,
);
expect(updates).toEqual([
{
//considered as regular diff since there are no identical eval paths provided
kind: "E",
path: ["Table1", "__evaluation__", "evaluatedValues", "tableData"],
lhs: [],
rhs: tableDataEvaluationValue,
},
{
kind: "N",
path: ["Table1", "tableData"],
//we should not see granular updates but complete replacement
rhs: largeDataSetWithSomeSimpleChange,
},
]);
});
test("should not generate any update when the new state has the same value as the old state", () => {
const oldStateSetWithSomeData = produce(oldState, (draft) => {
draft.Table1.tableData = largeDataSet;
draft.Table1.__evaluation__.evaluatedValues.tableData = largeDataSet;
});
const identicalEvalPathsPatches = {
"Table1.__evaluation__.evaluatedValues.['tableData']":
"Table1.tableData",
};
const newStateSetWithTheSameData = produce(oldState, (draft) => {
//deliberating making a new instance of largeDataSet
draft.Table1.tableData = [...largeDataSet] as any;
});
//since the old state has the same value as the new value..we wont generate a patch unnecessarily...
const updates = generateOptimisedUpdates(
oldStateSetWithSomeData,
newStateSetWithTheSameData,
identicalEvalPathsPatches,
);
expect(updates).toEqual([]);
});
});
});
//we are testing the flow of serialised updates generated from the worker thread and subsequently applied to the main thread state
describe("generateSerialisedUpdates and parseUpdatesAndDeleteUndefinedUpdates", () => {
it("should ignore undefined updates", () => {
const oldStateWithUndefinedValues = produce(oldState, (draft: any) => {
draft.Table1.pageSize = undefined;
});
const { serialisedUpdates } = generateSerialisedUpdates(
oldStateWithUndefinedValues,
//new state has the same undefined value
oldStateWithUndefinedValues,
{},
);
//no change hence empty array
expect(serialisedUpdates).toEqual("[]");
});
it("should generate a delete patch when a property is transformed to undefined", () => {
const oldStateWithUndefinedValues = produce(oldState, (draft: any) => {
draft.Table1.pageSize = undefined;
});
const { serialisedUpdates } = generateSerialisedUpdates(
oldState,
oldStateWithUndefinedValues,
{},
);
const parsedUpdates =
parseUpdatesAndDeleteUndefinedUpdates(serialisedUpdates);
expect(parsedUpdates).toEqual([
{
kind: "D",
path: ["Table1", "pageSize"],
},
]);
});
it("should generate an error when there is a serialisation error", () => {
const oldStateWithUndefinedValues = produce(oldState, (draft: any) => {
//generate a cyclical object
draft.Table1.filteredTableData = draft.Table1;
});
const { error, serialisedUpdates } = generateSerialisedUpdates(
oldState,
oldStateWithUndefinedValues,
{},
);
expect(error?.type).toEqual(EvalErrorTypes.SERIALIZATION_ERROR);
//when a serialisation error occurs we should not return an error
expect(serialisedUpdates).toEqual("[]");
});
//when functions are serialised they become undefined and these updates should be deleted from the state
describe("clean out all functions in the generated state", () => {
it("should clean out new function properties added to the generated state", () => {
const newStateWithSomeFnProperty = produce(oldState, (draft: any) => {
draft.Table1.someFn = () => {};
draft.Table1.__evaluation__.evaluatedValues.someEvalFn = () => {};
});
const { serialisedUpdates } = generateSerialisedUpdates(
oldState,
newStateWithSomeFnProperty,
{},
);
const parsedUpdates =
parseUpdatesAndDeleteUndefinedUpdates(serialisedUpdates);
//should ignore all function updates
expect(parsedUpdates).toEqual([]);
const parseAndApplyUpdatesToOldState = produce(oldState, (draft) => {
parsedUpdates.forEach((v: any) => {
applyChange(draft, undefined, v);
});
});
//no change in state
expect(parseAndApplyUpdatesToOldState).toEqual(oldState);
});
it("should delete properties which get updated to a function", () => {
const newStateWithSomeFnProperty = produce(oldState, (draft: any) => {
draft.Table1.pageSize = () => {};
draft.Table1.__evaluation__.evaluatedValues.transientTableData =
() => {};
});
const { serialisedUpdates } = generateSerialisedUpdates(
oldState,
newStateWithSomeFnProperty,
{},
);
const parsedUpdates =
parseUpdatesAndDeleteUndefinedUpdates(serialisedUpdates);
expect(parsedUpdates).toEqual([
{
kind: "D",
path: ["Table1", "pageSize"],
},
{
kind: "D",
path: [
"Table1",
"__evaluation__",
"evaluatedValues",
"transientTableData",
],
},
]);
const parseAndApplyUpdatesToOldState = produce(oldState, (draft) => {
parsedUpdates.forEach((v: any) => {
applyChange(draft, undefined, v);
});
});
const expectedState = produce(oldState, (draft: any) => {
delete draft.Table1.pageSize;
delete draft.Table1.__evaluation__.evaluatedValues.transientTableData;
});
expect(parseAndApplyUpdatesToOldState).toEqual(expectedState);
});
it("should delete function properties which get updated to undefined", () => {
const oldStateWithSomeFnProperty = produce(oldState, (draft: any) => {
// eslint-disable-next-line @typescript-eslint/no-empty-function
draft.Table1.pageSize = () => {};
draft.Table1.__evaluation__.evaluatedValues.transientTableData =
// eslint-disable-next-line @typescript-eslint/no-empty-function
() => {};
});
const newStateWithFnsTransformedToUndefined = produce(
oldState,
(draft: any) => {
draft.Table1.pageSize = undefined;
draft.Table1.__evaluation__.evaluatedValues.transientTableData =
undefined;
},
);
const { serialisedUpdates } = generateSerialisedUpdates(
oldStateWithSomeFnProperty,
newStateWithFnsTransformedToUndefined,
{},
);
const parsedUpdates =
parseUpdatesAndDeleteUndefinedUpdates(serialisedUpdates);
expect(parsedUpdates).toEqual([
{
kind: "D",
path: ["Table1", "pageSize"],
},
{
kind: "D",
path: [
"Table1",
"__evaluation__",
"evaluatedValues",
"transientTableData",
],
},
]);
const parseAndApplyUpdatesToOldState = produce(oldState, (draft) => {
parsedUpdates.forEach((v: any) => {
applyChange(draft, undefined, v);
});
});
const expectedState = produce(oldState, (draft: any) => {
delete draft.Table1.pageSize;
delete draft.Table1.__evaluation__.evaluatedValues.transientTableData;
});
expect(parseAndApplyUpdatesToOldState).toEqual(expectedState);
});
});
it("should serialise bigInteger values", () => {
const someBigInt = BigInt(121221);
const newStateWithBigInt = produce(oldState, (draft: any) => {
draft.Table1.pageSize = someBigInt;
});
const { serialisedUpdates } = generateSerialisedUpdates(
oldState,
newStateWithBigInt,
{},
);
const parsedUpdates =
parseUpdatesAndDeleteUndefinedUpdates(serialisedUpdates);
//should generate serialised bigInt update
expect(parsedUpdates).toEqual([
{
kind: "E",
path: ["Table1", "pageSize"],
rhs: "121221",
},
]);
const parseAndApplyUpdatesToOldState = produce(oldState, (draft) => {
parsedUpdates.forEach((v: any) => {
applyChange(draft, undefined, v);
});
});
const expectedState = produce(oldState, (draft: any) => {
draft.Table1.pageSize = "121221";
});
expect(parseAndApplyUpdatesToOldState).toEqual(expectedState);
});
});
|
2,462 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/__tests__/helpers.test.ts | import { findDuplicateIndex } from "../helpers";
describe("Worker Helper functions test", () => {
it("Correctly finds the duplicate index in an array of strings", () => {
const input = ["a", "b", "c", "d", "e", "a", "b"];
const expected = 5;
const result = findDuplicateIndex(input);
expect(result).toStrictEqual(expected);
});
it("Correctly finds the duplicate index in an array of objects and strings", () => {
const input = [
"a",
"b",
{ a: 1, b: 2 },
{ a: 2, b: 3 },
"e",
{ a: 1, b: 2 },
"b",
];
const expected = 5;
const result = findDuplicateIndex(input);
expect(result).toStrictEqual(expected);
});
/* TODO(abhinav): These kinds of issues creep up when dealing with JSON.stringify to make
things simple. So, the ideal solution here is to prevent the
usage of this function for array of objects
*/
it("Correctly ignores the duplicate index in an array of objects and strings, when properties are not ordered", () => {
const input = [
"a",
"b",
{ a: 1, b: 2 },
{ a: 2, b: 3 },
"e",
{ b: 2, a: 1 },
"b",
];
const expected = 6;
const result = findDuplicateIndex(input);
expect(result).toStrictEqual(expected);
});
it("Correctly returns -1 if no duplicates are found", () => {
const input = ["a", "b", "c", "d", "e", "f", "g"];
const expected = -1;
const result = findDuplicateIndex(input);
expect(result).toStrictEqual(expected);
});
});
|
2,464 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/__tests__/setters.test.ts | import { generateDataTreeWidget } from "entities/DataTree/dataTreeWidget";
import setters from "../setters";
import TableWidget from "widgets/TableWidgetV2/widget";
import { RenderModes } from "constants/WidgetConstants";
import type { ConfigTree, DataTree } from "entities/DataTree/dataTreeTypes";
import { createEvaluationContext } from "../evaluate";
import { registerWidgets } from "WidgetProvider/factory/registrationHelper";
registerWidgets([TableWidget]);
const evalTree: DataTree = {};
const configTree: ConfigTree = {};
const tableWidgetDataTree = generateDataTreeWidget(
{
type: TableWidget.type,
widgetId: "random",
widgetName: "Table1",
children: [],
bottomRow: 0,
isLoading: false,
parentColumnSpace: 0,
parentRowSpace: 0,
version: 1,
leftColumn: 0,
renderMode: RenderModes.CANVAS,
rightColumn: 0,
topRow: 0,
primaryColumns: [],
tableData: [],
},
{},
new Set(),
);
evalTree["Table1"] = tableWidgetDataTree.unEvalEntity;
configTree["Table1"] = tableWidgetDataTree.configEntity;
const evalContext = createEvaluationContext({
dataTree: evalTree,
isTriggerBased: true,
context: {},
configTree,
});
jest.mock("workers/Evaluation/handlers/evalTree", () => ({
get dataTreeEvaluator() {
return {
evalTree: evalContext,
getEvalTree: () => evalContext,
getConfigTree: () => configTree,
};
},
}));
jest.mock("../evalTreeWithChanges", () => ({
evalTreeWithChanges: () => {
//
},
}));
describe("Setter class test", () => {
it("Setters init method ", () => {
setters.init(configTree, evalTree);
expect(setters.getMap()).toEqual({
Table1: {
setData: true,
setSelectedRowIndex: true,
setVisibility: true,
},
});
});
it("getEntitySettersFromConfig method ", async () => {
const methodMap = setters.getEntitySettersFromConfig(
tableWidgetDataTree.configEntity,
"Table1",
evalTree["Table1"],
);
const globalContext = self as any;
Object.assign(globalContext, evalContext);
expect(Object.keys(methodMap)).toEqual([
"setVisibility",
"setSelectedRowIndex",
"setData",
]);
globalContext.Table1.setVisibility(true);
expect(globalContext.Table1.isVisible).toEqual(true);
});
});
|
2,465 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/__tests__/timeout.test.ts | import { PluginType } from "entities/Action";
import type { ActionEntity } from "@appsmith/entities/DataTree/types";
import type { DataTree } from "entities/DataTree/dataTreeTypes";
import { ENTITY_TYPE_VALUE } from "entities/DataTree/dataTreeFactory";
import { createEvaluationContext } from "../evaluate";
import { addPlatformFunctionsToEvalContext } from "@appsmith/workers/Evaluation/Actions";
import { overrideWebAPIs } from "../fns/overrides";
describe("Expects appsmith setTimeout to pass the following criteria", () => {
overrideWebAPIs(self);
jest.useFakeTimers();
jest.spyOn(self, "setTimeout");
self.postMessage = jest.fn();
it("returns a number a timerId", () => {
const timerId = setTimeout(jest.fn(), 1000);
expect(timerId).toBeDefined();
expect(typeof timerId).toBe("number");
});
it("Passes arguments into callback", () => {
const cb = jest.fn();
const args = [1, 2, "3", [4]];
setTimeout(cb, 1000, ...args);
expect(cb.mock.calls.length).toBe(0);
jest.runAllTimers();
expect(cb).toHaveBeenCalledWith(...args);
});
it("Has weird behavior with 'this' keyword", () => {
const cb = jest.fn();
const error = jest.fn();
const obj = {
var1: "myVar1",
getVar() {
try {
cb(this.var1);
} catch (e) {
error(e);
}
},
};
setTimeout(obj.getVar, 1000);
expect(cb.mock.calls.length).toBe(0);
jest.runAllTimers();
expect(error).toBeCalled();
});
it("Has weird behavior with 'this' keyword", () => {
const cb = jest.fn();
const error = jest.fn();
const obj = {
var1: "myVar1",
getVar() {
try {
cb(this.var1);
} catch (e) {
error(e);
}
},
};
setTimeout(obj.getVar.bind(obj), 1000);
expect(cb.mock.calls.length).toBe(0);
jest.runAllTimers();
expect(cb).toBeCalledWith(obj.var1);
});
it("'this' behavior should be fixed by binding this", () => {
const cb = jest.fn();
const error = jest.fn();
const obj = {
var1: "myVar1",
getVar() {
try {
cb(this.var1);
} catch (e) {
error(e);
}
},
};
setTimeout(obj.getVar.bind(obj), 1000);
expect(cb.mock.calls.length).toBe(0);
jest.runAllTimers();
expect(cb).toBeCalledWith(obj.var1);
});
it("Checks the behavior of clearTimeout", () => {
const cb = jest.fn();
const timerId = setTimeout(cb, 1000);
expect(cb.mock.calls.length).toBe(0);
clearTimeout(timerId);
jest.runAllTimers();
expect(cb.mock.calls.length).toBe(0);
});
it("Access to appsmith functions inside setTimeout", async () => {
const dataTree: DataTree = {
action1: {
actionId: "123",
pluginId: "",
data: {},
config: {},
datasourceUrl: "",
pluginType: PluginType.API,
dynamicBindingPathList: [],
name: "action1",
bindingPaths: {},
reactivePaths: {},
isLoading: false,
run: {},
clear: {},
responseMeta: { isExecutionSuccess: false },
ENTITY_TYPE: ENTITY_TYPE_VALUE.ACTION,
dependencyMap: {},
logBlackList: {},
} as ActionEntity,
};
self["$isDataField"] = false;
const evalContext = createEvaluationContext({
dataTree,
isTriggerBased: true,
context: {},
});
addPlatformFunctionsToEvalContext(evalContext);
setTimeout(() => evalContext.action1.run(), 1000);
jest.runAllTimers();
expect(self.postMessage).toBeCalled();
});
});
|
2,466 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/__tests__/validations.test.ts | import {
validate,
WIDGET_TYPE_VALIDATION_ERROR,
} from "workers/Evaluation/validations";
import type { WidgetProps } from "widgets/BaseWidget";
import { RenderModes } from "constants/WidgetConstants";
import { ValidationTypes } from "constants/WidgetValidation";
import moment from "moment";
import { AutocompleteDataType } from "utils/autocomplete/AutocompleteDataType";
const DUMMY_WIDGET: WidgetProps = {
bottomRow: 0,
isLoading: false,
leftColumn: 0,
parentColumnSpace: 0,
parentRowSpace: 0,
renderMode: RenderModes.CANVAS,
rightColumn: 0,
topRow: 0,
type: "SKELETON_WIDGET",
version: 2,
widgetId: "",
widgetName: "",
};
describe("Validate Validators", () => {
it("correctly validates text", () => {
const validation = {
type: ValidationTypes.TEXT,
params: {
required: true,
default: "abc",
allowedValues: ["abc", "123", "mno", "test"],
},
};
const inputs = ["abc", "xyz", undefined, null, {}, [], 123, ""];
const expected = [
{
isValid: true,
parsed: "abc",
},
{
isValid: false,
parsed: "abc",
messages: [
{
name: "ValidationError",
message: "Disallowed value: xyz",
},
],
},
{
isValid: false,
parsed: "abc",
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR} string ( abc | 123 | mno | test )`,
},
],
},
{
isValid: false,
parsed: "abc",
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR} string ( abc | 123 | mno | test )`,
},
],
},
{
isValid: false,
parsed: "{}",
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR} string ( abc | 123 | mno | test )`,
},
],
},
{
isValid: false,
parsed: "[]",
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR} string ( abc | 123 | mno | test )`,
},
],
},
{
isValid: true,
parsed: "123",
},
{
isValid: false,
parsed: "abc",
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR} string ( abc | 123 | mno | test )`,
},
],
},
];
inputs.forEach((input, index) => {
const result = validate(validation, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates text with regex match", () => {
const validation = {
type: ValidationTypes.TEXT,
params: {
default: "https://www.appsmith.com",
regex:
/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&\/=]*)/,
},
};
const inputs = [
"",
undefined,
"https://www.appsmith.com/",
"www.google.com",
"app.appsmith.com",
];
const expected = [
{
isValid: true,
parsed: "https://www.appsmith.com",
},
{
isValid: true,
parsed: "https://www.appsmith.com",
},
{
isValid: true,
parsed: "https://www.appsmith.com/",
},
{
isValid: true,
parsed: "www.google.com",
},
{
isValid: true,
parsed: "app.appsmith.com",
},
];
inputs.forEach((input, index) => {
const result = validate(validation, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly uses the expected message", () => {
const validation = {
type: ValidationTypes.TEXT,
params: {
default: "https://www.appsmith.com",
regex:
/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&\/=]*)/,
expected: {
type: "URL",
example: "https://www.appsmith.com",
autocompleteDataType: AutocompleteDataType.STRING,
},
},
};
const inputs = [
"",
undefined,
"https://www.appsmith.com/",
"www.google.com",
"app.appsmith.com",
];
const expected = [
{
isValid: true,
parsed: "https://www.appsmith.com",
},
{
isValid: true,
parsed: "https://www.appsmith.com",
},
{
isValid: true,
parsed: "https://www.appsmith.com/",
},
{
isValid: true,
parsed: "www.google.com",
},
{
isValid: true,
parsed: "app.appsmith.com",
},
];
inputs.forEach((input, index) => {
const result = validate(validation, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates text when required is set to false", () => {
const validation = {
type: ValidationTypes.TEXT,
params: {
default: "abc",
allowedValues: ["abc", "123", "mno", "test"],
},
};
const inputs = [""];
const expected = [
{
isValid: true,
parsed: "abc",
},
];
inputs.forEach((input, index) => {
const result = validate(validation, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates strict text", () => {
const validation = {
type: ValidationTypes.TEXT,
params: {
required: true,
default: "abc",
allowedValues: ["abc", "123", "mno", "test"],
strict: true,
},
};
const inputs = ["abc", "xyz", 123];
const expected = [
{
isValid: true,
parsed: "abc",
},
{
isValid: false,
parsed: "abc",
messages: [
{
name: "ValidationError",
message: "Disallowed value: xyz",
},
],
},
{
isValid: false,
parsed: "abc",
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR} string ( abc | 123 | mno | test )`,
},
],
},
];
inputs.forEach((input, index) => {
const result = validate(validation, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates image url", () => {
const config = {
type: ValidationTypes.IMAGE_URL,
params: {
default:
"https://cdn.dribbble.com/users/1787323/screenshots/4563995/dribbbe_hammer-01.png",
required: true,
},
};
const inputs = [
"https://cdn.dribbble.com/users/1787323/screenshots/4563995/dribbbe_hammer-01.png",
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAAKAAoDASIAAhEBAxEB/8QAFwAAAwEAAAAAAAAAAAAAAAAAAQUGCP/EACAQAAICAgICAwAAAAAAAAAAAAECAwUEEQAhBkESFSL/xAAVAQEBAAAAAAAAAAAAAAAAAAAFBv/EABwRAQAABwEAAAAAAAAAAAAAAAEAAgMEBREhQf/aAAwDAQACEQMRAD8A0nU5V9i+Q5/3NREaEpElc+NjGaVm1+iwQEhfe2A0ffIC5trSK3zYo8+dETIdVUMdABjocF9Z2UV1lRRWGXHGsxVVWZgAO+gN8WMSzFmPyYnZJ7JPAchcNQA5qKvEWktFmme7DyP/2Q==",
"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAAKAAoDASIAAhEBAxEB/8QAFwAAAwEAAAAAAAAAAAAAAAAAAQUGCP/EACAQAAICAgICAwAAAAAAAAAAAAECAwUEEQAhBkESFSL/xAAVAQEBAAAAAAAAAAAAAAAAAAAFBv/EABwRAQAABwEAAAAAAAAAAAAAAAEAAgMEBREhQf/aAAwDAQACEQMRAD8A0nU5V9i+Q5/3NREaEpElc+NjGaVm1+iwQEhfe2A0ffIC5trSK3zYo8+dETIdVUMdABjocF9Z2UV1lRRWGXHGsxVVWZgAO+gN8WMSzFmPyYnZJ7JPAchcNQA5qKvEWktFmme7DyP/2Q==",
undefined,
"blob:https://localhost/a18fd4c9-e485-44ef-9fcf-6345785e88ec",
];
const expected = [
{
isValid: true,
parsed:
"https://cdn.dribbble.com/users/1787323/screenshots/4563995/dribbbe_hammer-01.png",
},
{
isValid: true,
parsed:
"data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAAKAAoDASIAAhEBAxEB/8QAFwAAAwEAAAAAAAAAAAAAAAAAAQUGCP/EACAQAAICAgICAwAAAAAAAAAAAAECAwUEEQAhBkESFSL/xAAVAQEBAAAAAAAAAAAAAAAAAAAFBv/EABwRAQAABwEAAAAAAAAAAAAAAAEAAgMEBREhQf/aAAwDAQACEQMRAD8A0nU5V9i+Q5/3NREaEpElc+NjGaVm1+iwQEhfe2A0ffIC5trSK3zYo8+dETIdVUMdABjocF9Z2UV1lRRWGXHGsxVVWZgAO+gN8WMSzFmPyYnZJ7JPAchcNQA5qKvEWktFmme7DyP/2Q==",
},
{
isValid: true,
parsed:
"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAAKAAoDASIAAhEBAxEB/8QAFwAAAwEAAAAAAAAAAAAAAAAAAQUGCP/EACAQAAICAgICAwAAAAAAAAAAAAECAwUEEQAhBkESFSL/xAAVAQEBAAAAAAAAAAAAAAAAAAAFBv/EABwRAQAABwEAAAAAAAAAAAAAAAEAAgMEBREhQf/aAAwDAQACEQMRAD8A0nU5V9i+Q5/3NREaEpElc+NjGaVm1+iwQEhfe2A0ffIC5trSK3zYo8+dETIdVUMdABjocF9Z2UV1lRRWGXHGsxVVWZgAO+gN8WMSzFmPyYnZJ7JPAchcNQA5qKvEWktFmme7DyP/2Q==",
},
{
isValid: false,
parsed:
"https://cdn.dribbble.com/users/1787323/screenshots/4563995/dribbbe_hammer-01.png",
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR}: base64 encoded image | data uri | image url`,
},
],
},
{
isValid: true,
parsed: "blob:https://localhost/a18fd4c9-e485-44ef-9fcf-6345785e88ec",
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("Validates number with passThroughOnZero", () => {
const config: any = {
type: ValidationTypes.NUMBER,
params: {
min: 1,
max: 4,
},
};
expect(validate(config, -1, DUMMY_WIDGET).parsed).toStrictEqual(-1);
expect(validate(config, 0, DUMMY_WIDGET).parsed).toStrictEqual(0);
config.params.passThroughOnZero = false;
expect(validate(config, 0, DUMMY_WIDGET).parsed).toStrictEqual(1);
});
it("correctly validates number when required is true", () => {
const config = {
type: ValidationTypes.NUMBER,
params: {
required: true,
min: 100,
max: 200,
default: 150,
},
};
const inputs = [120, 90, 220, undefined, {}, [], "120", ""];
const expected = [
{
isValid: true,
parsed: 120,
},
{
isValid: false,
parsed: 90,
messages: [
{
name: "RangeError",
message: "Minimum allowed value: 100",
},
],
},
{
isValid: false,
parsed: 200,
messages: [
{
name: "RangeError",
message: "Maximum allowed value: 200",
},
],
},
{
isValid: false,
parsed: 150,
messages: [
{
name: "ValidationError",
message: "This value is required",
},
],
},
{
isValid: false,
parsed: 150,
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR} number Min: 100 Max: 200 Required`,
},
],
},
{
isValid: false,
parsed: 150,
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR} number Min: 100 Max: 200 Required`,
},
],
},
{
isValid: true,
parsed: 120,
},
{
isValid: false,
parsed: 150,
messages: [
{
name: "ValidationError",
message: "This value is required",
},
],
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates number when required is false", () => {
const config = {
type: ValidationTypes.NUMBER,
params: {
min: -8,
max: 200,
default: 150,
},
};
const inputs = ["", "-120", "-8"];
const expected = [
{
isValid: true,
parsed: 150,
},
{
isValid: false,
parsed: -120,
messages: [
{
name: "RangeError",
message: "Minimum allowed value: -8",
},
],
},
{
isValid: true,
parsed: -8,
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates boolean when required is true", () => {
const config = {
type: ValidationTypes.BOOLEAN,
params: {
default: false,
required: true,
},
};
const inputs = ["123", undefined, false, true, [], {}, "true", "false", ""];
const expected = [
{
isValid: false,
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR} boolean`,
},
],
parsed: false,
},
{
isValid: false,
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR} boolean`,
},
],
parsed: false,
},
{
isValid: true,
parsed: false,
},
{
isValid: true,
parsed: true,
},
{
isValid: false,
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR} boolean`,
},
],
parsed: false,
},
{
isValid: false,
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR} boolean`,
},
],
parsed: false,
},
{
isValid: true,
parsed: true,
},
{
isValid: true,
parsed: false,
},
{
isValid: false,
parsed: false,
messages: [
{
name: "TypeError",
message: "This value does not evaluate to type boolean",
},
],
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates boolean when required is false", () => {
const config = {
type: ValidationTypes.BOOLEAN,
params: {
default: false,
},
};
const inputs = [""];
const expected = [
{
isValid: true,
parsed: false,
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates object", () => {
const config = {
type: ValidationTypes.OBJECT,
params: {
required: true,
default: { key1: 120, key2: "abc" },
allowedKeys: [
{
name: "key1",
type: ValidationTypes.NUMBER,
params: {
required: true,
default: 120,
},
},
{
name: "key2",
type: ValidationTypes.TEXT,
params: {
default: "abc",
allowedValues: ["abc", "mnop"],
},
},
],
},
};
const inputs = [
{ key1: 100, key2: "mnop" },
`{ "key1": 100, "key2": "mnop" }`,
{ key3: "abc", key1: 30 },
undefined,
[],
{ key1: [], key2: "abc" },
{ key1: 120, key2: {} },
{ key2: "abc", key3: "something" },
];
const expected = [
{
isValid: true,
parsed: { key1: 100, key2: "mnop" },
},
{
isValid: true,
parsed: { key1: 100, key2: "mnop" },
},
{
isValid: true,
parsed: { key1: 30, key3: "abc" },
},
{
isValid: false,
parsed: { key1: 120, key2: "abc" },
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR}: { \"key1\": \"number Required\", \"key2\": \"string ( abc | mnop )\" }`,
},
],
},
{
isValid: false,
parsed: { key1: 120, key2: "abc" },
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR}: { \"key1\": \"number Required\", \"key2\": \"string ( abc | mnop )\" }`,
},
],
},
{
isValid: false,
parsed: { key1: 120, key2: "abc" },
messages: [
{
name: "TypeError",
message: `Value of key: key1 is invalid: This value does not evaluate to type number Required`,
},
],
},
{
isValid: false,
parsed: { key1: 120, key2: "abc" },
messages: [
{
name: "TypeError",
message: `Value of key: key2 is invalid: This value does not evaluate to type string ( abc | mnop )`,
},
],
},
{
isValid: false,
parsed: { key1: 120, key2: "abc" },
messages: [
{
name: "ValidationError",
message: `Missing required key: key1`,
},
],
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates array with allowed values", () => {
const inputs = [
["a", "b", "c"],
["m", "n", "b"],
["p", "r", "q"],
["p", "r", "q", "s"],
[],
{},
];
const config = {
type: ValidationTypes.ARRAY,
params: {
allowedValues: ["a", "b", "c", "n", "m", "p", "r"],
},
};
const expected = [
{
isValid: true,
parsed: ["a", "b", "c"],
messages: [],
},
{
isValid: true,
parsed: ["m", "n", "b"],
messages: [],
},
{
isValid: false,
parsed: [],
messages: [
{
name: "ValidationError",
message: "Value is not allowed in this array: q",
},
],
},
{
isValid: false,
parsed: [],
messages: [
{
name: "ValidationError",
message: "Value is not allowed in this array: q",
},
{
name: "ValidationError",
message: "Value is not allowed in this array: s",
},
],
},
{
isValid: true,
parsed: [],
messages: [],
},
{
isValid: false,
parsed: [],
messages: [
{
name: "TypeError",
message:
"This value does not evaluate to type Array<'a' | 'b' | 'c' | 'n' | 'm' | 'p' | 'r'>",
},
],
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates array with allowed values and default value", () => {
const inputs = [
["a", "b", "c"],
["m", "n", "b"],
["p", "r", "q"],
["p", "r", "q", "s"],
[],
{},
];
const config = {
type: ValidationTypes.ARRAY,
params: {
allowedValues: ["a", "b", "c", "n", "m", "p", "r"],
default: ["a"],
},
};
const expected = [
{
isValid: true,
parsed: ["a", "b", "c"],
messages: [],
},
{
isValid: true,
parsed: ["m", "n", "b"],
messages: [],
},
{
isValid: false,
parsed: ["a"],
messages: [
{
name: "ValidationError",
message: "Value is not allowed in this array: q",
},
],
},
{
isValid: false,
parsed: ["a"],
messages: [
{
name: "ValidationError",
message: "Value is not allowed in this array: q",
},
{
name: "ValidationError",
message: "Value is not allowed in this array: s",
},
],
},
{
isValid: true,
parsed: [],
messages: [],
},
{
isValid: false,
parsed: ["a"],
messages: [
{
name: "TypeError",
message:
"This value does not evaluate to type Array<'a' | 'b' | 'c' | 'n' | 'm' | 'p' | 'r'>",
},
],
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly limits the number of validation errors in array validation", () => {
const input = [
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
];
const config = {
type: ValidationTypes.ARRAY,
params: {
children: {
type: ValidationTypes.NUMBER,
params: {
required: true,
allowedValues: [1, 2, 3, 4],
},
},
},
};
const expected = {
isValid: false,
parsed: [],
messages: [
{
name: "TypeError",
message:
"Invalid entry at index: 0. This value does not evaluate to type number Required",
},
{
name: "TypeError",
message:
"Invalid entry at index: 1. This value does not evaluate to type number Required",
},
{
name: "TypeError",
message:
"Invalid entry at index: 2. This value does not evaluate to type number Required",
},
{
name: "TypeError",
message:
"Invalid entry at index: 3. This value does not evaluate to type number Required",
},
{
name: "TypeError",
message:
"Invalid entry at index: 4. This value does not evaluate to type number Required",
},
{
name: "TypeError",
message:
"Invalid entry at index: 5. This value does not evaluate to type number Required",
},
{
name: "TypeError",
message:
"Invalid entry at index: 6. This value does not evaluate to type number Required",
},
{
name: "TypeError",
message:
"Invalid entry at index: 7. This value does not evaluate to type number Required",
},
{
name: "TypeError",
message:
"Invalid entry at index: 8. This value does not evaluate to type number Required",
},
{
name: "TypeError",
message:
"Invalid entry at index: 9. This value does not evaluate to type number Required",
},
],
};
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected);
});
it("correctly validates array when required is true", () => {
const inputs = [
["a", "b", "c"],
["m", "n", "b"],
["p", "r", "q"],
[],
{},
undefined,
null,
"ABC",
`["a", "b", "c"]`,
'{ "key": "value" }',
["a", "b", "a", "c"],
"",
"[]",
];
const config = {
type: ValidationTypes.ARRAY,
params: {
required: true,
unique: true,
children: {
type: ValidationTypes.TEXT,
params: {
required: true,
allowedValues: ["a", "b", "c", "n", "m", "p", "r"],
},
},
},
};
const expected = [
{
isValid: true,
parsed: ["a", "b", "c"],
messages: [],
},
{
isValid: true,
parsed: ["m", "n", "b"],
messages: [],
},
{
isValid: false,
parsed: [],
messages: [
{
name: "ValidationError",
message: "Invalid entry at index: 2. Disallowed value: q",
},
],
},
{
isValid: true,
parsed: [],
messages: [],
},
{
isValid: false,
parsed: [],
messages: [
{
name: "TypeError",
message:
"This value does not evaluate to type Array<string ( a | b | c | n | m | p | r )>",
},
],
},
{
isValid: false,
parsed: [],
messages: [
{
name: "ValidationError",
message:
"This property is required for the widget to function correctly",
},
],
},
{
isValid: false,
parsed: [],
messages: [
{
name: "ValidationError",
message:
"This property is required for the widget to function correctly",
},
],
},
{
isValid: false,
parsed: [],
messages: [
{
name: "TypeError",
message:
"This value does not evaluate to type Array<string ( a | b | c | n | m | p | r )>",
},
],
},
{
isValid: true,
parsed: ["a", "b", "c"],
messages: [],
},
{
isValid: false,
parsed: [],
messages: [
{
name: "TypeError",
message:
"This value does not evaluate to type Array<string ( a | b | c | n | m | p | r )>",
},
],
},
{
isValid: false,
parsed: [],
messages: [
{
name: "ValidationError",
message: "Array must be unique. Duplicate values found at index: 2",
},
],
},
{
isValid: false,
parsed: [],
messages: [
{
name: "ValidationError",
message:
"This property is required for the widget to function correctly",
},
],
},
{
isValid: true,
parsed: [],
messages: [],
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates array when required is false", () => {
const inputs = [""];
const config = {
type: ValidationTypes.ARRAY,
params: {
unique: true,
children: {
type: ValidationTypes.TEXT,
params: {
required: true,
allowedValues: ["a", "b", "c", "n", "m", "p", "r"],
},
},
},
};
const expected = [
{
isValid: true,
parsed: [],
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates array with specific object children and required is true", () => {
const inputs = [
[{ label: 123, value: 234 }],
`[{"label": 123, "value": 234}]`,
[{ labels: 123, value: 234 }],
[{ label: "abcd", value: 234 }],
[{}],
[],
"",
];
const config = {
type: ValidationTypes.ARRAY,
params: {
required: true,
children: {
type: ValidationTypes.OBJECT,
params: {
allowedKeys: [
{
name: "label",
type: ValidationTypes.NUMBER,
params: {
required: true,
},
},
{
name: "value",
type: ValidationTypes.NUMBER,
params: {
required: true,
},
},
],
},
},
},
};
const expected = [
{
isValid: true,
parsed: [{ label: 123, value: 234 }],
messages: [],
},
{
isValid: true,
parsed: [{ label: 123, value: 234 }],
messages: [],
},
{
isValid: false,
parsed: [],
messages: [
{
name: "ValidationError",
message: "Invalid entry at index: 0. Missing required key: label",
},
],
},
{
isValid: false,
parsed: [],
messages: [
{
name: "TypeError",
message: `Invalid entry at index: 0. Value of key: label is invalid: This value does not evaluate to type number Required`,
},
],
},
{
isValid: false,
parsed: [],
messages: [
{
name: "ValidationError",
message: "Invalid entry at index: 0. Missing required key: label",
},
{
name: "ValidationError",
message: "Invalid entry at index: 0. Missing required key: value",
},
],
},
{
isValid: true,
parsed: [],
messages: [],
},
{
isValid: false,
parsed: [],
messages: [
{
name: "ValidationError",
message:
"This property is required for the widget to function correctly",
},
],
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates array with specific object children and required is false", () => {
const inputs = [""];
const config = {
type: ValidationTypes.ARRAY,
params: {
children: {
type: ValidationTypes.OBJECT,
params: {
allowedKeys: [
{
name: "label",
type: ValidationTypes.NUMBER,
params: {
required: true,
},
},
{
name: "value",
type: ValidationTypes.NUMBER,
params: {
required: true,
},
},
],
},
},
},
};
const expected = [
{
isValid: true,
parsed: [],
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates date iso string when required is true", () => {
const defaultLocalDate = moment().toISOString(true);
const defaultDate = moment().toISOString();
const inputs = [
defaultDate,
defaultLocalDate,
"2021-08-08",
undefined,
null,
"",
];
const config = {
type: ValidationTypes.DATE_ISO_STRING,
params: {
required: true,
default: defaultDate,
},
};
const expected = [
{
isValid: true,
parsed: defaultDate,
},
{
isValid: true,
parsed: defaultLocalDate,
},
{
isValid: true,
messages: [{ name: "", message: "" }],
parsed: moment("2021-08-08").toISOString(true),
},
{
isValid: false,
parsed: defaultDate,
messages: [
{
name: "TypeError",
message: "Value does not match: ISO 8601 date string",
},
],
},
{
isValid: false,
parsed: defaultDate,
messages: [
{
name: "TypeError",
message: "Value does not match: ISO 8601 date string",
},
],
},
{
isValid: false,
messages: [
{
name: "TypeError",
message: "Value does not match: ISO 8601 date string",
},
],
parsed: defaultDate,
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates date iso string when required is false", () => {
const defaultDate = moment().toISOString();
const inputs = [""];
const config = {
type: ValidationTypes.DATE_ISO_STRING,
params: {
required: false,
default: "",
},
};
const expected = [
{
isValid: true,
messages: [{ name: "", message: "" }],
parsed: "",
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
expect(result).not.toStrictEqual(defaultDate);
});
});
it("correctly validates object array when required is true", () => {
const inputs = [
[
{ apple: 1 },
{ orange: 2, mango: "fruit", watermelon: false },
{ banana: 3 },
],
`[{ "apple": 1, "orange": 2, "mango": "fruit", "watermelon": false }]`,
{},
undefined,
null,
[],
123,
"abcd",
[null],
[{ apple: 1 }, null, { banana: "2" }, undefined],
`[{ "apple": 1, "orange": 2, "mango": "fruit", "watermelon": false }, null]`,
"",
];
const config = {
type: ValidationTypes.OBJECT_ARRAY,
params: {
required: true,
default: [{ id: 1, name: "alpha" }],
},
};
const expected = [
{
isValid: true,
parsed: [
{ apple: 1 },
{ orange: 2, mango: "fruit", watermelon: false },
{ banana: 3 },
],
},
{
isValid: true,
parsed: [{ apple: 1, orange: 2, mango: "fruit", watermelon: false }],
},
{
isValid: false,
parsed: [{ id: 1, name: "alpha" }],
messages: [
{
name: "TypeError",
message: "This value does not evaluate to type Array<Object>",
},
],
},
{
isValid: false,
parsed: [{ id: 1, name: "alpha" }],
messages: [
{
name: "TypeError",
message: "This value does not evaluate to type Array<Object>",
},
],
},
{
isValid: false,
parsed: [{ id: 1, name: "alpha" }],
messages: [
{
name: "TypeError",
message: "This value does not evaluate to type Array<Object>",
},
],
},
{
isValid: false,
parsed: [{ id: 1, name: "alpha" }],
messages: [
{
name: "TypeError",
message: "This value does not evaluate to type Array<Object>",
},
],
},
{
isValid: false,
parsed: [{ id: 1, name: "alpha" }],
messages: [
{
name: "TypeError",
message: "This value does not evaluate to type Array<Object>",
},
],
},
{
isValid: false,
parsed: [{ id: 1, name: "alpha" }],
messages: [
{
name: "TypeError",
message: "This value does not evaluate to type Array<Object>",
},
],
},
{
isValid: false,
parsed: [{ id: 1, name: "alpha" }],
messages: [
{
name: "ValidationError",
message: "Invalid object at index 0",
},
],
},
{
isValid: false,
parsed: [{ id: 1, name: "alpha" }],
messages: [
{
name: "ValidationError",
message: "Invalid object at index 1",
},
],
},
{
isValid: false,
parsed: [{ id: 1, name: "alpha" }],
messages: [
{
name: "ValidationError",
message: "Invalid object at index 1",
},
],
},
{
isValid: false,
parsed: [{ id: 1, name: "alpha" }],
messages: [
{
name: "TypeError",
message: "This value does not evaluate to type Array<Object>",
},
],
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates object array when required is false", () => {
const inputs = [""];
const config = {
type: ValidationTypes.OBJECT_ARRAY,
params: {
required: false,
default: [{ id: 1, name: "alpha" }],
},
};
const expected = [
{
isValid: true,
parsed: [{ id: 1, name: "alpha" }],
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates object array when required is false", () => {
const inputs = [[]];
const config = {
type: ValidationTypes.OBJECT_ARRAY,
params: {
required: false,
default: [{ id: 1, name: "alpha" }],
},
};
const expected = [
{
isValid: true,
parsed: [{ id: 1, name: "alpha" }],
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates safe URL", () => {
const config = {
type: ValidationTypes.SAFE_URL,
params: {
default: "https://www.example.com",
},
};
const inputs = [
"https://www.example.com",
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==",
"javascript:alert(document.cookie)",
"data:text/html,<svg onload=alert(1)>",
];
const expected = [
{
isValid: true,
parsed: "https://www.example.com",
},
{
isValid: true,
parsed:
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==",
},
{
isValid: false,
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR}: URL`,
},
],
parsed: "https://www.example.com",
},
{
isValid: false,
messages: [
{
name: "TypeError",
message: `${WIDGET_TYPE_VALIDATION_ERROR}: URL`,
},
],
parsed: "https://www.example.com",
},
];
inputs.forEach((input, index) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[index]);
});
});
it("correctly validates array when default is given", () => {
const inputs = [undefined, null, ""];
const config = {
type: ValidationTypes.ARRAY,
params: {
required: true,
unique: true,
default: [],
},
};
const expected = {
isValid: true,
parsed: [],
};
inputs.forEach((input) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected);
});
});
it("correctly validates uniqueness of keys in array objects", () => {
const config = {
type: ValidationTypes.ARRAY,
params: {
children: {
type: ValidationTypes.OBJECT,
params: {
allowedKeys: [
{
name: "label",
type: ValidationTypes.TEXT,
params: {
default: "",
required: true,
unique: true,
},
},
{
name: "value",
type: ValidationTypes.TEXT,
params: {
default: "",
unique: true,
},
},
],
},
},
},
};
const input = [
{ label: "Blue", value: "" },
{ label: "Green", value: "" },
{ label: "Red", value: "red" },
];
const expected = {
isValid: false,
parsed: [],
messages: [
{
name: "ValidationError",
message:
"Duplicate values found for the following properties, in the array entries, that must be unique -- label,value.",
},
],
};
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected);
});
it("correctly validates TableProperty", () => {
const inputs = [
"a",
["a", "b"],
"x",
["a", "b", "x"],
["a", "b", "x", "y"],
];
const config = {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: {
type: ValidationTypes.TEXT,
params: {
allowedValues: ["a", "b", "c"],
default: "a",
},
},
};
const expected = [
{
isValid: true,
parsed: "a",
},
{
isValid: true,
parsed: ["a", "b"],
},
{
isValid: false,
parsed: "a",
messages: [
{
name: "ValidationError",
message: "Disallowed value: x",
},
],
},
{
isValid: false,
parsed: "a",
messages: [
{
name: "ValidationError",
message: "Disallowed value: x",
},
],
},
{
isValid: false,
parsed: "a",
messages: [
{
name: "ValidationError",
message: "Disallowed value: x",
},
],
},
];
inputs.forEach((input, i) => {
const result = validate(config, input, DUMMY_WIDGET);
expect(result).toStrictEqual(expected[i]);
});
});
});
// describe("Color Picker Text validator", () => {
// const validator = VALIDATORS.COLOR_PICKER_TEXT;
// const inputs = [
// "#e0e0e0",
// "rgb(200,200,200)",
// "{{Text2.text}}",
// "<p>red</p>",
// ];
// const expected = [
// {
// isValid: true,
// parsed: "#e0e0e0",
// },
// {
// isValid: true,
// parsed: "rgb(200,200,200)",
// },
// {
// isValid: false,
// parsed: "",
// message: "This value does not evaluate to type: text",
// },
// {
// isValid: false,
// parsed: "",
// message: "This value does not evaluate to type: text",
// },
// ];
// inputs.forEach((input, index) => {
// const response = validator(input, DUMMY_WIDGET);
// expect(response).toStrictEqual(expected[index]);
// });
// });
|
2,481 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/fns | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/fns/__tests__/LocalStorage.test.ts | import { addPlatformFunctionsToEvalContext } from "@appsmith/workers/Evaluation/Actions";
import { PluginType } from "entities/Action";
import type { ActionEntity } from "@appsmith/entities/DataTree/types";
import type { DataTree } from "entities/DataTree/dataTreeTypes";
import { createEvaluationContext } from "workers/Evaluation/evaluate";
import initLocalStorage from "../overrides/localStorage";
import { ENTITY_TYPE } from "pages/common/SearchSnippets";
describe("Tests localStorage implementation in worker", () => {
const dataTree: DataTree = {
action1: {
actionId: "123",
pluginId: "",
data: {},
config: {},
datasourceUrl: "",
pluginType: PluginType.API,
dynamicBindingPathList: [],
name: "action1",
bindingPaths: {},
reactivePaths: {},
isLoading: false,
run: {},
clear: {},
responseMeta: { isExecutionSuccess: false },
ENTITY_TYPE: ENTITY_TYPE.ACTION,
dependencyMap: {},
logBlackList: {},
} as ActionEntity,
};
const workerEventMock = jest.fn();
self.postMessage = workerEventMock;
self["$isDataField"] = false;
const evalContext = createEvaluationContext({
dataTree,
isTriggerBased: true,
context: {},
});
addPlatformFunctionsToEvalContext(evalContext);
initLocalStorage.call(evalContext);
it("setItem()", () => {
const key = "some";
const value = "thing";
jest.useFakeTimers();
evalContext.localStorage.setItem(key, value);
jest.runAllTimers();
expect(workerEventMock).lastCalledWith({
messageType: "DEFAULT",
body: {
data: [
{
payload: {
key: "some",
value: "thing",
persist: true,
},
type: "STORE_VALUE",
},
],
method: "PROCESS_STORE_UPDATES",
},
});
});
it("getItem()", () => {
expect(evalContext.localStorage.getItem("some")).toBe("thing");
});
it("removeItem()", () => {
evalContext.localStorage.removeItem("some");
jest.runAllTimers();
expect(workerEventMock).lastCalledWith({
messageType: "DEFAULT",
body: {
data: [
{
payload: {
key: "some",
},
type: "REMOVE_VALUE",
},
],
method: "PROCESS_STORE_UPDATES",
},
});
});
it("clear()", () => {
evalContext.localStorage.clear();
jest.runAllTimers();
expect(workerEventMock).lastCalledWith({
messageType: "DEFAULT",
body: {
data: [
{
payload: null,
type: "CLEAR_STORE",
},
],
method: "PROCESS_STORE_UPDATES",
},
});
});
});
|
2,482 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/fns | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/fns/__tests__/interval.test.ts | jest.useFakeTimers();
import { EventType } from "constants/AppsmithActionConstants/ActionConstants";
import { PluginType } from "entities/Action";
import type { ActionEntity } from "@appsmith/entities/DataTree/types";
import type { DataTree } from "entities/DataTree/dataTreeTypes";
import { ENTITY_TYPE_VALUE } from "entities/DataTree/dataTreeFactory";
import { overrideWebAPIs } from "../overrides";
import ExecutionMetaData from "../utils/ExecutionMetaData";
import { addPlatformFunctionsToEvalContext } from "@appsmith/workers/Evaluation/Actions";
import { createEvaluationContext } from "workers/Evaluation/evaluate";
const dataTree: DataTree = {
action1: {
actionId: "123",
pluginId: "",
data: {},
config: {},
datasourceUrl: "",
pluginType: PluginType.API,
dynamicBindingPathList: [],
name: "action1",
bindingPaths: {},
reactivePaths: {},
isLoading: false,
run: {},
clear: {},
responseMeta: { isExecutionSuccess: false },
ENTITY_TYPE: ENTITY_TYPE_VALUE.ACTION,
dependencyMap: {},
logBlackList: {},
} as ActionEntity,
};
const evalContext = createEvaluationContext({
dataTree,
isTriggerBased: true,
context: {},
});
jest.mock("workers/Evaluation/handlers/evalTree", () => ({
get dataTreeEvaluator() {
return {
evalTree: evalContext,
};
},
}));
describe("Tests for interval functions", () => {
beforeAll(() => {
self["$isDataField"] = false;
self["$cloudHosting"] = false;
ExecutionMetaData.setExecutionMetaData({
triggerMeta: {},
eventType: EventType.ON_PAGE_LOAD,
});
overrideWebAPIs(evalContext);
addPlatformFunctionsToEvalContext(evalContext);
});
afterAll(() => {
jest.clearAllMocks();
jest.clearAllTimers();
jest.useRealTimers();
});
it("Should call the callback function after the interval", async () => {
const callback = jest.fn();
const interval = evalContext.setInterval(callback, 1000);
jest.advanceTimersByTime(1000);
expect(callback).toBeCalledTimes(1);
evalContext.clearInterval(interval);
});
it("Should not call the callback function after the interval is cleared", async () => {
const callback = jest.fn();
const interval = evalContext.setInterval(callback, 1000);
jest.advanceTimersByTime(1000);
expect(callback).toBeCalledTimes(1);
evalContext.clearInterval(interval);
jest.advanceTimersByTime(1000);
expect(callback).toBeCalledTimes(1);
});
it("Callback should have access to outer scope variables", async () => {
const stalker = jest.fn();
function runTest() {
let count = 0;
const interval = evalContext.setInterval(() => {
count++;
stalker(count);
}, 1000);
return interval;
}
const interval = runTest();
jest.advanceTimersByTime(3000);
evalContext.clearInterval(interval);
expect(stalker).toBeCalledTimes(3);
expect(stalker).toBeCalledWith(1);
expect(stalker).toBeCalledWith(2);
expect(stalker).toBeCalledWith(3);
});
it("It should have access to platform fns inside callbacks", async () => {
const showAlertMock = jest.fn();
//@ts-expect-error no types for this
self.showAlert = showAlertMock;
const interval = evalContext.setInterval(() => {
//@ts-expect-error no types for this
self.showAlert("Hello World");
}, 1000);
jest.advanceTimersByTime(2000);
evalContext.clearInterval(interval);
expect(showAlertMock).toBeCalledTimes(2);
expect(showAlertMock).toBeCalledWith("Hello World");
});
});
|
2,483 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/fns | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/fns/__tests__/postWindowMessage.test.ts | import { addPlatformFunctionsToEvalContext } from "@appsmith/workers/Evaluation/Actions";
import TriggerEmitter, { BatchKey } from "../utils/TriggerEmitter";
import { evalContext } from "../mock";
const pingMock = jest.fn();
jest.mock("../utils/Messenger.ts", () => ({
WorkerMessenger: {
ping: (payload: any) => pingMock(JSON.stringify(payload)),
},
}));
describe("Post window message works", () => {
beforeAll(() => {
self["$isDataField"] = false;
addPlatformFunctionsToEvalContext(evalContext);
});
it("postMessage payload check", async () => {
const targetOrigin = "https://dev.appsmith.com/";
const source = "window";
const message = {
key1: 1,
key2: undefined,
key3: undefined,
key4: "test",
key5: {
key6: "test",
},
key7: [1, 2, 3, [4, 5, 6]],
};
const batchSpy = jest.fn();
TriggerEmitter.on(BatchKey.process_batched_triggers, batchSpy);
expect(evalContext.postWindowMessage(message, source, targetOrigin)).toBe(
undefined,
);
expect(batchSpy).toBeCalledTimes(1);
expect(batchSpy).toBeCalledTimes(1);
expect(batchSpy).toBeCalledWith({
trigger: {
payload: {
message,
source: "window",
targetOrigin: "https://dev.appsmith.com/",
},
type: "POST_MESSAGE",
},
triggerMeta: {
source: {},
triggerPropertyName: undefined,
},
eventType: undefined,
enableJSFnPostProcessors: true,
enableJSVarUpdateTracking: true,
});
TriggerEmitter.removeListener(BatchKey.process_batched_triggers, batchSpy);
batchSpy.mockClear();
});
});
|
2,484 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/fns | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/fns/__tests__/run.test.ts | import { MAIN_THREAD_ACTION } from "@appsmith/workers/Evaluation/evalWorkerActions";
import { addPlatformFunctionsToEvalContext } from "@appsmith/workers/Evaluation/Actions";
import { EventType } from "constants/AppsmithActionConstants/ActionConstants";
import ExecutionMetaData from "../utils/ExecutionMetaData";
import { evalContext } from "../mock";
jest.mock("workers/Evaluation/handlers/evalTree", () => ({
get dataTreeEvaluator() {
return {
evalTree: evalContext,
};
},
}));
const requestMock = jest.fn();
jest.mock("../utils/Messenger.ts", () => ({
...jest.requireActual("../utils/Messenger.ts"),
get WorkerMessenger() {
return {
request: (...args: any) => requestMock(...args),
};
},
}));
describe("Tests for run function in callback styled", () => {
beforeAll(() => {
self["$isDataField"] = false;
ExecutionMetaData.setExecutionMetaData({
triggerMeta: {},
eventType: EventType.ON_PAGE_LOAD,
});
addPlatformFunctionsToEvalContext(evalContext);
});
beforeEach(() => {
requestMock.mockClear();
});
it("1. Success callback should be called when the request is successful", async () => {
requestMock.mockReturnValue(
Promise.resolve({
data: ["resolved"],
}),
);
const successCallback = jest.fn(() => "success");
const errorCallback = jest.fn(() => "failed");
await evalContext.action1.run(successCallback, errorCallback);
expect(requestMock).toBeCalledWith({
method: MAIN_THREAD_ACTION.PROCESS_TRIGGER,
data: {
enableJSFnPostProcessors: true,
enableJSVarUpdateTracking: true,
trigger: {
type: "RUN_PLUGIN_ACTION",
payload: {
actionId: "123",
params: {},
onSuccess: successCallback.toString(),
onError: errorCallback.toString(),
},
},
eventType: "ON_PAGE_LOAD",
triggerMeta: {
source: {},
triggerPropertyName: undefined,
},
},
});
expect(successCallback).toBeCalledWith("resolved");
expect(successCallback).toReturnWith("success");
expect(errorCallback).not.toBeCalled();
});
it("2. Error callback should be called when the request is unsuccessful", async () => {
requestMock.mockReturnValue(
Promise.resolve({
error: { message: "error" },
}),
);
const successCallback = jest.fn(() => "success");
const errorCallback = jest.fn(() => "failed");
await evalContext.action1.run(successCallback, errorCallback);
expect(requestMock).toBeCalledWith({
method: MAIN_THREAD_ACTION.PROCESS_TRIGGER,
data: {
enableJSFnPostProcessors: true,
enableJSVarUpdateTracking: true,
trigger: {
type: "RUN_PLUGIN_ACTION",
payload: {
actionId: "123",
params: {},
onSuccess: successCallback.toString(),
onError: errorCallback.toString(),
},
},
eventType: "ON_PAGE_LOAD",
triggerMeta: {
source: {},
triggerPropertyName: undefined,
},
},
});
expect(errorCallback).toBeCalledWith("error");
expect(errorCallback).toReturnWith("failed");
expect(successCallback).toBeCalledTimes(0);
});
it("3. Callback should have access to variables in outer scope", async () => {
requestMock.mockReturnValue(
Promise.resolve({
data: ["resolved"],
}),
);
const successCallback = jest.fn();
await (async function () {
const innerScopeVar = "innerScopeVar";
successCallback.mockImplementation(() => innerScopeVar);
await evalContext.action1.run(successCallback);
})();
expect(successCallback).toBeCalledWith("resolved");
expect(successCallback).toReturnWith("innerScopeVar");
});
it("4. Callback should have access to other platform functions and entities at all times", async () => {
const showAlertMock = jest.fn();
//@ts-expect-error no types
self.showAlert = showAlertMock;
requestMock.mockReturnValue(
new Promise((resolve) => {
setTimeout(() => {
resolve({
data: ["resolved"],
});
}, 1000);
}),
);
const successCallback = jest.fn(() =>
//@ts-expect-error no types
self.showAlert(evalContext.action1.actionId),
);
await evalContext.action1.run(successCallback);
expect(successCallback).toBeCalledWith("resolved");
expect(showAlertMock).toBeCalledWith("123");
});
});
describe("Tests for run function in promise styled", () => {
beforeAll(() => {
self["$isDataField"] = false;
ExecutionMetaData.setExecutionMetaData({
triggerMeta: {},
eventType: EventType.ON_PAGE_LOAD,
});
addPlatformFunctionsToEvalContext(evalContext);
});
it("1. Should return a promise which resolves when the request is successful", async () => {
requestMock.mockReturnValue(
Promise.resolve({
data: ["resolved"],
}),
);
const successHandler = jest.fn();
const invocation = evalContext.action1.run();
invocation.then(successHandler);
expect(requestMock).toBeCalledWith({
method: MAIN_THREAD_ACTION.PROCESS_TRIGGER,
data: {
enableJSFnPostProcessors: true,
enableJSVarUpdateTracking: true,
trigger: {
type: "RUN_PLUGIN_ACTION",
payload: {
actionId: "123",
params: {},
},
},
eventType: "ON_PAGE_LOAD",
triggerMeta: {
source: {},
triggerPropertyName: undefined,
},
},
});
await expect(invocation).resolves.toEqual("resolved");
expect(successHandler).toBeCalledWith("resolved");
});
it("2. Should return a promise which rejects when the request is unsuccessful", async () => {
requestMock.mockReturnValue(
Promise.resolve({
error: { message: "error" },
}),
);
const successHandler = jest.fn();
const errorHandler = jest.fn();
await evalContext.action1.run().then(successHandler).catch(errorHandler);
expect(requestMock).toBeCalledWith({
method: MAIN_THREAD_ACTION.PROCESS_TRIGGER,
data: {
enableJSFnPostProcessors: true,
enableJSVarUpdateTracking: true,
trigger: {
type: "RUN_PLUGIN_ACTION",
payload: {
actionId: "123",
params: {},
},
},
eventType: "ON_PAGE_LOAD",
triggerMeta: {
source: {},
triggerPropertyName: undefined,
},
},
});
expect(successHandler).not.toBeCalled();
expect(errorHandler).toBeCalledWith({ message: "error" });
});
});
|
2,497 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/fns/utils | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/fns/utils/__tests__/Messenger.test.ts | import { MessageType } from "utils/MessageUtil";
import { WorkerMessenger } from "../Messenger";
describe("Tests all worker messenger method", () => {
const mockPostMessage = jest.fn();
self.postMessage = mockPostMessage;
afterEach(() => {
mockPostMessage.mockClear();
});
it("messenger.request", () => {
const response = WorkerMessenger.request({
method: "test",
data: {
trigger: {
type: "MOCK_TRIGGER",
payload: {},
},
eventType: "Test",
triggerMeta: {},
},
});
expect(mockPostMessage).toBeCalledWith({
messageId: expect.stringContaining("request-test"),
messageType: MessageType.REQUEST,
body: {
method: "test",
data: {
trigger: {
type: "MOCK_TRIGGER",
payload: {},
},
eventType: "Test",
triggerMeta: {},
},
},
});
const messageId = mockPostMessage.mock.calls[0][0].messageId;
dispatchEvent(
new MessageEvent("message", {
data: {
messageId,
messageType: MessageType.RESPONSE,
body: {
data: {
data: "resolved",
},
},
},
}),
);
expect(response).resolves.toStrictEqual({ data: "resolved" });
});
it("messenger.ping", () => {
WorkerMessenger.ping({
type: "MOCK_TRIGGER",
payload: {},
});
expect(mockPostMessage).toBeCalledWith({
messageType: MessageType.DEFAULT,
body: {
type: "MOCK_TRIGGER",
payload: {},
},
});
});
});
|
2,498 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/fns/utils | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/fns/utils/__tests__/Promisify.test.ts | // eslint-disable-next-line @typescript-eslint/no-unused-vars
const requestMock = jest.fn(async (...args: any) => Promise.resolve("success"));
jest.mock("../Messenger.ts", () => ({
...jest.requireActual("../Messenger.ts"),
WorkerMessenger: {
request: async (...args: any) => requestMock(...args),
},
}));
jest.mock("workers/Evaluation/handlers/evalTree", () => ({
get dataTreeEvaluator() {
return {
evalTree: {},
};
},
}));
import { MAIN_THREAD_ACTION } from "@appsmith/workers/Evaluation/evalWorkerActions";
import { EventType } from "constants/AppsmithActionConstants/ActionConstants";
import ExecutionMetaData from "../ExecutionMetaData";
import { promisify } from "../Promisify";
describe("Tests for promisify util", () => {
const triggerMeta = {
source: {
id: "testId",
name: "testName",
},
triggerPropertyName: "testProp",
};
const eventType = EventType.ON_PAGE_LOAD;
beforeAll(() => {
ExecutionMetaData.setExecutionMetaData({ triggerMeta, eventType });
});
it("Should dispatch payload return by descriptor", async () => {
const metaDataSpy = jest.spyOn(ExecutionMetaData, "setExecutionMetaData");
//@ts-expect-error No types;
self.showAlert = undefined;
const descriptor = jest.fn((key) => ({
type: "TEST_TYPE",
payload: { key },
}));
const executor = promisify(descriptor);
await executor(123);
expect(requestMock).toBeCalledTimes(1);
expect(requestMock).toBeCalledWith({
method: MAIN_THREAD_ACTION.PROCESS_TRIGGER,
data: {
enableJSFnPostProcessors: true,
enableJSVarUpdateTracking: true,
trigger: {
type: "TEST_TYPE",
payload: { key: 123 },
},
eventType,
triggerMeta,
},
});
expect(metaDataSpy).toBeCalledTimes(1);
expect(metaDataSpy).toBeCalledWith({
triggerMeta,
eventType,
enableJSFnPostProcessors: true,
enableJSVarUpdateTracking: true,
});
});
});
|
2,499 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/fns/utils | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/fns/utils/__tests__/TriggerEmitter.test.ts | const pingMock = jest.fn();
jest.mock("../Messenger.ts", () => ({
...jest.requireActual("../Messenger.ts"),
get WorkerMessenger() {
return {
ping: (...args: any) => {
pingMock(JSON.stringify(args[0]));
},
};
},
}));
import { MAIN_THREAD_ACTION } from "@appsmith/workers/Evaluation/evalWorkerActions";
import TriggerEmitter, { BatchKey } from "../TriggerEmitter";
describe("Tests all trigger events", () => {
it("Should invoke the right callback", () => {
const callback = jest.fn();
TriggerEmitter.on("test", callback);
TriggerEmitter.emit("test", "test");
expect(callback).toBeCalledWith("test");
TriggerEmitter.removeListener("test", callback);
});
it("show batch events of key process_store_updates", async () => {
const payload1 = {
type: "STORE_VALUE",
payload: {
name: "test",
value: "test",
persist: true,
},
};
const payload2 = {
type: "REMOVE_VALUE",
payload: {
name: "test",
},
};
const payload3 = {
type: "CLEAR_STORE",
payload: {},
};
TriggerEmitter.emit(BatchKey.process_store_updates, payload1);
TriggerEmitter.emit(BatchKey.process_store_updates, payload2);
TriggerEmitter.emit(BatchKey.process_store_updates, payload3);
await new Promise((resolve) => setTimeout(resolve, 100));
expect(pingMock).toBeCalledTimes(1);
expect(pingMock).toBeCalledWith(
JSON.stringify({
method: MAIN_THREAD_ACTION.PROCESS_STORE_UPDATES,
data: [payload1, payload2, payload3],
}),
);
pingMock.mockClear();
});
it("it should call store updates(priority) before logs(deferred)", async () => {
const payload1 = {
data: {
data: "log",
},
};
const payload2 = {
type: "STORE_VALUE",
payload: {
name: "test",
value: "test",
persist: true,
},
};
TriggerEmitter.emit(BatchKey.process_logs, payload1);
TriggerEmitter.emit(BatchKey.process_logs, payload1);
TriggerEmitter.emit(BatchKey.process_logs, payload1);
TriggerEmitter.emit(BatchKey.process_store_updates, payload2);
await new Promise((resolve) => setTimeout(resolve, 100));
expect(pingMock).toBeCalledTimes(2);
const args = pingMock.mock.calls;
expect(args[0][0]).toBe(
JSON.stringify({
method: MAIN_THREAD_ACTION.PROCESS_STORE_UPDATES,
data: [payload2],
}),
);
expect(args[1][0]).toBe(
JSON.stringify({
method: MAIN_THREAD_ACTION.PROCESS_LOGS,
data: [payload1, payload1, payload1],
}),
);
pingMock.mockClear();
});
});
|
2,512 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/handlers | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/handlers/__tests__/evalTree.test.ts | import { WorkerMessenger } from "workers/Evaluation/fns/utils/Messenger";
import { evalTreeTransmissionErrorHandler } from "../evalTree";
import { isFunction } from "lodash";
const mockEvalErrorHandler = jest.fn();
const mockSendMessage = jest.fn();
jest.mock("workers/Evaluation/handlers/evalTree", () => {
const actualExports = jest.requireActual(
"workers/Evaluation/handlers/evalTree",
);
return {
__esModule: true,
...actualExports,
evalTreeTransmissionErrorHandler: (...args: unknown[]) => {
mockEvalErrorHandler();
actualExports.evalTreeTransmissionErrorHandler(...args);
},
};
});
jest.mock("utils/MessageUtil", () => {
const actualExports = jest.requireActual("utils/MessageUtil");
return {
__esModule: true,
...actualExports,
sendMessage: (...args: any[]) => {
mockSendMessage(args[0].body.data);
const {
body: { data },
} = args[0];
if (isFunction(data.response)) {
throw new Error("unserializable data");
}
},
};
});
describe("test", () => {
it("calls custom evalTree error handler", () => {
const UNSERIALIZABLE_DATA = {
response: () => {},
logs: {
depedencies: { name: ["test", "you"] },
},
};
WorkerMessenger.respond(
"TEST",
UNSERIALIZABLE_DATA,
4,
evalTreeTransmissionErrorHandler,
);
// Since response is unserializable, expect EvalErrorHandler to be called
expect(mockEvalErrorHandler).toBeCalledTimes(1);
// Error in the first attempt, then, a successfully second attempt
expect(mockSendMessage).toBeCalledTimes(2);
expect(mockSendMessage.mock.calls[0]).toEqual([UNSERIALIZABLE_DATA]);
// The error handler should convert data to a serializable form
expect(mockSendMessage.mock.calls[1]).toEqual([
JSON.parse(JSON.stringify(UNSERIALIZABLE_DATA)),
]);
});
});
|
2,513 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/handlers | petrpan-code/appsmithorg/appsmith/app/client/src/workers/Evaluation/handlers/__tests__/jsLibrary.test.ts | import { flattenModule, installLibrary, uninstallLibrary } from "../jsLibrary";
import {
EVAL_WORKER_ASYNC_ACTION,
EVAL_WORKER_SYNC_ACTION,
} from "@appsmith/workers/Evaluation/evalWorkerActions";
import * as mod from "../../../common/JSLibrary/ternDefinitionGenerator";
jest.mock("../../../common/JSLibrary/ternDefinitionGenerator");
declare const self: WorkerGlobalScope;
describe("Tests to assert install/uninstall flows", function () {
beforeAll(() => {
self.importScripts = jest.fn(() => {
self.lodash = {};
});
self.import = jest.fn();
const mockTernDefsGenerator = jest.fn(() => ({}));
jest.mock("../../../common/JSLibrary/ternDefinitionGenerator.ts", () => {
return {
makeTernDefs: mockTernDefsGenerator,
};
});
});
it("should install a library", async function () {
const res = await installLibrary({
data: {
url: "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js",
takenAccessors: [],
takenNamesMap: {},
},
method: EVAL_WORKER_ASYNC_ACTION.INSTALL_LIBRARY,
});
//
expect(self.importScripts).toHaveBeenCalled();
expect(mod.makeTernDefs).toHaveBeenCalledWith({});
expect(res).toEqual({
success: true,
defs: {
"!name": "LIB/lodash",
lodash: undefined,
},
accessor: ["lodash"],
});
});
it("Reinstalling a different version of the same installed library should create a new accessor", async function () {
const res = await installLibrary({
data: {
url: "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.0/lodash.min.js",
takenAccessors: ["lodash"],
takenNamesMap: {},
},
method: EVAL_WORKER_ASYNC_ACTION.INSTALL_LIBRARY,
});
expect(res).toEqual({
success: true,
defs: {
"!name": "LIB/lodash_1",
lodash_1: undefined,
},
accessor: ["lodash_1"],
});
});
it("Detects name space collision where there is another entity(api, widget or query) with the same name and creates a unique accessor", async function () {
delete self["lodash"];
const res = await installLibrary({
data: {
url: "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.0/lodash.min.js",
takenAccessors: ["lodash_1"],
takenNamesMap: { lodash: true },
},
method: EVAL_WORKER_ASYNC_ACTION.INSTALL_LIBRARY,
});
expect(res).toEqual({
success: true,
defs: {
"!name": "LIB/lodash_2",
lodash_2: undefined,
},
accessor: ["lodash_2"],
});
delete self["lodash_2"];
});
it("Removes or set the accessors to undefined on the global object on un-installation", async function () {
self.lodash = {};
const res = await uninstallLibrary({
data: ["lodash"],
method: EVAL_WORKER_SYNC_ACTION.UNINSTALL_LIBRARY,
});
expect(res).toEqual({ success: true });
expect(self.lodash).toBeUndefined();
});
it("Test flatten of ESM module", () => {
/** ESM with default and named exports */
const library = {
default: {
method: "Hello",
},
method: "Hello",
};
const flatLibrary1 = flattenModule(library);
expect(flatLibrary1).toEqual({
method: "Hello",
});
expect(Object.getPrototypeOf(flatLibrary1)).toEqual({
method: "Hello",
});
/** ESM with named exports only */
const library2 = {
method: "Hello",
};
const flatLibrary2 = flattenModule(library2);
expect(flatLibrary2).toEqual({
method: "Hello",
});
/** ESM with default export only */
const library3 = {
default: {
method: "Hello",
},
};
const flatLibrary3 = flattenModule(library3);
expect(flatLibrary3).toEqual({
method: "Hello",
});
});
});
|
2,516 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/common | petrpan-code/appsmithorg/appsmith/app/client/src/workers/common/DataTreeEvaluator/test.ts | import DataTreeEvaluator from ".";
import { unEvalTree } from "./mockData/mockUnEvalTree";
import { configTree } from "./mockData/mockConfigTree";
import type { DataTree, ConfigTree } from "entities/DataTree/dataTreeTypes";
import type { DataTreeDiff } from "@appsmith/workers/Evaluation/evaluationUtils";
import {
arrayAccessorCyclicDependency,
arrayAccessorCyclicDependencyConfig,
} from "./mockData/ArrayAccessorTree";
import {
nestedArrayAccessorCyclicDependency,
nestedArrayAccessorCyclicDependencyConfig,
} from "./mockData/NestedArrayAccessorTree";
import { updateDependencyMap } from "workers/common/DependencyMap";
import { replaceThisDotParams } from "./utils";
import { isDataField } from "./utils";
import widgets from "widgets";
import type { WidgetConfiguration } from "WidgetProvider/constants";
import type { WidgetEntity } from "@appsmith/entities/DataTree/types";
const widgetConfigMap: Record<
string,
{
defaultProperties: WidgetConfiguration["properties"]["default"];
derivedProperties: WidgetConfiguration["properties"]["derived"];
metaProperties: WidgetConfiguration["properties"]["meta"];
}
> = {};
widgets.map((widget) => {
if (widget.type) {
widgetConfigMap[widget.type] = {
defaultProperties: widget.getDefaultPropertiesMap(),
derivedProperties: widget.getDerivedPropertiesMap(),
metaProperties: widget.getMetaPropertiesMap(),
};
}
});
const dataTreeEvaluator = new DataTreeEvaluator(widgetConfigMap);
describe("DataTreeEvaluator", () => {
describe("evaluateActionBindings", () => {
it("handles this.params.property", () => {
const result = dataTreeEvaluator.evaluateActionBindings(
[
"(function() { return this.params.property })()",
"(() => { return this.params.property })()",
'this.params.property || "default value"',
'this.params.property1 || "default value"',
],
{
property: "my value",
},
);
expect(result).toStrictEqual([
"my value",
"my value",
"my value",
"default value",
]);
});
it("handles this?.params.property", () => {
const result = dataTreeEvaluator.evaluateActionBindings(
[
"(() => { return this?.params.property })()",
"(function() { return this?.params.property })()",
'this?.params.property || "default value"',
'this?.params.property1 || "default value"',
],
{
property: "my value",
},
);
expect(result).toStrictEqual([
"my value",
"my value",
"my value",
"default value",
]);
});
it("handles this?.params?.property", () => {
const result = dataTreeEvaluator.evaluateActionBindings(
[
"(() => { return this?.params?.property })()",
"(function() { return this?.params?.property })()",
'this?.params?.property || "default value"',
'this?.params?.property1 || "default value"',
],
{
property: "my value",
},
);
expect(result).toStrictEqual([
"my value",
"my value",
"my value",
"default value",
]);
});
it("handles executionParams.property", () => {
const result = dataTreeEvaluator.evaluateActionBindings(
[
"(function() { return executionParams.property })()",
"(() => { return executionParams.property })()",
'executionParams.property || "default value"',
'executionParams.property1 || "default value"',
],
{
property: "my value",
},
);
expect(result).toStrictEqual([
"my value",
"my value",
"my value",
"default value",
]);
});
it("handles executionParams?.property", () => {
const result = dataTreeEvaluator.evaluateActionBindings(
[
"(function() { return executionParams?.property })()",
"(() => { return executionParams?.property })()",
'executionParams?.property || "default value"',
'executionParams?.property1 || "default value"',
],
{
property: "my value",
},
);
expect(result).toStrictEqual([
"my value",
"my value",
"my value",
"default value",
]);
});
});
describe("test updateDependencyMap", () => {
beforeEach(() => {
dataTreeEvaluator.setupFirstTree(
unEvalTree as unknown as DataTree,
configTree as unknown as ConfigTree,
);
dataTreeEvaluator.evalAndValidateFirstTree();
});
it("initial dependencyMap computation", () => {
const { evalOrder, unEvalUpdates } = dataTreeEvaluator.setupUpdateTree(
unEvalTree as unknown as DataTree,
configTree as unknown as ConfigTree,
);
dataTreeEvaluator.evalAndValidateSubTree(
evalOrder,
configTree as unknown as ConfigTree,
unEvalUpdates,
);
expect(dataTreeEvaluator.dependencies).toStrictEqual({
"Button2.text": ["Button1.text"],
Button2: ["Button2.text"],
Button1: ["Button1.text"],
});
});
it(`When empty binding is modified from {{Button1.text}} to {{""}}`, () => {
const translatedDiffs = [
{
payload: {
propertyPath: "Button2.text",
value: '{{""}}',
},
event: "EDIT",
},
];
const button2 = dataTreeEvaluator.oldUnEvalTree.Button2 as WidgetEntity;
const newUnevalTree = {
...dataTreeEvaluator.oldUnEvalTree,
Button2: {
...button2,
text: '{{""}}',
},
};
const { dependencies } = updateDependencyMap({
configTree: configTree as unknown as ConfigTree,
dataTreeEvalRef: dataTreeEvaluator,
translatedDiffs: translatedDiffs as Array<DataTreeDiff>,
unEvalDataTree: newUnevalTree,
});
expect(dependencies).toStrictEqual({
"Button2.text": [],
Button2: ["Button2.text"],
Button1: ["Button1.text"],
});
});
it(`When binding is removed`, () => {
const translatedDiffs = [
{
payload: {
propertyPath: "Button2.text",
value: "abc",
},
event: "EDIT",
},
];
const button2 = dataTreeEvaluator.oldUnEvalTree.Button2 as WidgetEntity;
const newUnevalTree = {
...dataTreeEvaluator.oldUnEvalTree,
Button2: {
...button2,
text: "abc",
},
};
const { dependencies } = updateDependencyMap({
dataTreeEvalRef: dataTreeEvaluator,
translatedDiffs: translatedDiffs as Array<DataTreeDiff>,
unEvalDataTree: newUnevalTree,
configTree: configTree as unknown as ConfigTree,
});
expect(dependencies).toStrictEqual({
Button2: ["Button2.text"],
Button1: ["Button1.text"],
"Button2.text": [],
});
});
});
describe("array accessor dependency handling", () => {
const dataTreeEvaluator = new DataTreeEvaluator(widgetConfigMap);
beforeEach(() => {
dataTreeEvaluator.setupFirstTree(
nestedArrayAccessorCyclicDependency.initUnEvalTree,
nestedArrayAccessorCyclicDependencyConfig.initConfigTree,
);
dataTreeEvaluator.evalAndValidateFirstTree();
});
describe("array of objects", () => {
// when Text1.text has a binding Api1.data[2].id
it("on consequent API failures", () => {
// cyclic dependency case
for (let i = 0; i < 2; i++) {
// success: response -> [{...}, {...}, {...}]
const { evalOrder, unEvalUpdates } =
dataTreeEvaluator.setupUpdateTree(
arrayAccessorCyclicDependency.apiSuccessUnEvalTree,
arrayAccessorCyclicDependencyConfig.apiSuccessConfigTree,
);
dataTreeEvaluator.evalAndValidateSubTree(
evalOrder,
arrayAccessorCyclicDependencyConfig.apiSuccessConfigTree,
unEvalUpdates,
);
expect(dataTreeEvaluator.dependencies["Api1"]).toStrictEqual([
"Api1.data",
]);
expect(dataTreeEvaluator.dependencies["Api1.data"]).toStrictEqual([
"Api1.data[2]",
]);
expect(dataTreeEvaluator.dependencies["Api1.data[2]"]).toStrictEqual([
"Api1.data[2].id",
]);
expect(dataTreeEvaluator.dependencies["Text1.text"]).toStrictEqual([
"Api1.data[2].id",
]);
// failure: response -> {}
const { evalOrder: order, unEvalUpdates: unEvalUpdates2 } =
dataTreeEvaluator.setupUpdateTree(
arrayAccessorCyclicDependency.apiFailureUnEvalTree,
arrayAccessorCyclicDependencyConfig.apiFailureConfigTree,
);
dataTreeEvaluator.evalAndValidateSubTree(
order,
arrayAccessorCyclicDependencyConfig.apiFailureConfigTree,
unEvalUpdates2,
);
expect(dataTreeEvaluator.dependencies["Api1"]).toStrictEqual([
"Api1.data",
]);
expect(dataTreeEvaluator.dependencies["Api1.data"]).toStrictEqual([]);
expect(dataTreeEvaluator.dependencies["Api1.data[2]"]).toStrictEqual(
undefined,
);
expect(dataTreeEvaluator.dependencies["Text1.text"]).toStrictEqual(
[],
);
}
});
// when Text1.text has a binding Api1.data[2].id
it("on API response array length change", () => {
// success: response -> [{...}, {...}, {...}]
const { evalOrder: order1, unEvalUpdates } =
dataTreeEvaluator.setupUpdateTree(
arrayAccessorCyclicDependency.apiSuccessUnEvalTree,
arrayAccessorCyclicDependencyConfig.apiSuccessConfigTree,
);
dataTreeEvaluator.evalAndValidateSubTree(
order1,
arrayAccessorCyclicDependencyConfig.apiSuccessConfigTree,
unEvalUpdates,
);
// success: response -> [{...}, {...}]
const { evalOrder: order2, unEvalUpdates: unEvalUpdates2 } =
dataTreeEvaluator.setupUpdateTree(
arrayAccessorCyclicDependency.apiSuccessUnEvalTree2,
arrayAccessorCyclicDependencyConfig.apiSuccessConfigTree2,
);
dataTreeEvaluator.evalAndValidateSubTree(
order2,
arrayAccessorCyclicDependencyConfig.apiSuccessConfigTree2,
unEvalUpdates2,
);
expect(dataTreeEvaluator.dependencies["Api1"]).toStrictEqual([
"Api1.data",
]);
expect(dataTreeEvaluator.dependencies["Api1.data"]).toStrictEqual([]);
expect(dataTreeEvaluator.dependencies["Api1.data[2]"]).toStrictEqual(
undefined,
);
expect(dataTreeEvaluator.dependencies["Text1.text"]).toStrictEqual([]);
});
});
describe("nested array of objects", () => {
// when Text1.text has a binding Api1.data[2][2].id
it("on consequent API failures", () => {
// cyclic dependency case
for (let i = 0; i < 2; i++) {
// success: response -> [ [{...}, {...}, {...}], [{...}, {...}, {...}], [{...}, {...}, {...}] ]
const { evalOrder: order, unEvalUpdates } =
dataTreeEvaluator.setupUpdateTree(
nestedArrayAccessorCyclicDependency.apiSuccessUnEvalTree,
nestedArrayAccessorCyclicDependencyConfig.apiSuccessConfigTree,
);
dataTreeEvaluator.evalAndValidateSubTree(
order,
nestedArrayAccessorCyclicDependencyConfig.apiSuccessConfigTree,
unEvalUpdates,
);
expect(dataTreeEvaluator.dependencies["Api1"]).toStrictEqual([
"Api1.data",
]);
expect(dataTreeEvaluator.dependencies["Api1.data"]).toStrictEqual([
"Api1.data[2]",
]);
expect(dataTreeEvaluator.dependencies["Api1.data[2]"]).toStrictEqual([
"Api1.data[2][2]",
]);
expect(
dataTreeEvaluator.dependencies["Api1.data[2][2]"],
).toStrictEqual(["Api1.data[2][2].id"]);
expect(dataTreeEvaluator.dependencies["Text1.text"]).toStrictEqual([
"Api1.data[2][2].id",
]);
// failure: response -> {}
const { evalOrder: order1, unEvalUpdates: unEvalUpdates2 } =
dataTreeEvaluator.setupUpdateTree(
nestedArrayAccessorCyclicDependency.apiFailureUnEvalTree,
nestedArrayAccessorCyclicDependencyConfig.apiFailureConfigTree,
);
dataTreeEvaluator.evalAndValidateSubTree(
order1,
nestedArrayAccessorCyclicDependencyConfig.apiFailureConfigTree,
unEvalUpdates2,
);
expect(dataTreeEvaluator.dependencies["Api1"]).toStrictEqual([
"Api1.data",
]);
expect(dataTreeEvaluator.dependencies["Api1.data"]).toStrictEqual([]);
expect(dataTreeEvaluator.dependencies["Api1.data[2]"]).toStrictEqual(
undefined,
);
expect(
dataTreeEvaluator.dependencies["Api1.data[2][2]"],
).toStrictEqual(undefined);
expect(dataTreeEvaluator.dependencies["Text1.text"]).toStrictEqual(
[],
);
}
});
// when Text1.text has a binding Api1.data[2][2].id
it("on API response array length change", () => {
// success: response -> [ [{...}, {...}, {...}], [{...}, {...}, {...}], [{...}, {...}, {...}] ]
const { evalOrder: order, unEvalUpdates } =
dataTreeEvaluator.setupUpdateTree(
nestedArrayAccessorCyclicDependency.apiSuccessUnEvalTree,
nestedArrayAccessorCyclicDependencyConfig.apiSuccessConfigTree,
);
dataTreeEvaluator.evalAndValidateSubTree(
order,
nestedArrayAccessorCyclicDependencyConfig.apiSuccessConfigTree,
unEvalUpdates,
);
// success: response -> [ [{...}, {...}, {...}], [{...}, {...}, {...}] ]
const { evalOrder: order1, unEvalUpdates: unEvalUpdates2 } =
dataTreeEvaluator.setupUpdateTree(
nestedArrayAccessorCyclicDependency.apiSuccessUnEvalTree2,
nestedArrayAccessorCyclicDependencyConfig.apiSuccessConfigTree2,
);
dataTreeEvaluator.evalAndValidateSubTree(
order1,
nestedArrayAccessorCyclicDependencyConfig.apiSuccessConfigTree2,
unEvalUpdates2,
);
expect(dataTreeEvaluator.dependencies["Api1"]).toStrictEqual([
"Api1.data",
]);
expect(dataTreeEvaluator.dependencies["Api1.data"]).toStrictEqual([]);
expect(dataTreeEvaluator.dependencies["Api1.data[2]"]).toStrictEqual(
undefined,
);
expect(dataTreeEvaluator.dependencies["Api1.data[2][2]"]).toStrictEqual(
undefined,
);
expect(dataTreeEvaluator.dependencies["Text1.text"]).toStrictEqual([]);
});
// when Text1.text has a binding Api1.data[2][2].id
it("on API response nested array length change", () => {
// success: response -> [ [{...}, {...}, {...}], [{...}, {...}, {...}], [{...}, {...}, {...}] ]
const { evalOrder: order, unEvalUpdates } =
dataTreeEvaluator.setupUpdateTree(
nestedArrayAccessorCyclicDependency.apiSuccessUnEvalTree,
nestedArrayAccessorCyclicDependencyConfig.apiSuccessConfigTree,
);
dataTreeEvaluator.evalAndValidateSubTree(
order,
nestedArrayAccessorCyclicDependencyConfig.apiSuccessConfigTree,
unEvalUpdates,
);
// success: response -> [ [{...}, {...}, {...}], [{...}, {...}, {...}], [] ]
const { evalOrder: order1, unEvalUpdates: unEvalUpdates2 } =
dataTreeEvaluator.setupUpdateTree(
nestedArrayAccessorCyclicDependency.apiSuccessUnEvalTree3,
nestedArrayAccessorCyclicDependencyConfig.apiSuccessConfigTree3,
);
dataTreeEvaluator.evalAndValidateSubTree(
order1,
nestedArrayAccessorCyclicDependencyConfig.apiSuccessConfigTree3,
unEvalUpdates2,
);
expect(dataTreeEvaluator.dependencies["Api1"]).toStrictEqual([
"Api1.data",
]);
expect(dataTreeEvaluator.dependencies["Api1.data"]).toStrictEqual([
"Api1.data[2]",
]);
expect(dataTreeEvaluator.dependencies["Api1.data[2]"]).toStrictEqual(
[],
);
expect(dataTreeEvaluator.dependencies["Api1.data[2][2]"]).toStrictEqual(
undefined,
);
expect(dataTreeEvaluator.dependencies["Text1.text"]).toStrictEqual([]);
});
});
});
});
describe("replaceThisDotParams", () => {
describe("no optional chaining this.params", () => {
it("1. IIFEE with function keyword", () => {
const code = "{{ (function() { return this.params.condition })() }}";
const replaced = replaceThisDotParams(code);
expect(replaced).toBe(
"{{ (function() { return $params.condition })() }}",
);
});
it("2. IIFEE with arrow function", () => {
const code = "{{ (() => { return this.params.condition })() }}";
const replaced = replaceThisDotParams(code);
expect(replaced).toBe("{{ (() => { return $params.condition })() }}");
});
it("3. normal binding", () => {
const code = "{{ this.params.condition }}";
const replaced = replaceThisDotParams(code);
expect(replaced).toBe("{{ $params.condition }}");
});
});
describe("optional chaining this?.params", () => {
it("1. IIFEE with function keyword", () => {
const code = "{{ (function() { return this?.params.condition })() }}";
const replaced = replaceThisDotParams(code);
expect(replaced).toBe(
"{{ (function() { return $params.condition })() }}",
);
});
it("2. IIFEE with arrow function", () => {
const code = "{{ (() => { return this?.params.condition })() }}";
const replaced = replaceThisDotParams(code);
expect(replaced).toBe("{{ (() => { return $params.condition })() }}");
});
it("3. normal binding", () => {
const code = "{{ this?.params.condition }}";
const replaced = replaceThisDotParams(code);
expect(replaced).toBe("{{ $params.condition }}");
});
});
describe("optional chaining this?.params?.condition", () => {
it("1. IIFEE with function keyword", () => {
const code = "{{ (function() { return this?.params?.condition })() }}";
const replaced = replaceThisDotParams(code);
expect(replaced).toBe(
"{{ (function() { return $params?.condition })() }}",
);
});
it("2. IIFEE with arrow function", () => {
const code = "{{ (() => { return this?.params?.condition })() }}";
const replaced = replaceThisDotParams(code);
expect(replaced).toBe("{{ (() => { return $params?.condition })() }}");
});
it("3. normal binding", () => {
const code = "{{ this?.params?.condition }}";
const replaced = replaceThisDotParams(code);
expect(replaced).toBe("{{ $params?.condition }}");
});
});
});
describe("isDataField", () => {
const configTree = {
JSObject1: {
actionId: "642d384a630f4634e27a67ff",
meta: {
myFun2: {
arguments: [],
confirmBeforeExecute: false,
},
myFun1: {
arguments: [],
confirmBeforeExecute: false,
},
},
name: "JSObject1",
pluginType: "JS",
ENTITY_TYPE: "JSACTION",
bindingPaths: {
body: "SMART_SUBSTITUTE",
superbaseClient: "SMART_SUBSTITUTE",
myVar2: "SMART_SUBSTITUTE",
myFun2: "SMART_SUBSTITUTE",
myFun1: "SMART_SUBSTITUTE",
},
reactivePaths: {
body: "SMART_SUBSTITUTE",
superbaseClient: "SMART_SUBSTITUTE",
myVar2: "SMART_SUBSTITUTE",
myFun2: "SMART_SUBSTITUTE",
myFun1: "SMART_SUBSTITUTE",
},
dynamicBindingPathList: [
{
key: "body",
},
{
key: "superbaseClient",
},
{
key: "myVar2",
},
{
key: "myFun2",
},
{
key: "myFun1",
},
],
variables: ["superbaseClient", "myVar2"],
dependencyMap: {
body: ["myFun2", "myFun1"],
},
},
JSObject2: {
actionId: "644242aeadc0936a9b0e71cc",
meta: {
myFun2: {
arguments: [],
confirmBeforeExecute: false,
},
myFun1: {
arguments: [],
confirmBeforeExecute: false,
},
},
name: "JSObject2",
pluginType: "JS",
ENTITY_TYPE: "JSACTION",
bindingPaths: {
body: "SMART_SUBSTITUTE",
supabaseClient: "SMART_SUBSTITUTE",
myVar2: "SMART_SUBSTITUTE",
myFun2: "SMART_SUBSTITUTE",
myFun1: "SMART_SUBSTITUTE",
},
reactivePaths: {
body: "SMART_SUBSTITUTE",
supabaseClient: "SMART_SUBSTITUTE",
myVar2: "SMART_SUBSTITUTE",
myFun2: "SMART_SUBSTITUTE",
myFun1: "SMART_SUBSTITUTE",
},
dynamicBindingPathList: [
{
key: "body",
},
{
key: "supabaseClient",
},
{
key: "myVar2",
},
{
key: "myFun2",
},
{
key: "myFun1",
},
],
variables: ["supabaseClient", "myVar2"],
dependencyMap: {
body: ["myFun2", "myFun1"],
},
},
MainContainer: {
defaultProps: {},
defaultMetaProps: [],
dynamicBindingPathList: [],
logBlackList: {},
bindingPaths: {},
reactivePaths: {},
triggerPaths: {},
validationPaths: {},
ENTITY_TYPE: "WIDGET",
privateWidgets: {},
propertyOverrideDependency: {},
overridingPropertyPaths: {},
type: "CANVAS_WIDGET",
dynamicTriggerPathList: [],
isMetaPropDirty: false,
widgetId: "0",
},
Button1: {
defaultProps: {},
defaultMetaProps: ["recaptchaToken"],
dynamicBindingPathList: [
{
key: "buttonColor",
},
{
key: "borderRadius",
},
{
key: "text",
},
],
logBlackList: {},
bindingPaths: {
text: "TEMPLATE",
tooltip: "TEMPLATE",
isVisible: "TEMPLATE",
isDisabled: "TEMPLATE",
animateLoading: "TEMPLATE",
googleRecaptchaKey: "TEMPLATE",
recaptchaType: "TEMPLATE",
disabledWhenInvalid: "TEMPLATE",
resetFormOnClick: "TEMPLATE",
buttonVariant: "TEMPLATE",
iconName: "TEMPLATE",
placement: "TEMPLATE",
buttonColor: "TEMPLATE",
borderRadius: "TEMPLATE",
boxShadow: "TEMPLATE",
},
reactivePaths: {
recaptchaToken: "TEMPLATE",
buttonColor: "TEMPLATE",
borderRadius: "TEMPLATE",
text: "TEMPLATE",
tooltip: "TEMPLATE",
isVisible: "TEMPLATE",
isDisabled: "TEMPLATE",
animateLoading: "TEMPLATE",
googleRecaptchaKey: "TEMPLATE",
recaptchaType: "TEMPLATE",
disabledWhenInvalid: "TEMPLATE",
resetFormOnClick: "TEMPLATE",
buttonVariant: "TEMPLATE",
iconName: "TEMPLATE",
placement: "TEMPLATE",
boxShadow: "TEMPLATE",
},
triggerPaths: {
onClick: true,
},
validationPaths: {
text: {
type: "TEXT",
},
tooltip: {
type: "TEXT",
},
isVisible: {
type: "BOOLEAN",
},
isDisabled: {
type: "BOOLEAN",
},
animateLoading: {
type: "BOOLEAN",
},
googleRecaptchaKey: {
type: "TEXT",
},
recaptchaType: {
type: "TEXT",
params: {
allowedValues: ["V3", "V2"],
default: "V3",
},
},
disabledWhenInvalid: {
type: "BOOLEAN",
},
resetFormOnClick: {
type: "BOOLEAN",
},
buttonVariant: {
type: "TEXT",
params: {
allowedValues: ["PRIMARY", "SECONDARY", "TERTIARY"],
default: "PRIMARY",
},
},
iconName: {
type: "TEXT",
},
placement: {
type: "TEXT",
params: {
allowedValues: ["START", "BETWEEN", "CENTER"],
default: "CENTER",
},
},
buttonColor: {
type: "TEXT",
},
borderRadius: {
type: "TEXT",
},
boxShadow: {
type: "TEXT",
},
},
ENTITY_TYPE: "WIDGET",
privateWidgets: {},
propertyOverrideDependency: {},
overridingPropertyPaths: {},
type: "BUTTON_WIDGET",
dynamicTriggerPathList: [],
isMetaPropDirty: false,
widgetId: "19ih8rt2eo",
},
Button2: {
defaultProps: {},
defaultMetaProps: ["recaptchaToken"],
dynamicBindingPathList: [
{
key: "buttonColor",
},
{
key: "borderRadius",
},
],
logBlackList: {},
bindingPaths: {
text: "TEMPLATE",
tooltip: "TEMPLATE",
isVisible: "TEMPLATE",
isDisabled: "TEMPLATE",
animateLoading: "TEMPLATE",
googleRecaptchaKey: "TEMPLATE",
recaptchaType: "TEMPLATE",
disabledWhenInvalid: "TEMPLATE",
resetFormOnClick: "TEMPLATE",
buttonVariant: "TEMPLATE",
iconName: "TEMPLATE",
placement: "TEMPLATE",
buttonColor: "TEMPLATE",
borderRadius: "TEMPLATE",
boxShadow: "TEMPLATE",
},
reactivePaths: {
recaptchaToken: "TEMPLATE",
buttonColor: "TEMPLATE",
borderRadius: "TEMPLATE",
text: "TEMPLATE",
tooltip: "TEMPLATE",
isVisible: "TEMPLATE",
isDisabled: "TEMPLATE",
animateLoading: "TEMPLATE",
googleRecaptchaKey: "TEMPLATE",
recaptchaType: "TEMPLATE",
disabledWhenInvalid: "TEMPLATE",
resetFormOnClick: "TEMPLATE",
buttonVariant: "TEMPLATE",
iconName: "TEMPLATE",
placement: "TEMPLATE",
boxShadow: "TEMPLATE",
},
triggerPaths: {
onClick: true,
},
validationPaths: {
text: {
type: "TEXT",
},
tooltip: {
type: "TEXT",
},
isVisible: {
type: "BOOLEAN",
},
isDisabled: {
type: "BOOLEAN",
},
animateLoading: {
type: "BOOLEAN",
},
googleRecaptchaKey: {
type: "TEXT",
},
recaptchaType: {
type: "TEXT",
params: {
allowedValues: ["V3", "V2"],
default: "V3",
},
},
disabledWhenInvalid: {
type: "BOOLEAN",
},
resetFormOnClick: {
type: "BOOLEAN",
},
buttonVariant: {
type: "TEXT",
params: {
allowedValues: ["PRIMARY", "SECONDARY", "TERTIARY"],
default: "PRIMARY",
},
},
iconName: {
type: "TEXT",
},
placement: {
type: "TEXT",
params: {
allowedValues: ["START", "BETWEEN", "CENTER"],
default: "CENTER",
},
},
buttonColor: {
type: "TEXT",
},
borderRadius: {
type: "TEXT",
},
boxShadow: {
type: "TEXT",
},
},
ENTITY_TYPE: "WIDGET",
privateWidgets: {},
propertyOverrideDependency: {},
overridingPropertyPaths: {},
type: "BUTTON_WIDGET",
dynamicPropertyPathList: [
{
key: "onClick",
},
],
dynamicTriggerPathList: [
{
key: "onClick",
},
],
isMetaPropDirty: false,
widgetId: "vss3w1eecd",
},
Button3: {
defaultProps: {},
defaultMetaProps: ["recaptchaToken"],
dynamicBindingPathList: [
{
key: "buttonColor",
},
{
key: "borderRadius",
},
],
logBlackList: {},
bindingPaths: {
text: "TEMPLATE",
tooltip: "TEMPLATE",
isVisible: "TEMPLATE",
isDisabled: "TEMPLATE",
animateLoading: "TEMPLATE",
googleRecaptchaKey: "TEMPLATE",
recaptchaType: "TEMPLATE",
disabledWhenInvalid: "TEMPLATE",
resetFormOnClick: "TEMPLATE",
buttonVariant: "TEMPLATE",
iconName: "TEMPLATE",
placement: "TEMPLATE",
buttonColor: "TEMPLATE",
borderRadius: "TEMPLATE",
boxShadow: "TEMPLATE",
},
reactivePaths: {
recaptchaToken: "TEMPLATE",
buttonColor: "TEMPLATE",
borderRadius: "TEMPLATE",
text: "TEMPLATE",
tooltip: "TEMPLATE",
isVisible: "TEMPLATE",
isDisabled: "TEMPLATE",
animateLoading: "TEMPLATE",
googleRecaptchaKey: "TEMPLATE",
recaptchaType: "TEMPLATE",
disabledWhenInvalid: "TEMPLATE",
resetFormOnClick: "TEMPLATE",
buttonVariant: "TEMPLATE",
iconName: "TEMPLATE",
placement: "TEMPLATE",
boxShadow: "TEMPLATE",
},
triggerPaths: {
onClick: true,
},
validationPaths: {
text: {
type: "TEXT",
},
tooltip: {
type: "TEXT",
},
isVisible: {
type: "BOOLEAN",
},
isDisabled: {
type: "BOOLEAN",
},
animateLoading: {
type: "BOOLEAN",
},
googleRecaptchaKey: {
type: "TEXT",
},
recaptchaType: {
type: "TEXT",
params: {
allowedValues: ["V3", "V2"],
default: "V3",
},
},
disabledWhenInvalid: {
type: "BOOLEAN",
},
resetFormOnClick: {
type: "BOOLEAN",
},
buttonVariant: {
type: "TEXT",
params: {
allowedValues: ["PRIMARY", "SECONDARY", "TERTIARY"],
default: "PRIMARY",
},
},
iconName: {
type: "TEXT",
},
placement: {
type: "TEXT",
params: {
allowedValues: ["START", "BETWEEN", "CENTER"],
default: "CENTER",
},
},
buttonColor: {
type: "TEXT",
},
borderRadius: {
type: "TEXT",
},
boxShadow: {
type: "TEXT",
},
},
ENTITY_TYPE: "WIDGET",
privateWidgets: {},
propertyOverrideDependency: {},
overridingPropertyPaths: {},
type: "BUTTON_WIDGET",
dynamicPropertyPathList: [
{
key: "onClick",
},
],
dynamicTriggerPathList: [
{
key: "onClick",
},
],
isMetaPropDirty: false,
widgetId: "pzom2ufg3b",
},
} as ConfigTree;
it("doesn't crash when config tree is empty", () => {
const isADataField = isDataField("appsmith.store", {});
expect(isADataField).toBe(false);
});
it("works correctly", function () {
const testCases = [
{
fullPath: "Button1.text",
isDataField: true,
},
{
fullPath: "appsmith.store",
isDataField: false,
},
{
fullPath: "JSObject2.body",
isDataField: false,
},
];
for (const testCase of testCases) {
const isADataField = isDataField(testCase.fullPath, configTree);
expect(isADataField).toBe(testCase.isDataField);
}
});
});
|
2,524 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/common | petrpan-code/appsmithorg/appsmith/app/client/src/workers/common/DependencyMap/test.ts | import ButtonWidget from "widgets/ButtonWidget";
import SelectWidget from "widgets/SelectWidget";
import type {
WidgetEntity,
DataTreeEntityConfig,
} from "@appsmith/entities/DataTree/types";
import { getEntityPathDependencies } from "./utils/getEntityDependencies";
import type BaseWidget from "widgets/BaseWidget";
const widgetConfigMap = {};
[ButtonWidget, SelectWidget].forEach((widget: typeof BaseWidget) => {
if (widget.type) {
// @ts-expect-error: Types are not available
widgetConfigMap[widget.type] = {
defaultProperties: widget.getDefaultPropertiesMap(),
derivedProperties: widget.getDerivedPropertiesMap(),
metaProperties: widget.getMetaPropertiesMap(),
};
}
});
describe("DependencyMap utils", function () {
test("getEntityPathDependencies", () => {
const entity = {
ENTITY_TYPE: "WIDGET",
isVisible: true,
animateLoading: true,
text: "Submit",
buttonVariant: "PRIMARY",
placement: "CENTER",
widgetName: "Button1",
isDisabled: false,
isDefaultClickDisabled: true,
disabledWhenInvalid: false,
resetFormOnClick: false,
recaptchaType: "V3",
key: "7rt30wsb1w",
widgetId: "hmqejzs6wz",
buttonColor: "{{appsmith.theme.colors.primaryColor}}",
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
boxShadow: "none",
isLoading: false,
parentColumnSpace: 2.9375,
parentRowSpace: 10,
leftColumn: 20,
rightColumn: 36,
topRow: 21,
bottomRow: 25,
onClick: "",
meta: {},
type: "BUTTON_WIDGET",
} as unknown as WidgetEntity;
const entityConfig = {
widgetId: "hmqejzs6wz",
ENTITY_TYPE: "WIDGET",
type: "BUTTON_WIDGET",
defaultProps: {},
defaultMetaProps: ["recaptchaToken"],
dynamicBindingPathList: [
{
key: "buttonColor",
},
{
key: "borderRadius",
},
],
logBlackList: {},
bindingPaths: {
text: "TEMPLATE",
tooltip: "TEMPLATE",
isVisible: "TEMPLATE",
isDisabled: "TEMPLATE",
animateLoading: "TEMPLATE",
googleRecaptchaKey: "TEMPLATE",
recaptchaType: "TEMPLATE",
disabledWhenInvalid: "TEMPLATE",
resetFormOnClick: "TEMPLATE",
buttonVariant: "TEMPLATE",
iconName: "TEMPLATE",
placement: "TEMPLATE",
buttonColor: "TEMPLATE",
borderRadius: "TEMPLATE",
boxShadow: "TEMPLATE",
},
reactivePaths: {
recaptchaToken: "TEMPLATE",
buttonColor: "TEMPLATE",
borderRadius: "TEMPLATE",
text: "TEMPLATE",
tooltip: "TEMPLATE",
isVisible: "TEMPLATE",
isDisabled: "TEMPLATE",
animateLoading: "TEMPLATE",
googleRecaptchaKey: "TEMPLATE",
recaptchaType: "TEMPLATE",
disabledWhenInvalid: "TEMPLATE",
resetFormOnClick: "TEMPLATE",
buttonVariant: "TEMPLATE",
iconName: "TEMPLATE",
placement: "TEMPLATE",
boxShadow: "TEMPLATE",
},
dynamicPropertyPathList: [
{
key: "onClick",
},
],
dynamicTriggerPathList: [
{
key: "onClick",
},
],
privateWidgets: {},
propertyOverrideDependency: {},
overridingPropertyPaths: {},
triggerPaths: {
onClick: true,
},
} as unknown as DataTreeEntityConfig;
const actualResult = getEntityPathDependencies(
entity,
entityConfig,
"Button1.onClick",
{},
);
expect([]).toStrictEqual(actualResult);
const entity2 = {
ENTITY_TYPE: "WIDGET",
isVisible: true,
animateLoading: true,
text: "Submit",
buttonVariant: "PRIMARY",
placement: "CENTER",
widgetName: "Button1",
isDisabled: false,
isDefaultClickDisabled: true,
disabledWhenInvalid: false,
resetFormOnClick: false,
recaptchaType: "V3",
key: "oucrqjoiv0",
widgetId: "35z8qp6hkj",
buttonColor: "{{appsmith.theme.colors.primaryColor}}",
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
boxShadow: "none",
isLoading: false,
parentColumnSpace: 2.9375,
parentRowSpace: 10,
leftColumn: 23,
rightColumn: 39,
topRow: 28,
bottomRow: 32,
googleRecaptchaKey: "{{JSObject.myVar1}}",
meta: {},
type: "BUTTON_WIDGET",
} as unknown as WidgetEntity;
const entityConfig2 = {
ENTITY_TYPE: "WIDGET",
widgetId: "35z8qp6hkj",
defaultProps: {},
defaultMetaProps: ["recaptchaToken"],
dynamicBindingPathList: [
{
key: "buttonColor",
},
{
key: "borderRadius",
},
{
key: "googleRecaptchaKey",
},
],
logBlackList: {},
bindingPaths: {
text: "TEMPLATE",
tooltip: "TEMPLATE",
isVisible: "TEMPLATE",
isDisabled: "TEMPLATE",
animateLoading: "TEMPLATE",
googleRecaptchaKey: "TEMPLATE",
recaptchaType: "TEMPLATE",
disabledWhenInvalid: "TEMPLATE",
resetFormOnClick: "TEMPLATE",
buttonVariant: "TEMPLATE",
iconName: "TEMPLATE",
placement: "TEMPLATE",
buttonColor: "TEMPLATE",
borderRadius: "TEMPLATE",
boxShadow: "TEMPLATE",
},
reactivePaths: {
recaptchaToken: "TEMPLATE",
buttonColor: "TEMPLATE",
borderRadius: "TEMPLATE",
googleRecaptchaKey: "TEMPLATE",
text: "TEMPLATE",
tooltip: "TEMPLATE",
isVisible: "TEMPLATE",
isDisabled: "TEMPLATE",
animateLoading: "TEMPLATE",
recaptchaType: "TEMPLATE",
disabledWhenInvalid: "TEMPLATE",
resetFormOnClick: "TEMPLATE",
buttonVariant: "TEMPLATE",
iconName: "TEMPLATE",
placement: "TEMPLATE",
boxShadow: "TEMPLATE",
},
triggerPaths: {
onClick: true,
},
validationPaths: {
text: {
type: "TEXT",
},
tooltip: {
type: "TEXT",
},
isVisible: {
type: "BOOLEAN",
},
isDisabled: {
type: "BOOLEAN",
},
animateLoading: {
type: "BOOLEAN",
},
googleRecaptchaKey: {
type: "TEXT",
},
recaptchaType: {
type: "TEXT",
params: {
allowedValues: ["V3", "V2"],
default: "V3",
},
},
disabledWhenInvalid: {
type: "BOOLEAN",
},
resetFormOnClick: {
type: "BOOLEAN",
},
buttonVariant: {
type: "TEXT",
params: {
allowedValues: ["PRIMARY", "SECONDARY", "TERTIARY"],
default: "PRIMARY",
},
},
iconName: {
type: "TEXT",
},
placement: {
type: "TEXT",
params: {
allowedValues: ["START", "BETWEEN", "CENTER"],
default: "CENTER",
},
},
buttonColor: {
type: "TEXT",
},
borderRadius: {
type: "TEXT",
},
boxShadow: {
type: "TEXT",
},
},
dynamicTriggerPathList: [],
type: "BUTTON_WIDGET",
privateWidgets: {},
propertyOverrideDependency: {},
overridingPropertyPaths: {},
} as unknown as DataTreeEntityConfig;
const result = getEntityPathDependencies(
entity2,
entityConfig2,
"Button1.googleRecaptchaKey",
{},
);
const expected = ["JSObject.myVar1"];
expect(expected).toStrictEqual(result);
});
});
|
2,531 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/workers/common/JSLibrary | petrpan-code/appsmithorg/appsmith/app/client/src/workers/common/JSLibrary/__tests__/ternDefinitionGenerator.test.ts | import { makeTernDefs } from "../ternDefinitionGenerator";
describe("Tests tern definition generator", () => {
const obj = {
var1: "myVar1",
var2: 2,
var3: true,
var4: null,
var5: undefined,
var6: { a: 1, b: 2 },
var7: () => {
return "there!";
},
var8: function () {
return "hey, ";
},
var9: new Date(),
};
const proto = {
sayHello() {
return "Hello";
},
};
it("Correctly determines tern def types based", () => {
const expected = {
var1: { "!type": "string" },
var2: { "!type": "number" },
var3: { "!type": "bool" },
var4: { "!type": "?" },
var5: { "!type": "?" },
var6: { a: { "!type": "number" }, b: { "!type": "number" } },
var7: { "!type": "fn()" },
};
const defs = makeTernDefs(obj);
expect(defs).toMatchObject(expected);
});
it("should look up the prototype chain on objects", () => {
Object.setPrototypeOf(obj, proto);
const expected = {
sayHello: { "!type": "fn()" },
};
const defs = makeTernDefs(proto);
expect(defs).toMatchObject(expected);
});
it("should look up the prototype property on functions", () => {
obj.var8.prototype = {
sayWorld() {
return "World";
},
};
const expected = {
var8: {
"!type": "fn()",
prototype: {
sayWorld: { "!type": "fn()" },
},
},
};
const defs = makeTernDefs(obj);
expect(defs).toMatchObject(expected);
});
});
|
4,624 | 0 | petrpan-code/trpc/trpc/examples/.experimental/next-app-dir | petrpan-code/trpc/trpc/examples/.experimental/next-app-dir/test/client.test.ts | import { expect, test } from '@playwright/test';
test.setTimeout(35e3);
//
// TODO: Activate client tests once we have the React Query setup working
test('client: refreshing the page should reuse the cached value', async ({
page,
}) => {
await page.goto('/client');
// await page.waitForSelector('text=hello from client');
// const nonce1 = await page.textContent('text=hello from client');
// await page.reload();
// const nonce2 = await page.textContent('text=hello from client');
// expect(nonce1).toBe(nonce2);
const nonce = await page.textContent('text=not implemented');
expect(nonce).toBe('not implemented');
});
// test('client: revalidating should load new content', async ({ page }) => {
// await page.goto('/client');
// await page.waitForSelector('text=hello from client');
// const nonce1 = await page.textContent('text=hello from client');
// await page.click('text=Revalidate');
// await page.waitForLoadState('networkidle');
// const nonce2 = await page.textContent('text=hello from client');
// expect(nonce1).not.toBe(nonce2);
// });
|
4,625 | 0 | petrpan-code/trpc/trpc/examples/.experimental/next-app-dir | petrpan-code/trpc/trpc/examples/.experimental/next-app-dir/test/server-cache.test.ts | import { expect, test } from '@playwright/test';
test.setTimeout(35e3);
// Initial page.reload is due to dev server having a more aggressive
// cache invalidation strategy.
test('server-cacheLink: refreshing the page should reuse the cached value', async ({
page,
}) => {
await page.goto('/rsc');
await page.reload();
await page.waitForSelector('text=hello i never hit an api endpoint');
const nonce1 = await page.textContent(
'text=hello i never hit an api endpoint',
);
await page.reload();
const nonce2 = await page.textContent(
'text=hello i never hit an api endpoint',
);
expect(nonce1).toBe(nonce2);
});
test('server-cacheLink: revalidating should load new content', async ({
page,
}) => {
await page.goto('/rsc');
await page.reload();
await page.waitForSelector('text=hello i never hit an api endpoint');
const nonce1 = await page.textContent(
'text=hello i never hit an api endpoint',
);
await page.click('text=Revalidate Cache 1');
await page.waitForLoadState('networkidle');
const nonce2 = await page.textContent(
'text=hello i never hit an api endpoint',
);
expect(nonce1).not.toBe(nonce2);
});
|
4,626 | 0 | petrpan-code/trpc/trpc/examples/.experimental/next-app-dir | petrpan-code/trpc/trpc/examples/.experimental/next-app-dir/test/server-http.test.ts | import { expect, test } from '@playwright/test';
test.setTimeout(35e3);
// Initial page.reload is due to dev server having a more aggressive
// cache invalidation strategy.
test('server-httpLink: refreshing the page should reuse the cached value', async ({
page,
}) => {
await page.goto('/rsc');
await page.reload();
await page.waitForSelector('text=hello from server');
const nonce1 = await page.textContent('text=hello from server1');
await page.reload();
const nonce2 = await page.textContent('text=hello from server1');
expect(nonce1).toBe(nonce2);
});
test('server-httpLink: revalidating should load new content', async ({
page,
}) => {
await page.goto('/rsc');
await page.reload();
await page.waitForSelector('text=hello from server');
const nonce1 = await page.textContent('text=hello from server1');
await page.click('text=Revalidate HTTP 1');
await page.waitForLoadState('networkidle');
const nonce2 = await page.textContent('text=hello from server1');
expect(nonce1).not.toBe(nonce2);
});
test('server-httpLink: requests are properly separated in the cache', async ({
page,
}) => {
await page.goto('/rsc');
await page.reload();
await page.waitForSelector('text=hello from server1');
await page.waitForSelector('text=hello from server2');
await page.reload();
await page.waitForLoadState('networkidle');
// Both should still return separately.
// Regression of https://github.com/trpc/trpc/issues/4622
// httpLink was not affected by this bug but checking just in case
await page.waitForSelector('text=hello from server1');
await page.waitForSelector('text=hello from server2');
});
|
4,657 | 0 | petrpan-code/trpc/trpc/examples/.interop/next-prisma-starter | petrpan-code/trpc/trpc/examples/.interop/next-prisma-starter/playwright/smoke.test.ts | import { test, expect } from '@playwright/test';
test.setTimeout(35e3);
test('go to /', async ({ page }) => {
await page.goto('/');
await page.waitForSelector(`text=Starter`);
});
test('test 404', async ({ page }) => {
const res = await page.goto('/post/not-found');
expect(res?.status()).toBe(404);
});
test('add a post', async ({ page, browser }) => {
const nonce = `${Math.random()}`;
await page.goto('/');
await page.fill(`[name=title]`, nonce);
await page.fill(`[name=text]`, nonce);
await page.click(`form [type=submit]`);
await page.waitForLoadState('networkidle');
await page.reload();
expect(await page.content()).toContain(nonce);
const ssrContext = await browser.newContext({
javaScriptEnabled: false,
});
const ssrPage = await ssrContext.newPage();
await ssrPage.goto('/');
expect(await ssrPage.content()).toContain(nonce);
});
test('server-side rendering test', async ({ page, browser }) => {
// add a post
const nonce = `${Math.random()}`;
await page.goto('/');
await page.fill(`[name=title]`, nonce);
await page.fill(`[name=text]`, nonce);
await page.click(`form [type=submit]`);
await page.waitForLoadState('networkidle');
// load the page without js
const ssrContext = await browser.newContext({
javaScriptEnabled: false,
});
const ssrPage = await ssrContext.newPage();
await ssrPage.goto('/');
expect(await ssrPage.content()).toContain(nonce);
});
|
4,674 | 0 | petrpan-code/trpc/trpc/examples/.interop/next-prisma-starter/src/server | petrpan-code/trpc/trpc/examples/.interop/next-prisma-starter/src/server/routers/post.test.ts | /**
* Integration test example for the `post` router
*/
import { createContextInner } from '../context';
import { appRouter } from './_app';
import { inferMutationInput } from '~/utils/trpc';
test('add and get post', async () => {
const ctx = await createContextInner({});
const caller = appRouter.createCaller(ctx);
const input: inferMutationInput<'post.add'> = {
text: 'hello test',
title: 'hello test',
};
const post = await caller.mutation('post.add', input);
const byId = await caller.query('post.byId', {
id: post.id,
});
expect(byId).toMatchObject(input);
});
|
4,714 | 0 | petrpan-code/trpc/trpc/examples/.test/ssg | petrpan-code/trpc/trpc/examples/.test/ssg/test/smoke.test.ts | import { expect, test } from '@playwright/test';
test('query should be prefetched', async ({ page }) => {
await page.goto('/');
/**
* Since we're prefetching the query, and have JavaScript disabled,
* the data should be available immediately
*/
expect(await page.textContent('h1')).toBe('hello client');
});
test('dates should be serialized', async ({ page }) => {
/**
* This test itself doesn't really test the serialization.
* But if it succeeds, it means we didn't get an error when
* accessing the .toDateString() method on the date.
*/
await page.goto('/');
expect(await page.textContent('p')).toBe('Sat Jan 01 2022');
});
|
4,782 | 0 | petrpan-code/trpc/trpc/examples/minimal-react | petrpan-code/trpc/trpc/examples/minimal-react/test/smoke.test.ts | import { test } from '@playwright/test';
test.setTimeout(35e3);
test('go to /', async ({ page }) => {
await page.goto('/');
await page.waitForSelector(`text=tRPC user`);
});
|
4,841 | 0 | petrpan-code/trpc/trpc/examples/next-prisma-starter | petrpan-code/trpc/trpc/examples/next-prisma-starter/playwright/smoke.test.ts | import { test, expect } from '@playwright/test';
test.setTimeout(35e3);
test('go to /', async ({ page }) => {
await page.goto('/');
await page.waitForSelector(`text=Starter`);
});
test('test 404', async ({ page }) => {
const res = await page.goto('/post/not-found');
expect(res?.status()).toBe(404);
});
test('add a post', async ({ page, browser }) => {
const nonce = `${Math.random()}`;
await page.goto('/');
await page.fill(`[name=title]`, nonce);
await page.fill(`[name=text]`, nonce);
await page.click(`form [type=submit]`);
await page.waitForLoadState('networkidle');
await page.reload();
expect(await page.content()).toContain(nonce);
const ssrContext = await browser.newContext({
javaScriptEnabled: false,
});
const ssrPage = await ssrContext.newPage();
await ssrPage.goto('/');
expect(await ssrPage.content()).toContain(nonce);
});
test('server-side rendering test', async ({ page, browser }) => {
// add a post
const nonce = `${Math.random()}`;
await page.goto('/');
await page.fill(`[name=title]`, nonce);
await page.fill(`[name=text]`, nonce);
await page.click(`form [type=submit]`);
await page.waitForLoadState('networkidle');
// load the page without js
const ssrContext = await browser.newContext({
javaScriptEnabled: false,
});
const ssrPage = await ssrContext.newPage();
await ssrPage.goto('/');
expect(await ssrPage.content()).toContain(nonce);
});
|
4,861 | 0 | petrpan-code/trpc/trpc/examples/next-prisma-starter/src/server | petrpan-code/trpc/trpc/examples/next-prisma-starter/src/server/routers/post.test.ts | /**
* Integration test example for the `post` router
*/
import { createContextInner } from '../context';
import { AppRouter, appRouter } from './_app';
import { inferProcedureInput } from '@trpc/server';
test('add and get post', async () => {
const ctx = await createContextInner({});
const caller = appRouter.createCaller(ctx);
const input: inferProcedureInput<AppRouter['post']['add']> = {
text: 'hello test',
title: 'hello test',
};
const post = await caller.post.add(input);
const byId = await caller.post.byId({ id: post.id });
expect(byId).toMatchObject(input);
});
|
4,893 | 0 | petrpan-code/trpc/trpc/examples/next-prisma-todomvc | petrpan-code/trpc/trpc/examples/next-prisma-todomvc/test/playwright.test.ts | import { test } from '@playwright/test';
test.setTimeout(35e3);
test('add todo', async ({ page }) => {
await page.goto('/');
const nonce = Math.random()
.toString(36)
.replace(/[^a-z]+/g, '')
.slice(0, 6);
await page.type('.new-todo', nonce);
await page.keyboard.press('Enter');
await page.waitForResponse('**/trpc/**');
await page.waitForSelector(`text=${nonce}`);
});
export {};
|
4,934 | 0 | petrpan-code/trpc/trpc/examples/next-prisma-websockets-starter | petrpan-code/trpc/trpc/examples/next-prisma-websockets-starter/test/playwright.test.ts | import { test } from '@playwright/test';
test.setTimeout(35e3);
test('send message', async ({ browser, page }) => {
const viewer = await browser.newPage();
await viewer.goto('/');
await page.goto('/api/auth/signin');
await page.type('[name="name"]', 'test');
await page.click('[type="submit"]');
const nonce =
Math.random()
.toString(36)
.replace(/[^a-z]+/g, '')
.slice(0, 6) || 'nonce';
// await page.click('[type=submit]');
await page.type('[name=text]', nonce);
await page.click('[type=submit]');
await viewer.waitForSelector(`text=${nonce}`);
viewer.close();
});
export {};
|
4,977 | 0 | petrpan-code/trpc/trpc/packages/client/src | petrpan-code/trpc/trpc/packages/client/src/internals/types.test.ts | import isomorphicFetch from 'isomorphic-fetch';
import nodeFetch from 'node-fetch';
import type { fetch as undiciFetch } from 'undici';
import { createTRPCProxyClient } from '../createTRPCClientProxy';
import { getFetch } from '../getFetch';
import { httpBatchLink } from '../links/httpBatchLink';
import { getAbortController } from './getAbortController';
import {
AbortControllerEsque,
AbortControllerInstanceEsque,
FetchEsque,
ResponseEsque,
} from './types';
describe('AbortController', () => {
test('AbortControllerEsque', () => {
expectTypeOf(
getAbortController,
).returns.toEqualTypeOf<AbortControllerEsque | null>();
expectTypeOf(() => {
const AbortController = getAbortController(undefined)!;
return new AbortController();
}).returns.toEqualTypeOf<AbortControllerInstanceEsque>();
});
});
describe('fetch', () => {
test('parameters', () => {
createTRPCProxyClient({
links: [
httpBatchLink({
url: 'YOUR_SERVER_URL',
fetch(url, options) {
return fetch(url, options);
},
}),
],
});
});
test('FetchEsque', () => {
expectTypeOf(getFetch).returns.toEqualTypeOf<FetchEsque>();
expectTypeOf(() =>
getFetch()('', {
body: '',
headers: Math.random() > 0.5 ? [['a', 'b']] : { a: 'b' },
method: 'GET',
signal: new AbortSignal(),
}),
).returns.toEqualTypeOf<Promise<ResponseEsque>>();
getFetch({} as unknown as typeof fetch);
});
test('NativeFetchEsque', () => {
getFetch(isomorphicFetch);
getFetch(nodeFetch as any);
// Passing in undiciFetch directly in Node v18.7.0 gives:
// ReferenceError: TextEncoder is not defined
// 🤷
getFetch({} as unknown as typeof undiciFetch);
});
});
|
4,986 | 0 | petrpan-code/trpc/trpc/packages/client/src | petrpan-code/trpc/trpc/packages/client/src/links/splitLink.test.ts | import { observable } from '@trpc/server/observable';
import { OperationLink, splitLink, TRPCLink } from '../';
import { AnyRouter } from '../../../server/src';
import { createChain } from '../links/internals/createChain';
test('splitLink', () => {
const wsLinkSpy = vi.fn();
const wsLink: TRPCLink<any> = () => () =>
observable(() => {
wsLinkSpy();
});
const httpLinkSpy = vi.fn();
const httpLink: TRPCLink<any> = () => () =>
observable(() => {
httpLinkSpy();
});
const links: OperationLink<AnyRouter, any, any>[] = [
// "dedupe link"
splitLink({
condition(op) {
return op.type === 'subscription';
},
true: wsLink,
false: [httpLink],
})(null as any),
];
createChain({
links,
op: {
type: 'query',
input: null,
path: '.',
id: 0,
context: {},
},
}).subscribe({});
expect(httpLinkSpy).toHaveBeenCalledTimes(1);
expect(wsLinkSpy).toHaveBeenCalledTimes(0);
vi.resetAllMocks();
createChain({
links,
op: {
type: 'subscription',
input: null,
path: '.',
id: 0,
context: {},
},
}).subscribe({});
expect(httpLinkSpy).toHaveBeenCalledTimes(0);
expect(wsLinkSpy).toHaveBeenCalledTimes(1);
});
|
4,990 | 0 | petrpan-code/trpc/trpc/packages/client/src/links | petrpan-code/trpc/trpc/packages/client/src/links/internals/createChain.test.ts | import { observable } from '@trpc/server/observable';
import { AnyRouter } from '@trpc/server/src';
import { createChain } from './createChain';
describe('chain', () => {
test('trivial', () => {
const result$ = createChain<AnyRouter, unknown, unknown>({
links: [
({ next, op }) => {
return observable((observer) => {
const subscription = next(op).subscribe(observer);
return () => {
subscription.unsubscribe();
};
});
},
({ op }) => {
return observable((observer) => {
observer.next({
context: {},
result: {
type: 'data',
data: {
input: op.input,
},
},
});
observer.complete();
});
},
],
op: {
type: 'query',
id: 1,
input: 'world',
path: 'hello',
context: {},
},
});
const next = vi.fn();
result$.subscribe({ next });
// console.log(next.mock.calls);
expect(next).toHaveBeenCalledTimes(1);
});
test('multiple responses', () => {
const result$ = createChain<AnyRouter, unknown, unknown>({
links: [
({ next, op }) => {
return observable((observer) => {
observer.next({
context: {},
result: {
type: 'data',
data: 'from cache',
},
});
const subscription = next(op).subscribe(observer);
return () => {
subscription.unsubscribe();
};
});
},
({ op }) => {
return observable((observer) => {
observer.next({
result: {
type: 'data',
data: {
input: op.input,
},
},
});
observer.complete();
});
},
],
op: {
type: 'query',
id: 1,
input: 'world',
path: 'hello',
context: {},
},
});
const next = vi.fn();
result$.subscribe({ next });
expect(next).toHaveBeenCalledTimes(2);
expect(next.mock.calls[0]).toMatchInlineSnapshot(`
Array [
Object {
"context": Object {},
"result": Object {
"data": "from cache",
"type": "data",
},
},
]
`);
expect(next.mock.calls[1]).toMatchInlineSnapshot(`
Array [
Object {
"result": Object {
"data": Object {
"input": "world",
},
"type": "data",
},
},
]
`);
});
});
|
4,993 | 0 | petrpan-code/trpc/trpc/packages/client/src/links | petrpan-code/trpc/trpc/packages/client/src/links/internals/dedupeLink.test.ts | import { waitFor } from '@testing-library/dom';
import { AnyRouter } from '@trpc/server/src';
import { observable } from '@trpc/server/src/observable';
import { OperationLink } from '../..';
import { createChain } from './createChain';
import { dedupeLink } from './dedupeLink';
test('dedupeLink', async () => {
const endingLinkTriggered = vi.fn();
const timerTriggered = vi.fn();
const links: OperationLink<AnyRouter, any, any>[] = [
// "dedupe link"
dedupeLink()(null as any),
({ op }) => {
return observable((subscribe) => {
endingLinkTriggered();
const timer = setTimeout(() => {
timerTriggered();
subscribe.next({
result: {
type: 'data',
data: {
input: op.input,
},
},
});
subscribe.complete();
}, 1);
return () => {
clearTimeout(timer);
};
});
},
];
{
const call1 = createChain<AnyRouter, unknown, unknown>({
links,
op: {
type: 'query',
id: 1,
input: 'world',
path: 'hello',
context: {},
},
});
const call2 = createChain<AnyRouter, unknown, unknown>({
links,
op: {
type: 'query',
id: 1,
input: 'world',
path: 'hello',
context: {},
},
});
const next = vi.fn();
call1.subscribe({ next });
call2.subscribe({ next });
expect(endingLinkTriggered).toHaveBeenCalledTimes(1);
await waitFor(() => {
expect(timerTriggered).toHaveBeenCalledTimes(1);
});
expect(next).toHaveBeenCalledTimes(2);
}
});
test('dedupe - cancel one does not cancel the other', async () => {
const endingLinkTriggered = vi.fn();
const timerTriggered = vi.fn();
const links: OperationLink<AnyRouter, any, any>[] = [
// "dedupe link"
dedupeLink()(null as any),
({ op }) => {
return observable((subscribe) => {
endingLinkTriggered();
const timer = setTimeout(() => {
timerTriggered();
subscribe.next({
result: {
type: 'data',
data: {
input: op.input,
},
},
});
subscribe.complete();
}, 1);
return () => {
clearTimeout(timer);
};
});
},
];
{
const call1 = createChain<AnyRouter, unknown, unknown>({
links,
op: {
type: 'query',
id: 1,
input: 'world',
path: 'hello',
context: {},
},
});
const call2 = createChain<AnyRouter, unknown, unknown>({
links,
op: {
type: 'query',
id: 1,
input: 'world',
path: 'hello',
context: {},
},
});
const next = vi.fn();
const call1$ = call1.subscribe({ next });
call2.subscribe({ next });
call1$.unsubscribe();
expect(endingLinkTriggered).toHaveBeenCalledTimes(1);
await waitFor(() => {
expect(timerTriggered).toHaveBeenCalledTimes(1);
expect(next).toHaveBeenCalledTimes(1);
});
}
});
|
4,997 | 0 | petrpan-code/trpc/trpc/packages/client/src/links | petrpan-code/trpc/trpc/packages/client/src/links/internals/parseJSONStream.test.ts | import { parseJSONStream } from './parseJSONStream';
describe('parseJsonStream', () => {
test('multiline streamed JSON', async () => {
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
start(controller) {
const enqueue = (chunk: string) => {
controller.enqueue(encoder.encode(chunk));
};
enqueue(`{"0":${JSON.stringify({ a: 1 })}\n`);
enqueue(`,"2":${JSON.stringify({ c: 3 })}\n`);
enqueue(`,"1":${JSON.stringify({ b: 2 })}\n`);
enqueue('}');
controller.close();
},
});
const orderReceived: any[] = [];
const itemsArray: any[] = [];
const fullData = await parseJSONStream({
readableStream: stream,
onSingle: (index, data) => {
orderReceived.push(index);
itemsArray[index] = data;
},
textDecoder: new TextDecoder(),
});
expect(orderReceived).toEqual([0, 2, 1]);
expect(itemsArray).toEqual([{ a: 1 }, { b: 2 }, { c: 3 }]);
expect(fullData).toEqual(undefined);
});
});
|
5,012 | 0 | petrpan-code/trpc/trpc/packages/next/src | petrpan-code/trpc/trpc/packages/next/src/app-dir/client.test.tsx | import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { initTRPC } from '@trpc/server';
import React from 'react';
import superjson from 'superjson';
import { z } from 'zod';
import {
experimental_createActionHook,
experimental_serverActionLink,
UseTRPCActionResult,
} from './create-action-hook';
import { experimental_createServerActionHandler } from './server';
describe('without transformer', () => {
const instance = initTRPC
.context<{
foo: string;
}>()
.create({});
const { procedure } = instance;
const createAction = experimental_createServerActionHandler(instance, {
createContext() {
return {
foo: 'bar',
};
},
});
const useAction = experimental_createActionHook({
links: [experimental_serverActionLink()],
});
test('server actions smoke test', async () => {
const action = createAction(procedure.mutation((opts) => opts.ctx));
expect(await action()).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": Object {
"foo": "bar",
},
},
}
`);
});
test('normalize FormData', async () => {
const action = createAction(
procedure
.input(
z.object({
text: z.string(),
}),
)
.mutation((opts) => `hello ${opts.input.text}` as const),
);
expect(
await action({
text: 'there',
}),
).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": "hello there",
},
}
`);
const formData = new FormData();
formData.append('text', 'there');
expect(await action(formData)).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": "hello there",
},
}
`);
});
test('an actual client', async () => {
const action = createAction(
procedure
.input(
z.object({
text: z.string(),
}),
)
.mutation((opts) => `hello ${opts.input.text}` as const),
);
const allStates: Omit<
UseTRPCActionResult<any>,
'mutate' | 'mutateAsync'
>[] = [] as any[];
function MyComponent() {
const mutation = useAction(action);
const { mutate, mutateAsync, ...other } = mutation;
allStates.push(other);
return (
<>
<button
role="trigger"
onClick={() => {
mutation.mutate({
text: 'world',
});
}}
>
click me
</button>
</>
);
}
// mount it
const utils = render(<MyComponent />);
// get the contents of pre
expect(allStates.at(-1)).toMatchInlineSnapshot(`
Object {
"status": "idle",
}
`);
// click the button
userEvent.click(utils.getByRole('trigger'));
// wait to finish
await waitFor(() => {
assert(allStates.at(-1)?.status === 'success');
});
expect(allStates).toMatchInlineSnapshot(`
Array [
Object {
"status": "idle",
},
Object {
"status": "loading",
},
Object {
"data": "hello world",
"status": "success",
},
]
`);
const lastState = allStates.at(-1);
assert(lastState?.status === 'success');
expect(lastState.data).toMatchInlineSnapshot(`"hello world"`);
});
});
describe('with transformer', () => {
const instance = initTRPC
.context<{
foo: string;
}>()
.create({
transformer: superjson,
});
const { procedure } = instance;
const createAction = experimental_createServerActionHandler(instance, {
createContext() {
return {
foo: 'bar',
};
},
});
const useAction = experimental_createActionHook({
links: [experimental_serverActionLink()],
transformer: superjson,
});
test('pass a Date', async () => {
const action = createAction(
procedure
.input(
z.object({
date: z.date(),
}),
)
.mutation((opts) => opts.input.date),
);
const allStates: Omit<
UseTRPCActionResult<any>,
'mutate' | 'mutateAsync'
>[] = [] as any[];
function MyComponent() {
const mutation = useAction(action);
const { mutate, mutateAsync, ...other } = mutation;
allStates.push(other);
return (
<>
<button
role="trigger"
onClick={() => {
mutation.mutate({
date: new Date(0),
});
}}
>
click me
</button>
</>
);
}
// mount it
const utils = render(<MyComponent />);
// get the contents of pre
expect(allStates.at(-1)).toMatchInlineSnapshot(`
Object {
"status": "idle",
}
`);
// click the button
userEvent.click(utils.getByRole('trigger'));
// wait to finish
await waitFor(() => {
assert(allStates.at(-1)?.status === 'success');
});
expect(allStates).toMatchInlineSnapshot(`
Array [
Object {
"status": "idle",
},
Object {
"status": "loading",
},
Object {
"data": 1970-01-01T00:00:00.000Z,
"status": "success",
},
]
`);
const lastState = allStates.at(-1);
assert(lastState?.status === 'success');
expect(lastState.data).toMatchInlineSnapshot('1970-01-01T00:00:00.000Z');
expect(lastState.data).toBeInstanceOf(Date);
});
test('FormData', async () => {
const action = createAction(
procedure
.input(
z.object({
text: z.string(),
}),
)
.mutation((opts) => opts.input.text),
);
const allStates: Omit<
UseTRPCActionResult<any>,
'mutate' | 'mutateAsync'
>[] = [] as any[];
function MyComponent() {
const mutation = useAction(action);
const { mutate, mutateAsync, ...other } = mutation;
allStates.push(other);
return (
<>
<form
onSubmit={(e) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
mutation.mutate(formData);
}}
>
<input type="text" name="text" defaultValue="world" />
<button role="trigger" type="submit">
click me
</button>
</form>
</>
);
}
// mount it
const utils = render(<MyComponent />);
// get the contents of pre
expect(allStates.at(-1)).toMatchInlineSnapshot(`
Object {
"status": "idle",
}
`);
// click the button
userEvent.click(utils.getByRole('trigger'));
// wait to finish
await waitFor(() => {
assert(allStates.at(-1)?.status === 'success');
});
expect(allStates).toMatchInlineSnapshot(`
Array [
Object {
"status": "idle",
},
Object {
"status": "loading",
},
Object {
"data": "world",
"status": "success",
},
]
`);
const lastState = allStates.at(-1);
assert(lastState?.status === 'success');
expect(lastState.data).toMatchInlineSnapshot('"world"');
});
});
describe('type tests', () => {
const ignoreErrors = async (fn: () => unknown) => {
try {
await fn();
} catch {
// ignore
}
};
const instance = initTRPC
.context<{
foo: string;
}>()
.create({});
const { procedure } = instance;
const createAction = experimental_createServerActionHandler(instance, {
createContext() {
return {
foo: 'bar',
};
},
});
const useAction = experimental_createActionHook({
links: [experimental_serverActionLink()],
});
test('assert input is sent', async () => {
ignoreErrors(async () => {
const action = createAction(
procedure.input(z.string()).mutation((opts) => opts.input),
);
const hook = useAction(action);
// @ts-expect-error this requires an input
await action();
// @ts-expect-error this requires an input
hook.mutate();
// @ts-expect-error this requires an input
await hook.mutateAsync();
});
});
test('assert types is correct', async () => {
ignoreErrors(async () => {
const action = createAction(
procedure.input(z.date().optional()).mutation((opts) => opts.input),
);
const hook = useAction(action);
// @ts-expect-error wrong type
await action('bleh');
// @ts-expect-error wrong type
hook.mutate('bleh');
hook.mutate();
await action();
});
});
test('assert no input', async () => {
ignoreErrors(async () => {
const action = createAction(procedure.mutation((opts) => opts.input));
const hook = useAction(action);
// @ts-expect-error this takes no input
await action(null);
// @ts-expect-error this takes no input
hook.mutate(null);
// @ts-expect-error this takes no input
await hook.mutateAsync(null);
});
});
});
|
5,015 | 0 | petrpan-code/trpc/trpc/packages/next/src | petrpan-code/trpc/trpc/packages/next/src/app-dir/formDataToObject.test.ts | import { formDataToObject } from './formDataToObject';
test('basic', () => {
const formData = new FormData();
formData.append('foo', 'bar');
expect(formDataToObject(formData)).toEqual({
foo: 'bar',
});
});
test('multiple values on the same key', () => {
const formData = new FormData();
formData.append('foo', 'bar');
formData.append('foo', 'baz');
expect(formDataToObject(formData)).toEqual({
foo: ['bar', 'baz'],
});
});
test('deep key', () => {
const formData = new FormData();
formData.append('foo.bar.baz', 'qux');
expect(formDataToObject(formData)).toEqual({
foo: {
bar: {
baz: 'qux',
},
},
});
});
test('array', () => {
const formData = new FormData();
formData.append('foo[0]', 'bar');
formData.append('foo[1]', 'baz');
expect(formDataToObject(formData)).toEqual({
foo: ['bar', 'baz'],
});
});
test('array with dot notation', () => {
const formData = new FormData();
formData.append('foo.0', 'bar');
formData.append('foo.1', 'baz');
expect(formDataToObject(formData)).toEqual({
foo: ['bar', 'baz'],
});
});
|
5,032 | 0 | petrpan-code/trpc/trpc/packages/react-query/src | petrpan-code/trpc/trpc/packages/react-query/src/internals/getArrayQueryKey.test.ts | import { getArrayQueryKey } from './getArrayQueryKey';
test('getArrayQueryKey', () => {
// empty path should not nest an extra array
expect(getArrayQueryKey('', 'any')).toMatchInlineSnapshot(`Array []`);
// should not nest an empty object
expect(getArrayQueryKey('foo', 'any')).toMatchInlineSnapshot(`
Array [
Array [
"foo",
],
]
`);
expect(getArrayQueryKey('foo', 'query')).toMatchInlineSnapshot(`
Array [
Array [
"foo",
],
Object {
"type": "query",
},
]
`);
expect(getArrayQueryKey(['foo'], 'query')).toMatchInlineSnapshot(`
Array [
Array [
"foo",
],
Object {
"type": "query",
},
]
`);
expect(getArrayQueryKey('foo', 'infinite')).toMatchInlineSnapshot(`
Array [
Array [
"foo",
],
Object {
"type": "infinite",
},
]
`);
expect(getArrayQueryKey(['foo'], 'infinite')).toMatchInlineSnapshot(`
Array [
Array [
"foo",
],
Object {
"type": "infinite",
},
]
`);
expect(getArrayQueryKey(['foo', 'bar'], 'query')).toMatchInlineSnapshot(`
Array [
Array [
"foo",
],
Object {
"input": "bar",
"type": "query",
},
]
`);
expect(getArrayQueryKey([undefined, 'bar'], 'query')).toMatchInlineSnapshot(`
Array [
Array [],
Object {
"input": "bar",
"type": "query",
},
]
`);
expect(getArrayQueryKey(['post.byId', '1'], 'query')).toMatchInlineSnapshot(`
Array [
Array [
"post",
"byId",
],
Object {
"input": "1",
"type": "query",
},
]
`);
});
|
5,092 | 0 | petrpan-code/trpc/trpc/packages/server/src/adapters/node-http/content-type | petrpan-code/trpc/trpc/packages/server/src/adapters/node-http/content-type/json/getPostBody.test.ts | import { EventEmitter } from 'events';
import { getPostBody } from './getPostBody';
test('has body', async () => {
const body = {};
const resolvedBody = await getPostBody({
req: {
body,
headers: {
'content-type': 'application/json',
},
},
} as any);
expect(resolvedBody).toMatchInlineSnapshot(`
Object {
"data": Object {},
"ok": true,
"preprocessed": true,
}
`);
});
test('req as eventemitter', async () => {
const events = new EventEmitter();
setTimeout(() => {
events.emit(
'data',
JSON.stringify({
hello: 'there',
}),
);
events.emit('end');
}, 5);
(events as any).headers = {};
const result = await getPostBody({
req: events,
} as any);
expect(result.ok).toBeTruthy();
expect((result as any).data).toBeTruthy();
expect(result).toMatchInlineSnapshot(`
Object {
"data": "{\\"hello\\":\\"there\\"}",
"ok": true,
"preprocessed": false,
}
`);
});
|
5,117 | 0 | petrpan-code/trpc/trpc/packages/server/src | petrpan-code/trpc/trpc/packages/server/src/http/batchStreamFormatter.test.ts | import { getBatchStreamFormatter } from './batchStreamFormatter';
test('getBatchStreamFormatter', () => {
const formatter = getBatchStreamFormatter();
expect(formatter(1, '{"foo": "bar"}')).toBe(`{"1":{"foo": "bar"}\n`);
expect(formatter(0, '{"q": "a"}')).toBe(`,"0":{"q": "a"}\n`);
expect(formatter(2, '{"hello": "world"}')).toBe(`,"2":{"hello": "world"}\n`);
expect(formatter.end()).toBe('}');
});
|
5,128 | 0 | petrpan-code/trpc/trpc/packages/server/src | petrpan-code/trpc/trpc/packages/server/src/observable/observable.test.ts | import { observable, share, tap } from '.';
test('vanilla observable - complete()', () => {
const obs = observable<number, Error>((observer) => {
observer.next(1);
observer.complete();
});
const next = vi.fn();
const error = vi.fn();
const complete = vi.fn();
obs.subscribe({
next,
error,
complete,
});
expect(next.mock.calls).toHaveLength(1);
expect(complete.mock.calls).toHaveLength(1);
expect(error.mock.calls).toHaveLength(0);
expect(next.mock.calls[0]![0]!).toBe(1);
});
test('vanilla observable - unsubscribe()', () => {
const obs$ = observable<number, Error>((observer) => {
observer.next(1);
});
const next = vi.fn();
const error = vi.fn();
const complete = vi.fn();
const sub = obs$.subscribe({
next,
error,
complete,
});
sub.unsubscribe();
expect(next.mock.calls).toHaveLength(1);
expect(complete.mock.calls).toHaveLength(0);
expect(error.mock.calls).toHaveLength(0);
expect(next.mock.calls[0]![0]!).toBe(1);
});
test('pipe - combine operators', () => {
const taps = {
next: vi.fn(),
complete: vi.fn(),
error: vi.fn(),
};
const obs = observable<number, Error>((observer) => {
observer.next(1);
}).pipe(
// operators:
share(),
tap(taps),
);
{
const next = vi.fn();
const error = vi.fn();
const complete = vi.fn();
obs.subscribe({
next,
error,
complete,
});
expect(next.mock.calls).toHaveLength(1);
expect(complete.mock.calls).toHaveLength(0);
expect(error.mock.calls).toHaveLength(0);
expect(next.mock.calls[0]![0]!).toBe(1);
}
{
const next = vi.fn();
const error = vi.fn();
const complete = vi.fn();
obs.subscribe({
next,
error,
complete,
});
expect(next.mock.calls).toHaveLength(0);
expect(complete.mock.calls).toHaveLength(0);
expect(error.mock.calls).toHaveLength(0);
}
expect({
next: taps.next.mock.calls,
error: taps.error.mock.calls,
complete: taps.complete.mock.calls,
}).toMatchInlineSnapshot(`
Object {
"complete": Array [],
"error": Array [],
"next": Array [
Array [
1,
],
],
}
`);
});
|
5,135 | 0 | petrpan-code/trpc/trpc/packages/server/src/observable | petrpan-code/trpc/trpc/packages/server/src/observable/operators/map.test.ts | import { EventEmitter } from 'events';
import { map } from '.';
import { observable } from '../observable';
interface SubscriptionEvents<TOutput> {
data: (data: TOutput) => void;
}
declare interface CustomEventEmitter<TOutput> {
on<U extends keyof SubscriptionEvents<TOutput>>(
event: U,
listener: SubscriptionEvents<TOutput>[U],
): this;
once<U extends keyof SubscriptionEvents<TOutput>>(
event: U,
listener: SubscriptionEvents<TOutput>[U],
): this;
emit<U extends keyof SubscriptionEvents<TOutput>>(
event: U,
...args: Parameters<SubscriptionEvents<TOutput>[U]>
): boolean;
}
class CustomEventEmitter<TOutput>
extends EventEmitter
implements CustomEventEmitter<TOutput> {}
test('map', () => {
type EventShape = { num: number };
const ee = new CustomEventEmitter<EventShape>();
const eventObservable = observable<EventShape, unknown>((observer) => {
const callback = (data: EventShape) => {
observer.next(data);
};
ee.on('data', callback);
return () => {
ee.off('data', callback);
};
});
const pipeCalls = vi.fn();
const piped = eventObservable.pipe(
map((...args) => {
pipeCalls(...args);
const [value] = args;
return value.num;
}),
);
const next = vi.fn();
const subscription = piped.subscribe({
next(value) {
expectTypeOf<number>(value);
next(value);
},
});
expect(next).not.toHaveBeenCalled();
ee.emit('data', { num: 1 });
ee.emit('data', { num: 2 });
expect(next).toHaveBeenCalledTimes(2);
expect(next.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
1,
],
Array [
2,
],
]
`);
expect(pipeCalls.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
Object {
"num": 1,
},
0,
],
Array [
Object {
"num": 2,
},
1,
],
]
`);
expect(ee.listeners('data')).toHaveLength(1);
subscription.unsubscribe();
expect(ee.listeners('data')).toHaveLength(0);
});
|
5,137 | 0 | petrpan-code/trpc/trpc/packages/server/src/observable | petrpan-code/trpc/trpc/packages/server/src/observable/operators/share.test.ts | /* eslint-disable no-var */
import { observable } from '../observable';
import { share } from './share';
test('share', () => {
const obs = share()(
observable<number, Error>((observer) => {
observer.next(1);
}),
);
{
const next = vi.fn();
const error = vi.fn();
const complete = vi.fn();
var subscription1 = obs.subscribe({
next,
error,
complete,
});
expect(next.mock.calls).toHaveLength(1);
expect(complete.mock.calls).toHaveLength(0);
expect(error.mock.calls).toHaveLength(0);
expect(next.mock.calls[0]![0]!).toBe(1);
}
{
// subscribe again - it's shared so should not propagate any results
const next = vi.fn();
const error = vi.fn();
const complete = vi.fn();
var subscription2 = obs.subscribe({
next,
error,
complete,
});
expect(next.mock.calls).toHaveLength(0);
expect(complete.mock.calls).toHaveLength(0);
expect(error.mock.calls).toHaveLength(0);
}
subscription1.unsubscribe();
subscription2.unsubscribe();
// now it should be reset so we can do a new subscription
{
const next = vi.fn();
const error = vi.fn();
const complete = vi.fn();
var subscription3 = obs.subscribe({
next,
error,
complete,
});
expect(next.mock.calls).toHaveLength(1);
expect(complete.mock.calls).toHaveLength(0);
expect(error.mock.calls).toHaveLength(0);
expect(next.mock.calls[0]![0]!).toBe(1);
subscription3.unsubscribe();
}
});
|
5,155 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/TRPCError.test.ts | import { getTRPCErrorFromUnknown, TRPCError } from '@trpc/server/src';
test('should extend original Error class', () => {
const trpcError = new TRPCError({ code: 'FORBIDDEN' });
expect(trpcError).toBeInstanceOf(TRPCError);
expect(trpcError).toBeInstanceOf(Error);
});
test('should populate name field using the class name', () => {
const trpcError = new TRPCError({ code: 'FORBIDDEN' });
expect(trpcError.name).toEqual('TRPCError');
});
test('should use message when one is provided', () => {
const trpcError = new TRPCError({ code: 'FORBIDDEN', message: 'wat' });
expect(trpcError.message).toEqual('wat');
});
test('should fallback to using code as a message when one is not provided', () => {
const trpcError = new TRPCError({ code: 'FORBIDDEN' });
expect(trpcError.message).toEqual('FORBIDDEN');
});
test('should correctly assign the cause when error instance is provided', () => {
const originalError = new Error('morty');
const trpcError = new TRPCError({
code: 'FORBIDDEN',
cause: originalError,
});
expect(trpcError.cause).toBe(originalError);
});
test('should be able to create synthetic cause from string', () => {
const trpcError = new TRPCError({ code: 'FORBIDDEN', cause: 'rick' });
expect(trpcError.cause).toBeInstanceOf(Error);
expect(trpcError.cause!.message).toBe('rick');
// @ts-expect-error -- until the target is updated to es2022+
expect(trpcError.cause!.cause).toBe(undefined);
});
test('should be able to create synthetic cause from object', () => {
const cause = { foo: 'bar' };
const trpcError = new TRPCError({ code: 'FORBIDDEN', cause });
expect(trpcError.cause).toBeInstanceOf(Error);
// @ts-expect-error -- until the target is updated to es2022+
expect(trpcError.cause.foo).toBe('bar');
});
test('should skip creating the cause if one is not provided', () => {
const trpcError = new TRPCError({ code: 'FORBIDDEN' });
expect(trpcError.cause).toBeUndefined();
});
describe('getTRPCErrorFromUnknown', () => {
test('should return same error if its already TRPCError instance', () => {
const originalError = new TRPCError({ code: 'FORBIDDEN' });
const trpcError = getTRPCErrorFromUnknown(originalError);
expect(trpcError).toBe(originalError);
});
test('should create new instance of TRPCError with `INTERNAL_SERVER_ERROR` code and same message for non-errors', () => {
const originalError = 'rick';
const trpcError = getTRPCErrorFromUnknown(originalError);
expect(trpcError).toBeInstanceOf(TRPCError);
expect(trpcError.message).toEqual('rick');
// @ts-expect-error -- until the target is updated to es2022+
expect(trpcError.cause!.cause).toBe(undefined);
});
test('should create new instance of TRPCError with `INTERNAL_SERVER_ERROR` code and proper cause for errors', () => {
const originalError = new Error('morty');
const trpcError = getTRPCErrorFromUnknown(originalError);
expect(trpcError).toBeInstanceOf(TRPCError);
expect(trpcError.message).toEqual('morty');
expect(trpcError.cause).toBe(originalError);
expect(trpcError.cause?.message).toEqual('morty');
});
test('should preserve original stack in case new instance of TRPCError is created', () => {
const originalError = new Error('picklerick');
originalError.stack = 'meeseeks';
const trpcError = getTRPCErrorFromUnknown(originalError);
expect(trpcError.stack).toEqual('meeseeks');
});
test('should create stack in case the cause was not an Error', () => {
const cause = 'picklyrick';
const trpcError = getTRPCErrorFromUnknown(cause);
expect(typeof trpcError.stack).toEqual('string');
});
});
test('should be extendable', () => {
class MyError extends TRPCError {
constructor() {
super({ code: 'FORBIDDEN' });
this.name = 'MyError';
}
}
const originalError = new MyError();
expect(originalError).toBeInstanceOf(TRPCError);
expect(originalError).toBeInstanceOf(Error);
expect(originalError).toBeInstanceOf(MyError);
const trpcError = getTRPCErrorFromUnknown(originalError);
expect(trpcError).toBe(originalError);
});
test('allows fuzzy matching based on error name', () => {
class MyError extends Error {
constructor() {
super('wat');
this.name = 'TRPCError';
}
}
const originalError = new MyError();
const trpcError = getTRPCErrorFromUnknown(originalError);
expect(trpcError).toBe(originalError);
});
|
5,159 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/abortQuery.test.ts | import { routerToServerAndClientNew, waitMs } from './___testHelpers';
import { initTRPC } from '@trpc/server/src/core';
const t = initTRPC.create();
const router = t.router({
testQuery: t.procedure.query(async () => {
await waitMs(1000);
return 'hello';
}),
testMutation: t.procedure.mutation(async () => {
await waitMs(1000);
return 'hello';
}),
});
type Router = typeof router;
describe('vanilla client procedure abortion', () => {
test('query', async () => {
const abortController = new AbortController();
const signal = abortController.signal;
const { close, proxy } = routerToServerAndClientNew<Router>(router);
const promise = proxy.testQuery.query(undefined, { signal });
abortController.abort();
expect(promise).rejects.toThrowError(/aborted/);
await close();
});
test('mutation', async () => {
const abortController = new AbortController();
const signal = abortController.signal;
const { close, proxy } = routerToServerAndClientNew<Router>(router);
const promise = proxy.testMutation.mutate(undefined, { signal });
abortController.abort();
expect(promise).rejects.toThrowError(/aborted/);
await close();
});
});
|
5,160 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/callRouter.test.ts | import './___packages';
import { initTRPC } from '@trpc/server';
test('deprecated: call proc directly', async () => {
const t = initTRPC.create();
const router = t.router({
sub: t.router({
hello: t.procedure.query(() => 'hello'),
}),
});
const result = await router.sub.hello({
ctx: {},
path: 'asd',
type: 'query',
rawInput: {},
});
expect(result).toBe('hello');
});
|
5,161 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/caller.test.ts | import { waitError } from './___testHelpers';
import { initTRPC, TRPCError } from '@trpc/server/src';
import { z } from 'zod';
const t = initTRPC
.context<{
foo?: 'bar';
}>()
.create();
const { procedure } = t;
test('undefined input query', async () => {
const router = t.router({
hello: procedure.query(() => 'world'),
});
const caller = router.createCaller({});
const result = await caller.hello();
expectTypeOf<string>(result);
});
test('input query', async () => {
const router = t.router({
greeting: t.procedure
.input(z.object({ name: z.string() }))
.query(({ input }) => `Hello ${input.name}`),
});
const caller = router.createCaller({});
const result = await caller.greeting({ name: 'Sachin' });
expectTypeOf<string>(result);
});
test('input mutation', async () => {
const posts = ['One', 'Two', 'Three'];
const router = t.router({
post: t.router({
delete: t.procedure.input(z.number()).mutation(({ input }) => {
posts.splice(input, 1);
}),
}),
});
const caller = router.createCaller({});
await caller.post.delete(0);
expect(posts).toStrictEqual(['Two', 'Three']);
});
test('input subscription', async () => {
const onDelete = vi.fn();
const router = t.router({
onDelete: t.procedure.subscription(onDelete),
});
const caller = router.createCaller({});
await caller.onDelete();
expect(onDelete).toHaveBeenCalledTimes(1);
});
test('context with middleware', async () => {
const isAuthed = t.middleware(({ next, ctx }) => {
if (!ctx.foo) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: 'You are not authorized',
});
}
return next();
});
const protectedProcedure = t.procedure.use(isAuthed);
const router = t.router({
secret: protectedProcedure.query(({ ctx }) => ctx.foo),
});
const caller = router.createCaller({});
const error = await waitError(caller.secret(), TRPCError);
expect(error.code).toBe('UNAUTHORIZED');
expect(error.message).toBe('You are not authorized');
const authorizedCaller = router.createCaller({ foo: 'bar' });
const result = await authorizedCaller.secret();
expect(result).toBe('bar');
});
|
5,162 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/children.test.ts | import { routerToServerAndClientNew } from './___testHelpers';
import { initTRPC } from '@trpc/server/src';
test('children', async () => {
const t = initTRPC.create();
const router = t.router({
foo: t.procedure.query(() => 'bar'),
child: t.router({
childQuery: t.procedure.query(() => 'asd'),
grandchild: t.router({
foo: t.procedure.query(() => 'grandchild' as const),
mut: t.procedure.mutation(() => 'mut'),
}),
}),
});
const { queries, mutations, subscriptions, procedures } = router._def;
expect({
queries,
mutations,
subscriptions,
procedures,
}).toMatchInlineSnapshot(`
Object {
"mutations": Object {
"child.grandchild.mut": [Function],
},
"procedures": Object {
"child.childQuery": [Function],
"child.grandchild.foo": [Function],
"child.grandchild.mut": [Function],
"foo": [Function],
},
"queries": Object {
"child.childQuery": [Function],
"child.grandchild.foo": [Function],
"foo": [Function],
},
"subscriptions": Object {},
}
`);
const { close, proxy } = routerToServerAndClientNew(router);
expect(await proxy.foo.query()).toBe('bar');
expect(await proxy.child.grandchild.foo.query()).toBe('grandchild');
expect(await proxy.child.grandchild.mut.mutate()).toBe('mut');
await close();
});
test('w/o children', async () => {
const t = initTRPC.create();
const foo = t.procedure.query(() => 'bar');
const router = t.router({
foo,
});
expectTypeOf(router._def.procedures.foo).toEqualTypeOf(foo);
});
|
5,163 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/clientInternals.test.ts | import { getFetch } from '@trpc/client/src';
import { getAbortController } from '@trpc/client/src/internals/getAbortController';
describe('getAbortController() from..', () => {
test('passed', () => {
const sym: any = Symbol('test');
expect(getAbortController(sym)).toBe(sym);
});
test('window', () => {
const sym: any = Symbol('test');
(global as any).AbortController = undefined;
(global as any).window = {
AbortController: sym,
};
expect(getAbortController(null)).toBe(sym);
});
test('global', () => {
const sym: any = Symbol('test');
(global as any).AbortController = sym;
(global as any).window = undefined;
expect(getAbortController(null)).toBe(sym);
});
test('window w. undefined AbortController -> global', () => {
const sym: any = Symbol('test');
(global as any).AbortController = sym;
(global as any).window = {};
expect(getAbortController(null)).toBe(sym);
});
test('neither', () => {
(global as any).AbortController = undefined;
(global as any).window = undefined;
expect(getAbortController(null)).toBe(null);
});
});
describe('getFetch() from...', () => {
test('passed', () => {
const customImpl: any = () => true;
expect(getFetch(customImpl)).toBe(customImpl);
});
test('window', () => {
(global as any).fetch = undefined;
(global as any).window = {
fetch: () => 42,
};
expect(getFetch()('')).toBe(42);
});
test('global', () => {
(global as any).fetch = () => 1337;
(global as any).window = undefined;
delete (global as any).window;
expect(getFetch()('')).toBe(1337);
});
test('window w. undefined fetch -> global', () => {
(global as any).fetch = () => 808;
(global as any).window = {};
expect(getFetch()('')).toBe(808);
});
test('neither -> throws', () => {
(global as any).fetch = undefined;
(global as any).window = undefined;
expect(() => getFetch()).toThrowError();
});
});
|
5,164 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/concat.test.ts | import { routerToServerAndClientNew } from './___testHelpers';
import { initTRPC, TRPCError } from '@trpc/server/src';
import { konn } from 'konn';
type User = {
id: string;
name: string;
};
type Context = {
user: User | null;
};
const mockUser: User = {
id: '123',
name: 'John Doe',
};
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.context<Context>().create();
const isAuthed = t.middleware(({ next, ctx }) => {
if (!ctx.user) {
throw new TRPCError({
code: 'UNAUTHORIZED',
});
}
return next({
ctx: {
user: ctx.user,
},
});
});
const addFoo = t.middleware(({ next }) => {
return next({
ctx: {
foo: 'bar' as const,
},
});
});
const proc1 = t.procedure.use(isAuthed);
const proc2 = t.procedure.use(addFoo);
const combined = t.procedure.unstable_concat(proc1).unstable_concat(proc2);
const appRouter = t.router({
getContext: combined.mutation(({ ctx }) => {
return ctx;
}),
});
const opts = routerToServerAndClientNew(appRouter, {
server: {
createContext() {
return {
user: mockUser,
};
},
},
});
const client = opts.client;
return {
close: opts.close,
client,
proxy: opts.proxy,
};
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('decorate independently', async () => {
const result = await ctx.proxy.getContext.mutate();
expect(result).toEqual({
user: mockUser,
foo: 'bar',
});
expectTypeOf(result).toEqualTypeOf<{
user: User | null;
foo: 'bar';
}>();
});
|
5,165 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/createClient.test.ts | import './___packages';
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
global.fetch = vi.fn() as any;
describe('typedefs on createClient', () => {
test('ok to pass only links', () => {
createTRPCProxyClient({
links: [httpBatchLink({ url: 'foo' })],
});
});
test('error if both url and links are passed', () => {
createTRPCProxyClient({
links: [httpBatchLink({ url: 'foo' })],
// @ts-expect-error - can't pass url along with links
url: 'foo',
});
});
});
|
5,166 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/createUntypedClient.test.ts | import { ignoreErrors } from './___testHelpers';
import { createTRPCUntypedClient } from '@trpc/client/src';
import { Unsubscribable } from '@trpc/server/src/observable';
test('loosely typed parameters', () => {
const client = createTRPCUntypedClient({
links: [],
});
ignoreErrors(async () => {
const _arguments = [
'foo',
{ bar: 1 },
{
signal: new AbortController().signal,
},
] as const;
await client.query(..._arguments);
await client.mutation(..._arguments);
client.subscription(..._arguments);
});
});
test('subscription required parameters and result', () => {
const client = createTRPCUntypedClient({
links: [],
});
ignoreErrors(() => {
// @ts-expect-error must pass input
client.subscription('foo');
// @ts-expect-error must pass options
client.subscription('foo', { bar: 1 });
const subResult = client.subscription('foo', { bar: 1 }, {});
expectTypeOf<typeof subResult>().toEqualTypeOf<Unsubscribable>();
});
});
test('query and mutation result type is Promise<any>', () => {
const client = createTRPCUntypedClient({
links: [],
});
ignoreErrors(async () => {
const queryResult = client.query('foo');
expectTypeOf<typeof queryResult>().toEqualTypeOf<Promise<any>>();
const awaitedQueryResult = await queryResult;
expectTypeOf<typeof awaitedQueryResult>().toBeUnknown();
const mutationResult = client.query('foo');
expectTypeOf<typeof mutationResult>().toEqualTypeOf<Promise<any>>();
const awaitedMutationResult = await mutationResult;
expectTypeOf<typeof awaitedMutationResult>().toBeUnknown();
});
});
|
5,167 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/dataloader.test.ts | /* eslint-disable @typescript-eslint/no-empty-function */
import { waitError, waitMs } from './___testHelpers';
import { dataLoader } from '@trpc/client/src/internals/dataLoader';
describe('basic', () => {
const fetchFn = vi.fn();
const validateFn = vi.fn();
const loader = dataLoader<number, number>({
validate: () => {
validateFn();
return true;
},
fetch: (keys) => {
fetchFn(keys);
const promise = new Promise<number[]>((resolve) => {
resolve(keys.map((v) => v + 1));
});
return { promise, cancel: () => {} };
},
});
beforeEach(() => {
fetchFn.mockClear();
validateFn.mockClear();
});
test('no time between calls', async () => {
const $result = await Promise.all([
loader.load(1).promise,
loader.load(2).promise,
]);
expect($result).toEqual([2, 3]);
expect(validateFn.mock.calls.length).toMatchInlineSnapshot(`2`);
expect(fetchFn).toHaveBeenCalledTimes(1);
expect(fetchFn).toHaveBeenNthCalledWith(1, [1, 2]);
});
test('time between calls', async () => {
const res1 = loader.load(3);
await waitMs(1);
const res2 = loader.load(4);
const $result = await Promise.all([res1.promise, res2.promise]);
expect($result).toEqual([4, 5]);
expect(validateFn.mock.calls.length).toMatchInlineSnapshot(`2`);
expect(fetchFn).toHaveBeenCalledTimes(2);
expect(fetchFn).toHaveBeenNthCalledWith(1, [3]);
expect(fetchFn).toHaveBeenNthCalledWith(2, [4]);
});
});
describe('cancellation', () => {
const fetchFn = vi.fn();
const validateFn = vi.fn();
const cancelFn = vi.fn();
const loader = dataLoader<number, number>({
validate: () => {
return true;
},
fetch: (keys) => {
fetchFn();
const promise = new Promise<number[]>((resolve) => {
setTimeout(() => {
resolve(keys.map((v) => v + 1));
}, 10);
});
return { promise, cancel: cancelFn };
},
});
beforeEach(() => {
fetchFn.mockClear();
validateFn.mockClear();
cancelFn.mockClear();
});
test('cancel immediately before it is executed', async () => {
const res1 = loader.load(1);
const res2 = loader.load(2);
res1.cancel();
res2.cancel();
expect(fetchFn).toHaveBeenCalledTimes(0);
expect(validateFn).toHaveBeenCalledTimes(0);
expect(cancelFn).toHaveBeenCalledTimes(0);
expect(await Promise.allSettled([res1.promise, res2.promise]))
.toMatchInlineSnapshot(`
Array [
Object {
"reason": [Error: Aborted],
"status": "rejected",
},
Object {
"reason": [Error: Aborted],
"status": "rejected",
},
]
`);
});
test('cancel after some time', async () => {
const res1 = loader.load(2);
const res2 = loader.load(3);
await waitMs(1);
res1.cancel();
res2.cancel();
expect(await Promise.allSettled([res1.promise, res2.promise]))
.toMatchInlineSnapshot(`
Array [
Object {
"status": "fulfilled",
"value": 3,
},
Object {
"status": "fulfilled",
"value": 4,
},
]
`);
});
test('cancel only a single request', async () => {
const res1 = loader.load(2);
const res2 = loader.load(3);
res2.cancel();
expect(cancelFn).toHaveBeenCalledTimes(0);
expect(await Promise.allSettled([res1.promise, res2.promise]))
.toMatchInlineSnapshot(`
Array [
Object {
"status": "fulfilled",
"value": 3,
},
Object {
"reason": [Error: Aborted],
"status": "rejected",
},
]
`);
});
});
test('errors', async () => {
const loader = dataLoader<number, number>({
validate: () => true,
fetch: () => {
const promise = new Promise<number[]>((_resolve, reject) => {
reject(new Error('Some error'));
});
return { promise, cancel: () => {} };
},
});
const result1 = loader.load(1);
const result2 = loader.load(2);
await expect(result1.promise).rejects.toMatchInlineSnapshot(
`[Error: Some error]`,
);
await expect(result2.promise).rejects.toMatchInlineSnapshot(
`[Error: Some error]`,
);
});
describe('validation', () => {
const validateFn = vi.fn();
const fetchFn = vi.fn();
const loader = dataLoader<number, number>({
validate: (keys) => {
validateFn(keys);
const sum = keys.reduce((acc, key) => acc + key, 0);
return sum < 10;
},
fetch: (keys) => {
fetchFn(keys);
const promise = new Promise<number[]>((resolve) => {
resolve(keys.map((v) => v + 1));
});
return { promise, cancel: () => {} };
},
});
beforeEach(() => {
fetchFn.mockClear();
validateFn.mockClear();
});
test('1', async () => {
const $result = await Promise.all([
loader.load(1).promise,
loader.load(9).promise,
loader.load(0).promise,
]);
expect($result).toEqual([2, 10, 1]);
expect(validateFn.mock.calls.length).toMatchInlineSnapshot(`4`);
});
test('2', async () => {
const $result = await Promise.all([
loader.load(2).promise,
loader.load(9).promise,
loader.load(3).promise,
loader.load(4).promise,
loader.load(5).promise,
loader.load(1).promise,
]);
expect($result).toMatchInlineSnapshot(`
Array [
3,
10,
4,
5,
6,
2,
]
`);
expect(validateFn.mock.calls.length).toMatchInlineSnapshot(`9`);
expect(fetchFn.mock.calls.length).toMatchInlineSnapshot(`4`);
});
test('too large', async () => {
const $result = await waitError(loader.load(13).promise);
expect($result).toMatchInlineSnapshot(
`[Error: Input is too big for a single dispatch]`,
);
});
});
|
5,168 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/errorFormatting.test.ts | import { routerToServerAndClientNew, waitError } from './___testHelpers';
import { TRPCClientError } from '@trpc/client';
import {
AnyRouter,
DefaultErrorShape,
initTRPC,
TRPCError,
} from '@trpc/server';
import { DefaultErrorData } from '@trpc/server/src/error/formatter';
import { konn } from 'konn';
import { z, ZodError } from 'zod';
function isTRPCClientError<TRouter extends AnyRouter>(
cause: unknown,
): cause is TRPCClientError<TRouter> {
return cause instanceof TRPCClientError;
}
describe('no custom error formatter', () => {
const t = initTRPC.create();
const appRouter = t.router({
greeting: t.procedure.query(() => {
if (Math.random() >= 0) {
// always fails
throw new Error('Fails');
}
return 'never';
}),
});
const ctx = konn()
.beforeEach(() => {
const opts = routerToServerAndClientNew(appRouter);
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('infer errors with type guard', async () => {
const err = await waitError(ctx.proxy.greeting.query());
if (!isTRPCClientError<typeof appRouter>(err)) {
throw new Error('Bad');
}
expectTypeOf(err.data).not.toBeAny();
expectTypeOf(err.shape).not.toBeAny();
expectTypeOf(err.data!).toMatchTypeOf<DefaultErrorData>();
expectTypeOf(err.shape!).toMatchTypeOf<DefaultErrorShape>();
});
});
describe('with custom error formatter', () => {
const t = initTRPC.create({
errorFormatter({ shape }) {
return {
...shape,
data: {
...shape.data,
foo: 'bar' as const,
},
};
},
});
const appRouter = t.router({
greeting: t.procedure.query(() => {
if (Math.random() >= 0) {
// always fails
throw new Error('Fails');
}
return 'never';
}),
});
const ctx = konn()
.beforeEach(() => {
const opts = routerToServerAndClientNew(appRouter);
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('infer errors with type guard', async () => {
const err = await waitError(ctx.proxy.greeting.query());
if (!isTRPCClientError<typeof appRouter>(err)) {
throw new Error('Bad');
}
expectTypeOf(err.data).not.toBeAny();
expectTypeOf(err.shape).not.toBeAny();
expectTypeOf(err.data!).toMatchTypeOf<DefaultErrorData>();
expectTypeOf(err.shape!).toMatchTypeOf<DefaultErrorShape>();
expectTypeOf(err.data!.foo).toEqualTypeOf<'bar'>();
err.data!.stack = '[redacted]';
expect(err.data).toMatchInlineSnapshot(`
Object {
"code": "INTERNAL_SERVER_ERROR",
"foo": "bar",
"httpStatus": 500,
"path": "greeting",
"stack": "[redacted]",
}
`);
expect(err.shape).toMatchInlineSnapshot(`
Object {
"code": -32603,
"data": Object {
"code": "INTERNAL_SERVER_ERROR",
"foo": "bar",
"httpStatus": 500,
"path": "greeting",
"stack": "[redacted]",
},
"message": "Fails",
}
`);
});
});
describe('custom error sub-classes', () => {
class MyCustomAuthError extends TRPCError {
public readonly reason;
public constructor(opts: {
message?: string;
reason: 'BAD_PHONE' | 'INVALID_AREA_CODE';
cause?: unknown;
}) {
super({
...opts,
code: 'UNAUTHORIZED',
message: opts.message ?? opts.reason,
});
this.reason = opts.reason;
}
}
const t = initTRPC.create({
errorFormatter(opts) {
return {
...opts.shape,
data: {
...opts.shape.data,
reason:
opts.error instanceof MyCustomAuthError ? opts.error.reason : null,
},
};
},
});
const appRouter = t.router({
greeting: t.procedure.query(() => {
if (Math.random() >= 0) {
// always fails
throw new MyCustomAuthError({
reason: 'BAD_PHONE',
});
}
return 'never';
}),
});
const ctx = konn()
.beforeEach(() => {
const opts = routerToServerAndClientNew(appRouter);
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('infer errors with type guard', async () => {
const err = await waitError(ctx.proxy.greeting.query());
if (!isTRPCClientError<typeof appRouter>(err)) {
throw new Error('Bad');
}
expectTypeOf(err.data).not.toBeAny();
expectTypeOf(err.shape).not.toBeAny();
expectTypeOf(err.data!).toMatchTypeOf<DefaultErrorData>();
expectTypeOf(err.shape!).toMatchTypeOf<DefaultErrorShape>();
expectTypeOf(err.data!.reason).toEqualTypeOf<
'BAD_PHONE' | 'INVALID_AREA_CODE' | null
>();
err.data!.stack = '[redacted]';
expect(err.shape!.data.httpStatus).toBe(401);
expect(err.shape!.data.reason).toBe('BAD_PHONE');
expect(err.shape).toMatchInlineSnapshot(`
Object {
"code": -32001,
"data": Object {
"code": "UNAUTHORIZED",
"httpStatus": 401,
"path": "greeting",
"reason": "BAD_PHONE",
"stack": "[redacted]",
},
"message": "BAD_PHONE",
}
`);
});
});
describe('zod errors according to docs', () => {
const t = initTRPC.create({
errorFormatter(opts) {
const { shape, error } = opts;
return {
...shape,
data: {
...shape.data,
zodError:
error.code === 'BAD_REQUEST' && error.cause instanceof ZodError
? error.cause.flatten()
: null,
},
};
},
});
const appRouter = t.router({
greeting: t.procedure.input(z.number().min(10)).query((opts) => opts.input),
});
const ctx = konn()
.beforeEach(() => {
const opts = routerToServerAndClientNew(appRouter);
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('zod errors according to docs', async () => {
// bad query
const err = await waitError(ctx.proxy.greeting.query(5));
assert(isTRPCClientError<typeof appRouter>(err));
assert(err.data);
assert(err.data.zodError);
expectTypeOf(err.data.zodError).toMatchTypeOf<
z.typeToFlattenedError<any>
>();
expect(err.data?.zodError).toMatchInlineSnapshot(`
Object {
"fieldErrors": Object {},
"formErrors": Array [
"Number must be greater than or equal to 10",
],
}
`);
// good
expect(await ctx.proxy.greeting.query(10)).toBe(10);
});
});
|
5,169 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/errors.test.ts | /* eslint-disable @typescript-eslint/no-empty-function */
import http from 'http';
import { routerToServerAndClientNew, waitError } from './___testHelpers';
import {
createTRPCProxyClient,
httpBatchLink,
httpLink,
TRPCClientError,
TRPCLink,
} from '@trpc/client/src';
import { observable } from '@trpc/server/observable';
import * as trpc from '@trpc/server/src';
import { initTRPC } from '@trpc/server/src';
import { CreateHTTPContextOptions } from '@trpc/server/src/adapters/standalone';
import { TRPCError } from '@trpc/server/src/error/TRPCError';
import { getMessageFromUnknownError } from '@trpc/server/src/error/utils';
import { OnErrorFunction } from '@trpc/server/src/internals/types';
import { konn } from 'konn';
import fetch from 'node-fetch';
import { z, ZodError } from 'zod';
test('basic', async () => {
class MyError extends Error {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, MyError.prototype);
}
}
const t = initTRPC.create();
const router = t.router({
err: t.procedure.query(() => {
throw new MyError('woop');
}),
});
const onError = vi.fn();
const { close, proxy } = routerToServerAndClientNew(router, {
server: {
onError,
},
});
const clientError = await waitError(proxy.err.query(), TRPCClientError);
expect(clientError.shape.message).toMatchInlineSnapshot(`"woop"`);
expect(clientError.shape.code).toMatchInlineSnapshot(`-32603`);
expect(onError).toHaveBeenCalledTimes(1);
const serverError = onError.mock.calls[0]![0]!.error;
expect(serverError).toBeInstanceOf(TRPCError);
if (!(serverError instanceof TRPCError)) {
throw new Error('Wrong error');
}
expect(serverError.cause).toBeInstanceOf(MyError);
await close();
});
test('input error', async () => {
const onError = vi.fn();
const t = initTRPC.create();
const router = t.router({
err: t.procedure.input(z.string()).mutation(() => {
return null;
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
server: {
onError,
},
});
const clientError = await waitError(
proxy.err.mutate(1 as any),
TRPCClientError,
);
expect(clientError.shape.message).toMatchInlineSnapshot(`
"[
{
\\"code\\": \\"invalid_type\\",
\\"expected\\": \\"string\\",
\\"received\\": \\"number\\",
\\"path\\": [],
\\"message\\": \\"Expected string, received number\\"
}
]"
`);
expect(clientError.shape.code).toMatchInlineSnapshot(`-32600`);
expect(onError).toHaveBeenCalledTimes(1);
const serverError = onError.mock.calls[0]![0]!.error;
// if (!(serverError instanceof TRPCError)) {
// console.log('err', serverError);
// throw new Error('Wrong error');
// }
expect(serverError.cause).toBeInstanceOf(ZodError);
await close();
});
test('unauthorized()', async () => {
const onError = vi.fn();
const t = initTRPC.create();
const router = t.router({
err: t.procedure.query(() => {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
server: {
onError,
},
});
const clientError = await waitError(proxy.err.query(), TRPCClientError);
expect(clientError).toMatchInlineSnapshot(`[TRPCClientError: UNAUTHORIZED]`);
expect(onError).toHaveBeenCalledTimes(1);
const serverError = onError.mock.calls[0]![0]!.error;
expect(serverError).toBeInstanceOf(TRPCError);
await close();
});
test('getMessageFromUnknownError()', () => {
expect(getMessageFromUnknownError('test', 'nope')).toBe('test');
expect(getMessageFromUnknownError(1, 'test')).toBe('test');
expect(getMessageFromUnknownError({}, 'test')).toBe('test');
});
describe('formatError()', () => {
test('simple', async () => {
const onError = vi.fn();
const t = initTRPC.create({
errorFormatter({ shape, error }) {
if (error.cause instanceof ZodError) {
return {
...shape,
data: {
...shape.data,
type: 'zod' as const,
errors: error.cause.errors,
},
};
}
return shape;
},
});
const router = t.router({
err: t.procedure.input(z.string()).mutation(() => {
return null;
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
server: {
onError,
},
});
const clientError = await waitError(
proxy.err.mutate(1 as any),
TRPCClientError,
);
delete clientError.data.stack;
expect(clientError.data).toMatchInlineSnapshot(`
Object {
"code": "BAD_REQUEST",
"errors": Array [
Object {
"code": "invalid_type",
"expected": "string",
"message": "Expected string, received number",
"path": Array [],
"received": "number",
},
],
"httpStatus": 400,
"path": "err",
"type": "zod",
}
`);
expect(clientError.shape).toMatchInlineSnapshot(`
Object {
"code": -32600,
"data": Object {
"code": "BAD_REQUEST",
"errors": Array [
Object {
"code": "invalid_type",
"expected": "string",
"message": "Expected string, received number",
"path": Array [],
"received": "number",
},
],
"httpStatus": 400,
"path": "err",
"type": "zod",
},
"message": "[
{
\\"code\\": \\"invalid_type\\",
\\"expected\\": \\"string\\",
\\"received\\": \\"number\\",
\\"path\\": [],
\\"message\\": \\"Expected string, received number\\"
}
]",
}
`);
expect(onError).toHaveBeenCalledTimes(1);
const serverError = onError.mock.calls[0]![0]!.error;
expect(serverError.cause).toBeInstanceOf(ZodError);
await close();
});
test('double errors', async () => {
expect(() => {
trpc
.router()
.formatError(({ shape }) => {
return shape;
})
.formatError(({ shape }) => {
return shape;
});
}).toThrowErrorMatchingInlineSnapshot(
`"You seem to have double \`formatError()\`-calls in your router tree"`,
);
});
test('setting custom http response code', async () => {
const TEAPOT_ERROR_CODE = 418;
const onError = vi.fn();
const t = initTRPC.create({
errorFormatter: ({ error, shape }) => {
if (!(error.cause instanceof ZodError)) {
return shape;
}
return {
...shape,
data: {
...shape.data,
httpStatus: TEAPOT_ERROR_CODE,
},
};
},
});
const router = t.router({
q: t.procedure.input(z.string()).query(() => null),
});
const { close, httpUrl } = routerToServerAndClientNew(router, {
server: {
onError,
},
});
const res = await fetch(`${httpUrl}/q`);
expect(res.ok).toBeFalsy();
expect(res.status).toBe(TEAPOT_ERROR_CODE);
await close();
});
test('do not override response status set by middleware or resolver', async () => {
const TEAPOT_ERROR_CODE = 418;
const onError = vi.fn();
const t = initTRPC.context<CreateHTTPContextOptions>().create({});
const middleware = t.middleware(({ ctx }) => {
ctx.res.statusCode = TEAPOT_ERROR_CODE;
throw new Error('Some error');
});
const router = t.router({
q: t.procedure.use(middleware).query(() => null),
});
const { close, httpUrl } = routerToServerAndClientNew(router, {
server: {
onError,
},
});
const res = await fetch(`${httpUrl}/q`);
expect(res.ok).toBeFalsy();
expect(res.status).toBe(TEAPOT_ERROR_CODE);
await close();
});
});
test('make sure object is ignoring prototype', async () => {
const onError = vi.fn();
const t = initTRPC.create();
const router = t.router({
hello: t.procedure.query(() => 'there'),
});
const { close, proxy } = routerToServerAndClientNew(router, {
server: {
onError,
},
});
const clientError = await waitError(
(proxy as any).toString.query(),
TRPCClientError,
);
expect(clientError.shape.message).toMatchInlineSnapshot(
`"No \\"query\\"-procedure on path \\"toString\\""`,
);
expect(clientError.shape.code).toMatchInlineSnapshot(`-32004`);
expect(onError).toHaveBeenCalledTimes(1);
const serverError = onError.mock.calls[0]![0]!.error;
expect(serverError.code).toMatchInlineSnapshot(`"NOT_FOUND"`);
await close();
});
test('allow using built-in Object-properties', async () => {
const t = initTRPC.create();
const router = t.router({
toString: t.procedure.query(() => 'toStringValue'),
hasOwnProperty: t.procedure.query(() => 'hasOwnPropertyValue'),
});
const { close, proxy } = routerToServerAndClientNew(router);
expect(await proxy.toString.query()).toBe('toStringValue');
expect(await proxy.hasOwnProperty.query()).toBe('hasOwnPropertyValue');
await close();
});
test('retain stack trace', async () => {
class CustomError extends Error {
constructor() {
super('CustomError.msg');
this.name = 'CustomError';
Object.setPrototypeOf(this, new.target.prototype);
}
}
const onErrorFn: OnErrorFunction<any, any> = () => {};
const onError = vi.fn(onErrorFn);
const t = initTRPC.create();
const router = t.router({
hello: t.procedure.query(() => {
if (true) {
throw new CustomError();
}
return 'toStringValue';
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
server: {
onError,
},
});
const clientError = await waitError(() => proxy.hello.query());
expect(clientError.name).toBe('TRPCClientError');
expect(onError).toHaveBeenCalledTimes(1);
const serverOnErrorOpts = onError.mock.calls[0]![0]!;
const serverError = serverOnErrorOpts.error;
expect(serverError).toBeInstanceOf(TRPCError);
expect(serverError.cause).toBeInstanceOf(CustomError);
expect(serverError.stack).not.toContain('getErrorFromUnknown');
const stackParts = serverError.stack!.split('\n');
// first line of stack trace
expect(stackParts[1]).toContain(__filename);
await close();
});
describe('links have meta data about http failures', async () => {
type Handler = (opts: {
req: http.IncomingMessage;
res: http.ServerResponse;
}) => void;
function createServer(handler: Handler) {
const server = http.createServer((req, res) => {
handler({ req, res });
});
server.listen(0);
const port = (server.address() as any).port as number;
return {
url: `http://localhost:${port}`,
async close() {
await new Promise((resolve) => {
server.close(resolve);
});
},
};
}
const ctx = konn()
.beforeEach(() => {
return {
server: createServer(({ res }) => {
res.setHeader('content-type', 'application/json');
res.write(
JSON.stringify({
__error: {
foo: 'bar',
},
}),
);
res.end();
}),
};
})
.afterEach((opts) => {
opts.server?.close();
})
.done();
test('httpLink', async () => {
let meta = undefined as Record<string, unknown> | undefined;
const client: any = createTRPCProxyClient<any>({
links: [
() => {
return ({ next, op }) => {
return observable((observer) => {
const unsubscribe = next(op).subscribe({
error(err) {
observer.error(err);
meta = err.meta;
},
});
return unsubscribe;
});
};
},
httpLink({
url: ctx.server.url,
fetch: fetch as any,
}),
],
});
const error = await waitError(client.test.query(), TRPCClientError);
expect(error).toMatchInlineSnapshot(
`[TRPCClientError: Unable to transform response from server]`,
);
expect(meta).not.toBeUndefined();
expect(meta?.responseJSON).not.toBeFalsy();
expect(meta?.responseJSON).not.toBeFalsy();
expect(meta?.responseJSON).toMatchInlineSnapshot(`
Object {
"__error": Object {
"foo": "bar",
},
}
`);
});
test('httpBatchLink', async () => {
let meta = undefined as Record<string, unknown> | undefined;
const client: any = createTRPCProxyClient<any>({
links: [
() => {
return ({ next, op }) => {
return observable((observer) => {
const unsubscribe = next(op).subscribe({
error(err) {
observer.error(err);
meta = err.meta;
},
});
return unsubscribe;
});
};
},
httpBatchLink({
url: ctx.server.url,
fetch: fetch as any,
}),
],
});
const error = await waitError(client.test.query(), TRPCClientError);
expect(error).toMatchInlineSnapshot(
`[TRPCClientError: Unable to transform response from server]`,
);
expect(meta).not.toBeUndefined();
expect(meta?.responseJSON).not.toBeFalsy();
expect(meta?.responseJSON).not.toBeFalsy();
expect(meta?.responseJSON).toMatchInlineSnapshot(`
Object {
"__error": Object {
"foo": "bar",
},
}
`);
});
test('rethrow custom error', async () => {
type AppRouter = any;
class MyCustomError extends TRPCClientError<AppRouter> {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
}
}
function isObject(value: unknown): value is Record<string, unknown> {
// check that value is object
return !!value && !Array.isArray(value) && typeof value === 'object';
}
const customErrorLink: TRPCLink<AppRouter> = (_runtime) => (opts) =>
observable((observer) => {
const unsubscribe = opts.next(opts.op).subscribe({
error(err) {
if (
err.meta &&
isObject(err.meta.responseJSON) &&
'__error' in err.meta.responseJSON // <----- you need to modify this
) {
// custom error handling
observer.error(
new MyCustomError(
`custom error: ${JSON.stringify(
err.meta.responseJSON.__error,
)}`,
),
);
}
observer.error(err);
},
});
return unsubscribe;
});
const client: any = createTRPCProxyClient<any>({
links: [
customErrorLink,
httpLink({
url: ctx.server.url,
fetch: fetch as any,
}),
],
});
const error = await waitError(client.test.query());
expect(error).toMatchInlineSnapshot(
'[TRPCClientError: custom error: {"foo":"bar"}]',
);
expect(error).toBeInstanceOf(TRPCClientError);
expect(error).toBeInstanceOf(MyCustomError);
});
});
|
5,170 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/getUntypedClient.test.ts | import { getUntypedClient, TRPCUntypedClient } from '@trpc/client';
import { AnyRouter, initTRPC } from '@trpc/server';
import { konn } from 'konn';
import './___packages';
import { routerToServerAndClientNew } from './___testHelpers';
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
foo: t.procedure.query(() => 'bar'),
});
return routerToServerAndClientNew(appRouter);
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('getUntypedClient()', async () => {
const proxy = ctx.proxy;
expect(await proxy.foo.query()).toBe('bar');
const untyped = getUntypedClient(proxy);
type TRouter = typeof untyped extends TRPCUntypedClient<infer T> ? T : never;
expectTypeOf<TRouter>().toEqualTypeOf<typeof ctx.router>();
expectTypeOf<TRouter>().not.toEqualTypeOf<AnyRouter>();
expect(await untyped.query('foo')).toBe('bar');
});
|
5,171 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/headers.test.tsx | import { routerToServerAndClientNew } from './___testHelpers';
import {
createTRPCProxyClient,
httpBatchLink,
httpLink,
} from '@trpc/client/src';
import { Dict, initTRPC } from '@trpc/server/src';
describe('pass headers', () => {
type Context = {
headers: Dict<string[] | string>;
};
const t = initTRPC.context<Context>().create();
const appRouter = t.router({
hello: t.procedure.query(({ ctx }) => {
return {
'x-special': ctx.headers['x-special'],
};
}),
});
type AppRouter = typeof appRouter;
const { close, httpUrl } = routerToServerAndClientNew(appRouter, {
server: {
createContext(opts) {
return {
headers: opts.req.headers,
};
},
// createContext({ req }) {
// return { headers: req.headers };
// },
},
});
afterAll(async () => {
await close();
});
test('no headers', async () => {
const client = createTRPCProxyClient<AppRouter>({
links: [httpBatchLink({ url: httpUrl })],
});
expect(await client.hello.query()).toMatchInlineSnapshot(`Object {}`);
});
test('custom headers', async () => {
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: httpUrl,
headers() {
return {
'x-special': 'special header',
};
},
}),
],
});
expect(await client.hello.query()).toMatchInlineSnapshot(`
Object {
"x-special": "special header",
}
`);
});
test('async headers', async () => {
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: httpUrl,
async headers() {
return {
'x-special': 'async special header',
};
},
}),
],
});
expect(await client.hello.query()).toMatchInlineSnapshot(`
Object {
"x-special": "async special header",
}
`);
});
test('custom headers with context using httpBatchLink', async () => {
type LinkContext = {
headers: Dict<string[] | string>;
};
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: httpUrl,
headers(opts) {
return new Promise((resolve) => {
resolve({
'x-special': (opts.opList[0].context as LinkContext).headers[
'x-special'
],
});
});
},
}),
],
});
expect(
await client.hello.query(undefined, {
context: {
headers: {
'x-special': 'special header',
},
},
}),
).toMatchInlineSnapshot(`
Object {
"x-special": "special header",
}
`);
});
test('custom headers with context using httpLink', async () => {
type LinkContext = {
headers: Dict<string[] | string>;
};
const client = createTRPCProxyClient<AppRouter>({
links: [
httpLink({
url: httpUrl,
headers(opts) {
return {
'x-special': (opts.op.context as LinkContext).headers[
'x-special'
],
};
},
}),
],
});
expect(
await client.hello.query(undefined, {
context: {
headers: {
'x-special': 'special header',
},
},
}),
).toMatchInlineSnapshot(`
Object {
"x-special": "special header",
}
`);
});
});
|
5,172 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/index.test.ts | /* eslint-disable @typescript-eslint/no-empty-function */
import { routerToServerAndClientNew, waitError } from './___testHelpers';
import { waitFor } from '@testing-library/react';
import {
createTRPCProxyClient,
createWSClient,
httpBatchLink,
HTTPHeaders,
TRPCClientError,
wsLink,
} from '@trpc/client/src';
import { initTRPC, Maybe, TRPCError } from '@trpc/server/src';
import { CreateHTTPContextOptions } from '@trpc/server/src/adapters/standalone';
import { observable } from '@trpc/server/src/observable';
import { z } from 'zod';
test('smoke test', async () => {
const t = initTRPC.create();
const router = t.router({
hello: t.procedure.query(() => 'world'),
});
const { close, proxy } = routerToServerAndClientNew(router);
expect(await proxy.hello.query()).toBe('world');
await close();
});
test('mix query and mutation', async () => {
type Context = object;
const t = initTRPC.context<Context>().create();
const router = t.router({
q1: t.procedure.query(() => 'q1res'),
q2: t.procedure.input(z.object({ q2: z.string() })).query(() => 'q2res'),
m1: t.procedure.mutation(() => 'm1res'),
});
const caller = router.createCaller({});
expect(await caller.q1()).toMatchInlineSnapshot(`"q1res"`);
expect(await caller.q2({ q2: 'hey' })).toMatchInlineSnapshot(`"q2res"`);
expect(await caller.m1()).toMatchInlineSnapshot(`"m1res"`);
});
test('merge', async () => {
type Context = object;
const t = initTRPC.context<Context>().create();
const mergeRouters = t.mergeRouters;
const root = t.router({
helloo: t.procedure.query(() => 'world'),
});
const posts = t.router({
list: t.procedure.query(() => [{ text: 'initial' }]),
create: t.procedure.input(z.string()).mutation(({ input }) => {
return { text: input };
}),
});
const router = mergeRouters(root, posts);
const caller = router.createCaller({});
expect(await caller.list()).toMatchInlineSnapshot(`
Array [
Object {
"text": "initial",
},
]
`);
});
describe('integration tests', () => {
test('not found procedure', async () => {
const t = initTRPC.create();
const router = t.router({
hello: t.procedure
.input(z.object({ who: z.string() }).nullish())
.query(({ input }) => {
return {
text: `hello ${input?.who ?? 'world'}`,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const err = await waitError(
// @ts-expect-error - expected missing query
proxy.notfound.query('notFound' as any),
TRPCClientError,
);
expect(err.message).toMatchInlineSnapshot(
`"No \\"query\\"-procedure on path \\"notfound\\""`,
);
expect(err.shape?.message).toMatchInlineSnapshot(
`"No \\"query\\"-procedure on path \\"notfound\\""`,
);
await close();
});
test('invalid input', async () => {
const t = initTRPC.create();
const router = t.router({
hello: t.procedure
.input(z.object({ who: z.string() }).nullish())
.query(({ input }) => {
expectTypeOf(input).toMatchTypeOf<Maybe<{ who: string }>>();
return {
text: `hello ${input?.who ?? 'world'}`,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const err = await waitError(
proxy.hello.query({ who: 123 as any }),
TRPCClientError,
);
expect(err.shape?.code).toMatchInlineSnapshot(`-32600`);
expect(err.shape?.message).toMatchInlineSnapshot(`
"[
{
\\"code\\": \\"invalid_type\\",
\\"expected\\": \\"string\\",
\\"received\\": \\"number\\",
\\"path\\": [
\\"who\\"
],
\\"message\\": \\"Expected string, received number\\"
}
]"
`);
await close();
});
test('passing input to input w/o input', async () => {
const t = initTRPC.create();
const snap = vi.fn();
const router = t.router({
q: t.procedure.query(({ input }) => {
snap(input);
return { text: 'hello' };
}),
m: t.procedure.mutation(({ input }) => {
snap(input);
return { text: 'hello' };
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
await proxy.q.query();
await proxy.q.query(undefined);
await proxy.q.query(null as any); // treat null as undefined
await proxy.q.query('not-nullish' as any);
await proxy.m.mutate();
await proxy.m.mutate(undefined);
await proxy.m.mutate(null as any); // treat null as undefined
await proxy.m.mutate('not-nullish' as any);
expect(snap.mock.calls.every((call) => call[0] === undefined)).toBe(true);
await close();
});
describe('type testing', () => {
test('basic', async () => {
type Input = { who: string };
const t = initTRPC.create();
const router = t.router({
hello: t.procedure
.input(z.object({ who: z.string() }))
.query(({ input }) => {
expectTypeOf(input).not.toBeAny();
expectTypeOf(input).toMatchTypeOf<{ who: string }>();
return {
text: `hello ${input?.who ?? 'world'}`,
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const res = await proxy.hello.query({ who: 'katt' });
expectTypeOf(res.input).toMatchTypeOf<Input>();
expectTypeOf(res.input).not.toBeAny();
expectTypeOf(res).toMatchTypeOf<{ input: Input; text: string }>();
expect(res.text).toEqual('hello katt');
await close();
});
test('mixed response', async () => {
const t = initTRPC.create();
const router = t.router({
postById: t.procedure.input(z.number()).query(({ input }) => {
if (input === 1) {
return {
id: 1,
title: 'helloo',
};
}
if (input === 2) {
return { id: 2, title: 'test' };
}
return null;
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const res = await proxy.postById.query(1);
expectTypeOf(res).toMatchTypeOf<{ id: number; title: string } | null>();
expect(res).toEqual({
id: 1,
title: 'helloo',
});
await close();
});
test('propagate ctx', async () => {
type Context = {
user?: {
id: number;
name: string;
};
};
const headers: HTTPHeaders = {};
function createContext({ req }: CreateHTTPContextOptions): Context {
if (req.headers.authorization !== 'kattsecret') {
return {};
}
return {
user: {
id: 1,
name: 'KATT',
},
};
}
const t = initTRPC.context<Context>().create();
const router = t.router({
whoami: t.procedure.query(({ ctx }) => {
if (!ctx.user) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return ctx.user;
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
server: {
createContext,
},
client({ httpUrl }) {
return {
links: [
httpBatchLink({
headers,
url: httpUrl,
}),
],
};
},
});
// no auth, should fail
{
const err = await waitError(proxy.whoami.query(), TRPCClientError);
expect(err.shape.message).toMatchInlineSnapshot(`"UNAUTHORIZED"`);
}
// auth, should work
{
headers.authorization = 'kattsecret';
const res = await proxy.whoami.query();
expectTypeOf(res).toMatchTypeOf<{ id: number; name: string }>();
expect(res).toEqual({
id: 1,
name: 'KATT',
});
}
await close();
});
test('optional input', async () => {
type Input = Maybe<{ who: string }>;
const t = initTRPC.create();
const router = t.router({
hello: t.procedure
.input(z.object({ who: z.string() }).nullish())
.query(({ input }) => {
expectTypeOf(input).not.toBeAny();
expectTypeOf(input).toMatchTypeOf<Input>();
return {
text: `hello ${input?.who ?? 'world'}`,
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
{
const res = await proxy.hello.query({ who: 'katt' });
expectTypeOf(res.input).toMatchTypeOf<Input>();
expectTypeOf(res.input).not.toBeAny();
}
{
const res = await proxy.hello.query();
expectTypeOf(res.input).toMatchTypeOf<Input>();
expectTypeOf(res.input).not.toBeAny();
}
await close();
});
test('mutation', async () => {
type Input = Maybe<{ who: string }>;
const t = initTRPC.create();
const router = t.router({
hello: t.procedure
.input(
z
.object({
who: z.string(),
})
.nullish(),
)
.mutation(({ input }) => {
expectTypeOf(input).not.toBeAny();
expectTypeOf(input).toMatchTypeOf<Input>();
return {
text: `hello ${input?.who ?? 'world'}`,
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const res = await proxy.hello.mutate({ who: 'katt' });
expectTypeOf(res.input).toMatchTypeOf<Input>();
expectTypeOf(res.input).not.toBeAny();
expect(res.text).toBe('hello katt');
await close();
});
});
});
describe('createCaller()', () => {
type Context = object;
const t = initTRPC.context<Context>().create();
const router = t.router({
q: t.procedure.input(z.number()).query(({ input }) => {
return { input };
}),
m: t.procedure.input(z.number()).mutation(({ input }) => {
return { input };
}),
sub: t.procedure.input(z.number()).subscription(({ input }) => {
return observable<{ input: typeof input }>((emit) => {
emit.next({ input });
return () => {
// noop
};
});
}),
});
test('query()', async () => {
const data = await router.createCaller({}).q(1);
expectTypeOf(data).toMatchTypeOf<{ input: number }>();
expect(data).toEqual({ input: 1 });
});
test('mutation()', async () => {
const data = await router.createCaller({}).m(2);
expectTypeOf(data).toMatchTypeOf<{ input: number }>();
expect(data).toEqual({ input: 2 });
});
test('subscription()', async () => {
const subObservable = await router.createCaller({}).sub(3);
await new Promise<void>((resolve) => {
subObservable.subscribe({
next(data: { input: number }) {
expect(data).toEqual({ input: 3 });
expectTypeOf(data).toMatchTypeOf<{ input: number }>();
resolve();
},
});
});
});
});
describe('createCaller()', () => {
type Context = object;
const t = initTRPC.context<Context>().create();
const router = t.router({
q: t.procedure.input(z.number()).query(({ input }) => {
return { input };
}),
m: t.procedure.input(z.number()).mutation(({ input }) => {
return { input };
}),
sub: t.procedure.input(z.number()).subscription(({ input }) => {
return observable<{ input: typeof input }>((emit) => {
emit.next({ input });
return () => {
// noop
};
});
}),
});
test('query()', async () => {
const data = await router.createCaller({}).q(1);
expectTypeOf(data).toMatchTypeOf<{ input: number }>();
expect(data).toEqual({ input: 1 });
});
test('mutation()', async () => {
const data = await router.createCaller({}).m(2);
expectTypeOf(data).toMatchTypeOf<{ input: number }>();
expect(data).toEqual({ input: 2 });
});
test('subscription()', async () => {
const subObservable = await router.createCaller({}).sub(3);
await new Promise<void>((resolve) => {
subObservable.subscribe({
next(data: { input: number }) {
expect(data).toEqual({ input: 3 });
expectTypeOf(data).toMatchTypeOf<{ input: number }>();
resolve();
},
});
});
});
});
// regression https://github.com/trpc/trpc/issues/527
test('void mutation response', async () => {
const t = initTRPC.create();
const newRouter = t.router({
undefined: t.procedure.mutation(() => {}),
null: t.procedure.mutation(() => null),
});
const { close, proxy, wssPort, router } =
routerToServerAndClientNew(newRouter);
expect(await proxy.undefined.mutate()).toMatchInlineSnapshot(`undefined`);
expect(await proxy.null.mutate()).toMatchInlineSnapshot(`null`);
const ws = createWSClient({
url: `ws://localhost:${wssPort}`,
WebSocket: WebSocket as any,
});
const wsClient = createTRPCProxyClient<typeof router>({
links: [wsLink({ client: ws })],
});
expect(await wsClient.undefined.mutate()).toMatchInlineSnapshot(`undefined`);
expect(await wsClient.null.mutate()).toMatchInlineSnapshot(`null`);
ws.close();
await close();
});
// https://github.com/trpc/trpc/issues/559
describe('ObservableAbortError', () => {
test('cancelling request should throw ObservableAbortError', async () => {
const t = initTRPC.create();
const router = t.router({
slow: t.procedure.query(async () => {
await new Promise((resolve) => setTimeout(resolve, 500));
return null;
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const onReject = vi.fn();
const ac = new AbortController();
const req = proxy.slow.query(undefined, {
signal: ac.signal,
});
req.catch(onReject);
// cancel after 10ms
await new Promise((resolve) => setTimeout(resolve, 5));
ac.abort();
await waitFor(() => {
expect(onReject).toHaveBeenCalledTimes(1);
});
const err = onReject.mock.calls[0]![0]! as TRPCClientError<any>;
expect(err.name).toBe('TRPCClientError');
expect(err.cause?.name).toBe('ObservableAbortError');
await close();
});
test('cancelling batch request should throw AbortError', async () => {
// aborting _one_ batch request doesn't necessarily mean we cancel the reqs part of that batch
const t = initTRPC.create();
const router = t.router({
slow1: t.procedure.query(async () => {
await new Promise((resolve) => setTimeout(resolve, 500));
return 'slow1';
}),
slow2: t.procedure.query(async () => {
await new Promise((resolve) => setTimeout(resolve, 500));
return 'slow2';
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
server: {
batching: {
enabled: true,
},
},
client({ httpUrl }) {
return {
links: [httpBatchLink({ url: httpUrl })],
};
},
});
const ac = new AbortController();
const req1 = proxy.slow1.query(undefined, { signal: ac.signal });
const req2 = proxy.slow2.query();
const onReject1 = vi.fn();
req1.catch(onReject1);
await new Promise((resolve) => setTimeout(resolve, 5));
ac.abort();
await waitFor(() => {
expect(onReject1).toHaveBeenCalledTimes(1);
});
const err = onReject1.mock.calls[0]![0]! as TRPCClientError<any>;
expect(err).toBeInstanceOf(TRPCClientError);
expect(err.cause?.name).toBe('ObservableAbortError');
expect(await req2).toBe('slow2');
await close();
});
});
test('regression: JSON.stringify([undefined]) gives [null] causes wrong type to procedure input', async () => {
const t = initTRPC.create();
const router = t.router({
q: t.procedure.input(z.string().optional()).query(({ input }) => {
return { input };
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
client({ httpUrl }) {
return {
links: [httpBatchLink({ url: httpUrl })],
};
},
server: {
batching: {
enabled: true,
},
},
});
expect(await proxy.q.query('foo')).toMatchInlineSnapshot(`
Object {
"input": "foo",
}
`);
expect(await proxy.q.query()).toMatchInlineSnapshot(`Object {}`);
await close();
});
describe('apply()', () => {
test('query without input', async () => {
const t = initTRPC.create();
const router = t.router({
hello: t.procedure.query(() => 'world'),
});
const { close, proxy } = routerToServerAndClientNew(router);
expect(await proxy.hello.query.apply(undefined)).toBe('world');
await close();
});
test('query with input', async () => {
const t = initTRPC.create();
const router = t.router({
helloinput: t.procedure
.input(z.string())
.query(({ input }) => `hello ${input}`),
});
const { close, proxy } = routerToServerAndClientNew(router);
expect(await proxy.helloinput.query.apply(undefined, ['world'])).toBe(
'hello world',
);
await close();
});
});
|
5,173 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/inferenceHelpers.test.ts | import { inferRouterInputs, inferRouterOutputs, initTRPC } from '@trpc/server';
import { z } from 'zod';
const t = initTRPC.create();
const roomProcedure = t.procedure.input(
z.object({
roomId: z.string(),
}),
);
const appRouter = t.router({
getRoom: roomProcedure.query(({ input }) => {
return {
id: input.roomId,
name: 'This is my room',
type: 'Best Room',
};
}),
sendMessage: roomProcedure
.input(
z.object({
text: z.string(),
optionalKey: z.string().min(1).optional(),
}),
)
.mutation(({ input }) => {
if (input.optionalKey) {
return { ...input, testField: 'heyo' };
}
return input;
}),
sendMessage2: roomProcedure
.input(
z.object({
text: z.string(),
}),
)
.mutation(({ input }) => {
// ^?
input.roomId;
input.text;
return input;
}),
});
type AppRouter = typeof appRouter;
describe('inferRouterInputs', () => {
type AppRouterInputs = inferRouterInputs<AppRouter>;
test('happy path', async () => {
type Input = AppRouterInputs['getRoom'];
expectTypeOf({ roomId: 'abcd' }).toEqualTypeOf<Input>();
});
test('happy path with optional fields', async () => {
type Input = AppRouterInputs['sendMessage'];
expectTypeOf({ roomId: 'abcd', text: 'testing' }).toMatchTypeOf<Input>();
});
test('sad path', async () => {
type Input = AppRouterInputs['sendMessage2'];
expectTypeOf({ roomId: 2, text: 'testing' }).not.toEqualTypeOf<Input>();
});
});
describe('inferRouterOutputs', () => {
type AppRouterOutputs = inferRouterOutputs<AppRouter>;
test('happy path', async () => {
type Output = AppRouterOutputs['getRoom'];
expectTypeOf({
id: 'abcd',
name: 'This is my room, too',
type: 'Best Room part 2',
}).toEqualTypeOf<Output>();
});
test('happy path with optional fields', async () => {
type Output = AppRouterOutputs['sendMessage'];
expectTypeOf({
roomId: 'abcd',
text: 'testing 1',
}).toMatchTypeOf<Output>();
expectTypeOf({
roomId: 'abcd',
text: 'testing 2',
optionalKey: 'this is optional',
}).toMatchTypeOf<Output>();
expectTypeOf({
roomId: 'abcd',
text: 'testing 3',
optionalKey: 'this is optional',
testField: 'hey',
}).toMatchTypeOf<Output>();
expectTypeOf({
roomId: 'abcd',
text: 'testing 3',
testField: 'hey',
}).toMatchTypeOf<Output>();
});
test('sad path', async () => {
type Output = AppRouterOutputs['sendMessage2'];
expectTypeOf({ roomId: 2, text: 'testing' }).not.toEqualTypeOf<Output>();
});
});
|
5,174 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/initTRPC.test.ts | import {
DataTransformerOptions,
DefaultDataTransformer,
initTRPC,
} from '@trpc/server/src';
test('default transformer', () => {
const t = initTRPC
.context<{
foo: 'bar';
}>()
.create();
const router = t.router({});
expectTypeOf<typeof router._def._config.$types.ctx>().toMatchTypeOf<{
foo: 'bar';
}>();
expectTypeOf(t._config.transformer).toMatchTypeOf<DefaultDataTransformer>();
expectTypeOf(
router._def._config.transformer,
).toMatchTypeOf<DefaultDataTransformer>();
});
test('custom transformer', () => {
const transformer: DataTransformerOptions = {
deserialize: (v) => v,
serialize: (v) => v,
};
const t = initTRPC.create({
transformer,
});
const router = t.router({});
expectTypeOf(
router._def._config.transformer,
).toMatchTypeOf<DataTransformerOptions>();
expectTypeOf(
router._def._config.transformer,
).not.toMatchTypeOf<DefaultDataTransformer>();
});
test('meta typings', () => {
type Meta = { __META__: true };
const meta: Meta = { __META__: true };
const t = initTRPC.meta<Meta>().create();
const procedure = t.procedure.meta(meta);
expect(procedure._def.meta).toBe(meta);
expectTypeOf(procedure._def.meta).toMatchTypeOf<Meta | undefined>();
});
test('config types', () => {
{
const t = initTRPC.create();
t._config;
// ^?
expectTypeOf<typeof t._config.$types.ctx>().toEqualTypeOf<object>();
expectTypeOf<typeof t._config.$types.meta>().toEqualTypeOf<object>();
// eslint-disable-next-line @typescript-eslint/ban-types
expectTypeOf<typeof t._config.$types.meta>().toEqualTypeOf<{}>();
// eslint-disable-next-line @typescript-eslint/ban-types
expectTypeOf<typeof t._config.$types.meta>().toEqualTypeOf<{}>();
}
{
type Meta = {
foo: 'bar';
};
type Context = {
bar: 'foo';
};
const t = initTRPC.meta<Meta>().context<Context>().create();
// ^?
expectTypeOf<typeof t._config.$types.ctx>().toEqualTypeOf<Context>();
expectTypeOf<typeof t._config.$types.meta>().toEqualTypeOf<Meta>();
}
{
const {
_config: { $types },
} = initTRPC.create();
// @ts-expect-error mock unknown key
expect(() => $types.unknown).toThrow(
`Tried to access "$types.unknown" which is not available at runtime`,
);
}
});
test('detect server env', () => {
expect(() => initTRPC.create({ isServer: false })).toThrow(
`You're trying to use @trpc/server in a non-server environment. This is not supported by default.`,
);
expect(() =>
initTRPC.create({ isServer: false, allowOutsideOfServer: true }),
).not.toThrowError();
});
test('context function type', () => {
const createContext = () => ({
foo: 'bar' as const,
});
const t = initTRPC.context<typeof createContext>().create();
expectTypeOf<typeof t._config.$types.ctx>().toMatchTypeOf<{
foo: 'bar';
}>();
});
test('context async function type', () => {
const createContext = async () => ({
foo: 'bar' as const,
});
const t = initTRPC.context<typeof createContext>().create();
expectTypeOf<typeof t._config.$types.ctx>().toMatchTypeOf<{
foo: 'bar';
}>();
});
|
5,175 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/input.test.ts | import { routerToServerAndClientNew, waitError } from './___testHelpers';
import { createTRPCProxyClient, TRPCClientError } from '@trpc/client';
import {
inferProcedureInput,
inferProcedureParams,
initTRPC,
} from '@trpc/server';
import { UnsetMarker } from '@trpc/server/core/internals/utils';
import { konn } from 'konn';
import { z, ZodError } from 'zod';
const ignoreErrors = async (fn: () => unknown) => {
try {
await fn();
} catch {
// ignore
}
};
describe('double input validator', () => {
const t = initTRPC.create({
errorFormatter({ shape, error }) {
return {
...shape,
data: {
...shape.data,
zod: error.cause instanceof ZodError ? error.cause.flatten() : null,
},
};
},
});
const roomProcedure = t.procedure.input(
z.object({
roomId: z.string(),
}),
);
const appRouter = t.router({
sendMessage: roomProcedure
.input(
z.object({
text: z.string(),
optionalKey: z.string().optional(),
}),
)
.mutation(({ input }) => {
return input;
}),
sendMessage2: roomProcedure
.input(
z.object({
text: z.string(),
}),
)
.mutation(({ input }) => {
// ^?
input.roomId;
input.text;
return input;
}),
});
type AppRouter = typeof appRouter;
const ctx = konn()
.beforeEach(() => {
const opts = routerToServerAndClientNew(appRouter);
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('happy path', async () => {
type Input = inferProcedureInput<AppRouter['sendMessage']>;
const data: Input = {
roomId: '123',
text: 'hello',
};
const result = await ctx.proxy.sendMessage.mutate(data);
expect(result).toEqual(data);
expectTypeOf(result).toMatchTypeOf(data);
});
test('sad path', async () => {
type Input = inferProcedureInput<AppRouter['sendMessage']>;
{
// @ts-expect-error missing input params
const input: Input = {
roomId: '',
};
const error = await waitError<TRPCClientError<AppRouter>>(
ctx.proxy.sendMessage.mutate(input),
TRPCClientError,
);
expect(error.data).toHaveProperty('zod');
expect(error.data!.zod!.fieldErrors).toMatchInlineSnapshot(`
Object {
"text": Array [
"Required",
],
}
`);
}
{
// @ts-expect-error missing input params
const input: Input = {
text: '',
};
const error = await waitError<TRPCClientError<AppRouter>>(
ctx.proxy.sendMessage.mutate(input),
TRPCClientError,
);
expect(error.data!.zod!.fieldErrors).toMatchInlineSnapshot(`
Object {
"roomId": Array [
"Required",
],
}
`);
}
});
});
test('only allow double input validator for object-like inputs', () => {
const t = initTRPC.create();
try {
t.procedure.input(z.literal('hello')).input(
// @ts-expect-error first one wasn't an object-like thingy
z.object({
foo: z.string(),
}),
);
} catch {
// whatever
}
try {
t.procedure
.input(
z.object({
foo: z.string(),
}),
)
.input(
// @ts-expect-error second one wasn't an object-like thingy
z.literal('bar'),
);
} catch {
// whatever
}
});
describe('multiple input validators with optionals', () => {
const t = initTRPC.create();
const webhookProc = t.procedure.input(
z
.object({
id: z.string(),
eventTypeId: z.number().optional(),
})
.optional(),
);
test('2nd parser also optional => merged optional', async () => {
const webhookRouter = t.router({
byId: webhookProc
.input(
z
.object({
webhookId: z.string(),
})
.optional(),
)
.query(({ input }) => {
expectTypeOf(input).toEqualTypeOf<
| {
id: string;
eventTypeId?: number;
webhookId: string;
}
| undefined
>();
return input;
}),
});
const opts = routerToServerAndClientNew(webhookRouter);
await expect(opts.proxy.byId.query()).resolves.toBeUndefined();
await expect(opts.proxy.byId.query(undefined)).resolves.toBeUndefined();
await expect(
opts.proxy.byId.query({ id: '123', webhookId: '456' }),
).resolves.toMatchObject({
id: '123',
webhookId: '456',
});
await opts.close();
});
test('2nd parser required => merged required', async () => {
const webhookRouter = t.router({
byId: webhookProc
.input(
z.object({
webhookId: z.string(),
}),
)
.query(({ input }) => {
expectTypeOf(input).toEqualTypeOf<{
id: string;
eventTypeId?: number;
webhookId: string;
}>();
return input;
}),
});
const opts = routerToServerAndClientNew(webhookRouter);
await expect(
opts.proxy.byId.query({ id: '123', webhookId: '456' }),
).resolves.toMatchObject({
id: '123',
webhookId: '456',
});
// @ts-expect-error - missing id and webhookId
await expect(opts.proxy.byId.query()).rejects.toThrow();
// @ts-expect-error - missing id and webhookId
await expect(opts.proxy.byId.query(undefined)).rejects.toThrow();
await expect(
opts.proxy.byId.query({ id: '123', eventTypeId: 1, webhookId: '456' }),
).resolves.toMatchObject({
id: '123',
eventTypeId: 1,
webhookId: '456',
});
await opts.close();
});
test('with optional keys', async () => {
const webhookRouter = t.router({
byId: webhookProc
.input(
z.object({
webhookId: z.string(),
foo: z.string().optional(),
}),
)
.query(({ input }) => {
expectTypeOf(input).toEqualTypeOf<{
id: string;
eventTypeId?: number;
webhookId: string;
foo?: string;
}>();
return input;
}),
});
const opts = routerToServerAndClientNew(webhookRouter);
await expect(
opts.proxy.byId.query({ id: '123', webhookId: '456' }),
).resolves.toMatchObject({
id: '123',
webhookId: '456',
});
await expect(
opts.proxy.byId.query({ id: '123', webhookId: '456', foo: 'bar' }),
).resolves.toMatchObject({
id: '123',
webhookId: '456',
foo: 'bar',
});
await opts.close();
});
test('cannot chain optional to required', async () => {
try {
t.procedure
.input(z.object({ foo: z.string() }))
// @ts-expect-error cannot chain optional to required
.input(z.object({ bar: z.number() }).optional());
} catch {
// whatever
}
});
});
test('no input', async () => {
const t = initTRPC.create();
const proc = t.procedure.query(({ input }) => {
expectTypeOf(input).toBeUndefined();
expect(input).toBeUndefined();
return input;
});
type ProcType = inferProcedureParams<typeof proc>;
expectTypeOf<ProcType['_input_in']>().toEqualTypeOf<UnsetMarker>();
expectTypeOf<ProcType['_input_out']>().toEqualTypeOf<UnsetMarker>();
expectTypeOf<ProcType['_output_in']>().toBeUndefined();
expectTypeOf<ProcType['_output_out']>().toBeUndefined();
const router = t.router({
proc,
});
const opts = routerToServerAndClientNew(router);
await expect(opts.proxy.proc.query()).resolves.toBeUndefined();
await opts.close();
});
test('zod default() string', async () => {
const t = initTRPC.create();
const proc = t.procedure
.input(z.string().default('bar'))
.query(({ input }) => {
expectTypeOf(input).toBeString();
return input;
});
type ProcType = inferProcedureParams<typeof proc>;
expectTypeOf<ProcType['_input_in']>().toEqualTypeOf<string | undefined>();
expectTypeOf<ProcType['_input_out']>().toEqualTypeOf<string>();
const router = t.router({
proc,
});
const opts = routerToServerAndClientNew(router);
await expect(opts.proxy.proc.query()).resolves.toBe('bar');
await expect(opts.proxy.proc.query('hello')).resolves.toBe('hello');
await opts.close();
});
test('zod default() required object', async () => {
const t = initTRPC.create();
const proc = t.procedure
.input(
z.object({
foo: z.string().optional().default('foo'),
}),
)
.query(({ input }) => {
expectTypeOf(input).toBeObject();
return input;
});
type ProcType = inferProcedureParams<typeof proc>;
expectTypeOf<ProcType['_input_in']>().toEqualTypeOf<{ foo?: string }>();
expectTypeOf<ProcType['_input_out']>().toEqualTypeOf<{ foo: string }>();
const router = t.router({
proc,
});
const opts = routerToServerAndClientNew(router);
await expect(opts.proxy.proc.query({ foo: 'bar' })).resolves.toEqual({
foo: 'bar',
});
await expect(opts.proxy.proc.query({})).resolves.toEqual({ foo: 'foo' });
await opts.close();
});
test('zod default() mixed default object', async () => {
const t = initTRPC.create();
const proc = t.procedure
.input(
z
.object({
foo: z.string(),
bar: z.string().optional().default('barFoo'),
})
.optional()
.default({ foo: 'fooBar' }),
)
.query(({ input }) => {
expectTypeOf(input).toBeObject();
return input;
});
type ProcType = inferProcedureParams<typeof proc>;
expectTypeOf<ProcType['_input_in']>().toEqualTypeOf<
{ foo: string; bar?: string } | undefined
>();
expectTypeOf<ProcType['_input_out']>().toEqualTypeOf<{
foo: string;
bar: string;
}>();
const router = t.router({
proc,
});
const opts = routerToServerAndClientNew(router);
await expect(
opts.proxy.proc.query({ foo: 'bar', bar: 'foo' }),
).resolves.toEqual({ foo: 'bar', bar: 'foo' });
await expect(opts.proxy.proc.query({ foo: 'fooFoo' })).resolves.toEqual({
foo: 'fooFoo',
bar: 'barFoo',
});
await expect(opts.proxy.proc.query({ foo: 'bar' })).resolves.toEqual({
foo: 'bar',
bar: 'barFoo',
});
await expect(opts.proxy.proc.query(undefined)).resolves.toEqual({
foo: 'fooBar',
bar: 'barFoo',
});
await opts.close();
});
test('zod default() defaults within object', async () => {
const t = initTRPC.create();
const proc = t.procedure
.input(
z
.object({
foo: z.string().optional().default('defaultFoo'),
bar: z.string().optional().default('defaultBar'),
})
.optional()
.default({}),
)
.query(({ input }) => {
expectTypeOf(input).toBeObject();
return input;
});
type ProcType = inferProcedureParams<typeof proc>;
expectTypeOf<ProcType['_input_in']>().toEqualTypeOf<
{ foo?: string; bar?: string } | undefined
>();
expectTypeOf<ProcType['_input_out']>().toEqualTypeOf<{
foo: string;
bar: string;
}>();
const router = t.router({
proc,
});
const opts = routerToServerAndClientNew(router);
await expect(
opts.proxy.proc.query({ foo: 'bar', bar: 'foo' }),
).resolves.toEqual({ foo: 'bar', bar: 'foo' });
await expect(opts.proxy.proc.query(undefined)).resolves.toEqual({
foo: 'defaultFoo',
bar: 'defaultBar',
});
await opts.close();
});
test('double validators with undefined', async () => {
const t = initTRPC.create();
{
const roomProcedure = t.procedure.input(
z.object({
roomId: z.string(),
}),
);
const proc = roomProcedure
.input(
z.object({
optionalKey: z.string().optional(),
}),
)
.mutation(({ input }) => {
return input;
});
type Input = inferProcedureParams<typeof proc>['_input_in'];
expectTypeOf<Input>().toEqualTypeOf<{
roomId: string;
optionalKey?: string;
}>();
const router = t.router({
proc,
});
const client = createTRPCProxyClient<typeof router>({
links: [],
});
await ignoreErrors(() =>
client.proc.mutate({
roomId: 'foo',
}),
);
}
{
const roomProcedure = t.procedure.input(
z.object({
roomId: z.string().optional(),
}),
);
const proc = roomProcedure
.input(
z.object({
key: z.string(),
}),
)
.mutation(({ input }) => {
return input;
});
type Input = inferProcedureParams<typeof proc>['_input_in'];
expectTypeOf<Input>().toEqualTypeOf<{
roomId?: string;
key: string;
}>();
const router = t.router({
proc,
});
const client = createTRPCProxyClient<typeof router>({
links: [],
});
await ignoreErrors(() =>
client.proc.mutate({
key: 'string',
}),
);
}
});
test('merges optional with required property', async () => {
const t = initTRPC.create();
const router = t.router({
proc: t.procedure
.input(
z.object({
id: z.string(),
}),
)
.input(
z.object({
id: z.string().optional(),
}),
)
.query(() => 'hi'),
});
type Input = inferProcedureInput<(typeof router)['proc']>;
// ^?
expectTypeOf<Input>().toEqualTypeOf<{ id: string }>();
const client = createTRPCProxyClient<typeof router>({
links: [],
});
await ignoreErrors(async () => {
// @ts-expect-error id is not optional
await client.proc.query({});
await client.proc.query({ id: 'foo' });
});
});
|
5,176 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/isDev.test.ts | import { routerToServerAndClientNew, waitError } from './___testHelpers';
import { TRPCClientError } from '@trpc/client/src';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
const createTestContext = (opts: { isDev: boolean }) =>
konn()
.beforeEach(() => {
const t = initTRPC.create({ isDev: opts.isDev });
const appRouter = t.router({
failingMutation: t.procedure.mutation(() => {
if (Math.random() < 2) {
throw new Error('Always fails');
}
return 'hello';
}),
});
const res = routerToServerAndClientNew(appRouter);
return res;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
describe('isDev:true', () => {
const ctx = createTestContext({ isDev: true });
test('prints stacks', async () => {
const error = (await waitError(
() => ctx.proxy.failingMutation.mutate(),
TRPCClientError,
)) as TRPCClientError<typeof ctx.router>;
expect(error.data?.stack?.split('\n')[0]).toMatchInlineSnapshot(
`"Error: Always fails"`,
);
});
});
describe('isDev:false', () => {
const ctx = createTestContext({ isDev: false });
test('does not print stack', async () => {
const error = (await waitError(
() => ctx.proxy.failingMutation.mutate(),
TRPCClientError,
)) as TRPCClientError<typeof ctx.router>;
expect(error.data?.stack).toBeUndefined();
});
});
|
5,177 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/jsonify.test.ts | import { routerToServerAndClientNew } from './___testHelpers';
import { initTRPC } from '@trpc/server';
import { konn } from 'konn';
import superjson from 'superjson';
describe('no transformer specified', () => {
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create();
const appRouter = t.router({
happy: t.procedure.query(() => {
return {
map: new Map<string, string>([['foo', 'bar']]),
set: new Set<string>(['foo', 'bar']),
date: new Date(0),
fn: () => {
return 'hello';
},
arrayWithUndefined: [1, undefined, 2],
};
}),
});
const opts = routerToServerAndClientNew(appRouter);
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('it works', async () => {
const result = await ctx.proxy.happy.query();
expectTypeOf(result).not.toBeAny();
expectTypeOf(result.date).toBeString();
result.set;
// ^?
result.map;
// ^?
expectTypeOf(result).toMatchTypeOf<{
date: string;
map: object;
set: object;
}>();
expectTypeOf(result.arrayWithUndefined);
// ^?
expect(result).toMatchInlineSnapshot(`
Object {
"arrayWithUndefined": Array [
1,
null,
2,
],
"date": "1970-01-01T00:00:00.000Z",
"map": Object {},
"set": Object {},
}
`);
});
});
describe('with transformer specified', () => {
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create({
transformer: superjson,
});
const appRouter = t.router({
happy: t.procedure.query(() => ({
map: new Map<string, string>([['foo', 'bar']]),
set: new Set<string>(['foo', 'bar']),
date: new Date(0),
fn: () => {
return 'hello';
},
arrayWithUndefined: [1, undefined, 2],
})),
});
const opts = routerToServerAndClientNew(appRouter);
return opts;
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
test('it works', async () => {
const result = await ctx.proxy.happy.query();
expectTypeOf(result.date).toEqualTypeOf<Date>();
result.set;
// ^?
result.map;
// ^?
expectTypeOf(result).toMatchTypeOf<{
date: Date;
map: Map<string, string>;
set: Set<string>;
}>();
// ^?
expect(result).toMatchInlineSnapshot(`
Object {
"json": Object {
"arrayWithUndefined": Array [
1,
null,
2,
],
"date": "1970-01-01T00:00:00.000Z",
"map": Array [
Array [
"foo",
"bar",
],
],
"set": Array [
"foo",
"bar",
],
},
"meta": Object {
"values": Object {
"arrayWithUndefined.1": Array [
"undefined",
],
"date": Array [
"Date",
],
"map": Array [
"map",
],
"set": Array [
"set",
],
},
},
}
`);
});
});
|
5,178 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/links.test.ts | import { routerToServerAndClientNew } from './___testHelpers';
import {
createTRPCProxyClient,
httpBatchLink,
httpLink,
loggerLink,
OperationLink,
TRPCClientError,
TRPCClientRuntime,
unstable_httpBatchStreamLink,
} from '@trpc/client/src';
import { createChain } from '@trpc/client/src/links/internals/createChain';
import { retryLink } from '@trpc/client/src/links/internals/retryLink';
import { AnyRouter, initTRPC } from '@trpc/server/src';
import { observable, observableToPromise } from '@trpc/server/src/observable';
import { z } from 'zod';
const mockRuntime: TRPCClientRuntime = {
transformer: {
serialize: (v) => v,
deserialize: (v) => v,
},
combinedTransformer: {
input: {
serialize: (v) => v,
deserialize: (v) => v,
},
output: {
serialize: (v) => v,
deserialize: (v) => v,
},
},
};
test('chainer', async () => {
let attempt = 0;
const serverCall = vi.fn();
const t = initTRPC.create();
const router = t.router({
hello: t.procedure.query(({}) => {
attempt++;
serverCall();
if (attempt < 3) {
throw new Error('Err ' + attempt);
}
return 'world';
}),
});
const { httpPort, close } = routerToServerAndClientNew(router);
const chain = createChain({
links: [
retryLink({ attempts: 3 })(mockRuntime),
httpLink({
url: `http://localhost:${httpPort}`,
})(mockRuntime),
],
op: {
id: 1,
type: 'query',
path: 'hello',
input: null,
context: {},
},
});
const result = await observableToPromise(chain).promise;
expect(result?.context?.response).toBeTruthy();
result.context!.response = '[redacted]' as any;
expect(result).toMatchInlineSnapshot(`
Object {
"context": Object {
"response": "[redacted]",
"responseJSON": Object {
"result": Object {
"data": "world",
},
},
},
"result": Object {
"data": "world",
"type": "data",
},
}
`);
expect(serverCall).toHaveBeenCalledTimes(3);
await close();
});
test('cancel request', async () => {
const onDestroyCall = vi.fn();
const chain = createChain({
links: [
() =>
observable(() => {
return () => {
onDestroyCall();
};
}),
],
op: {
id: 1,
type: 'query',
path: 'hello',
input: null,
context: {},
},
});
chain.subscribe({}).unsubscribe();
expect(onDestroyCall).toHaveBeenCalled();
});
describe('batching', () => {
test('query batching', async () => {
const metaCall = vi.fn();
const t = initTRPC.create();
const router = t.router({
hello: t.procedure.input(z.string().nullish()).query(({ input }) => {
return `hello ${input ?? 'world'}`;
}),
});
const { httpPort, close } = routerToServerAndClientNew(router, {
server: {
createContext() {
metaCall();
return {};
},
batching: {
enabled: true,
},
},
});
const links = [
httpBatchLink({
url: `http://localhost:${httpPort}`,
})(mockRuntime),
];
const chain1 = createChain({
links,
op: {
id: 1,
type: 'query',
path: 'hello',
input: null,
context: {},
},
});
const chain2 = createChain({
links,
op: {
id: 2,
type: 'query',
path: 'hello',
input: 'alexdotjs',
context: {},
},
});
const results = await Promise.all([
observableToPromise(chain1).promise,
observableToPromise(chain2).promise,
]);
for (const res of results) {
expect(res?.context?.response).toBeTruthy();
res.context!.response = '[redacted]';
}
expect(results).toMatchInlineSnapshot(`
Array [
Object {
"context": Object {
"response": "[redacted]",
"responseJSON": Array [
Object {
"result": Object {
"data": "hello world",
},
},
Object {
"result": Object {
"data": "hello alexdotjs",
},
},
],
},
"result": Object {
"data": "hello world",
"type": "data",
},
},
Object {
"context": Object {
"response": "[redacted]",
"responseJSON": Array [
Object {
"result": Object {
"data": "hello world",
},
},
Object {
"result": Object {
"data": "hello alexdotjs",
},
},
],
},
"result": Object {
"data": "hello alexdotjs",
"type": "data",
},
},
]
`);
expect(metaCall).toHaveBeenCalledTimes(1);
await close();
});
test('query streaming', async () => {
const metaCall = vi.fn();
const t = initTRPC.create();
const router = t.router({
deferred: t.procedure
.input(
z.object({
wait: z.number(),
}),
)
.query(async (opts) => {
await new Promise<void>((resolve) =>
setTimeout(resolve, opts.input.wait * 10),
);
return opts.input.wait;
}),
});
const { httpPort, close } = routerToServerAndClientNew(router, {
server: {
createContext() {
metaCall();
return {};
},
batching: {
enabled: true,
},
},
});
const links = [
unstable_httpBatchStreamLink({
url: `http://localhost:${httpPort}`,
})(mockRuntime),
];
const chain1 = createChain({
links,
op: {
id: 1,
type: 'query',
path: 'deferred',
input: { wait: 2 },
context: {},
},
});
const chain2 = createChain({
links,
op: {
id: 2,
type: 'query',
path: 'deferred',
input: { wait: 1 },
context: {},
},
});
const results = await Promise.all([
observableToPromise(chain1).promise,
observableToPromise(chain2).promise,
]);
for (const res of results) {
expect(res?.context?.response).toBeTruthy();
res.context!.response = '[redacted]';
}
expect(results).toMatchInlineSnapshot(`
Array [
Object {
"context": Object {
"response": "[redacted]",
},
"result": Object {
"data": 2,
"type": "data",
},
},
Object {
"context": Object {
"response": "[redacted]",
},
"result": Object {
"data": 1,
"type": "data",
},
},
]
`);
expect(metaCall).toHaveBeenCalledTimes(1);
await close();
});
test('batching on maxURLLength', async () => {
const createContextFn = vi.fn();
const t = initTRPC.create();
const appRouter = t.router({
['big-input']: t.procedure.input(z.string()).query(({ input }) => {
return input.length;
}),
});
const { proxy, httpUrl, close, router } = routerToServerAndClientNew(
appRouter,
{
server: {
createContext() {
createContextFn();
return {};
},
batching: {
enabled: true,
},
},
client: (opts) => ({
links: [
httpBatchLink({
url: opts.httpUrl,
maxURLLength: 2083,
}),
],
}),
},
);
{
// queries should be batched into a single request
// url length: 118 < 2083
const res = await Promise.all([
proxy['big-input'].query('*'.repeat(10)),
proxy['big-input'].query('*'.repeat(10)),
]);
expect(res).toEqual([10, 10]);
expect(createContextFn).toBeCalledTimes(1);
createContextFn.mockClear();
}
{
// queries should be sent and individual requests
// url length: 2146 > 2083
const res = await Promise.all([
proxy['big-input'].query('*'.repeat(1024)),
proxy['big-input'].query('*'.repeat(1024)),
]);
expect(res).toEqual([1024, 1024]);
expect(createContextFn).toBeCalledTimes(2);
createContextFn.mockClear();
}
{
// queries should be batched into a single request
// url length: 2146 < 9999
const clientWithBigMaxURLLength = createTRPCProxyClient<typeof router>({
links: [httpBatchLink({ url: httpUrl, maxURLLength: 9999 })],
});
const res = await Promise.all([
clientWithBigMaxURLLength['big-input'].query('*'.repeat(1024)),
clientWithBigMaxURLLength['big-input'].query('*'.repeat(1024)),
]);
expect(res).toEqual([1024, 1024]);
expect(createContextFn).toBeCalledTimes(1);
}
await close();
});
test('server not configured for batching', async () => {
const serverCall = vi.fn();
const t = initTRPC.create();
const appRouter = t.router({
hello: t.procedure.query(({}) => {
serverCall();
return 'world';
}),
});
const { close, router, httpPort, trpcClientOptions } =
routerToServerAndClientNew(appRouter, {
server: {
batching: {
enabled: false,
},
},
});
const client = createTRPCProxyClient<typeof router>({
...trpcClientOptions,
links: [
httpBatchLink({
url: `http://localhost:${httpPort}`,
headers: {},
}),
],
});
await expect(client.hello.query()).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Batching is not enabled on the server]`,
);
await close();
});
});
test('create client with links', async () => {
let attempt = 0;
const serverCall = vi.fn();
const t = initTRPC.create();
const appRouter = t.router({
hello: t.procedure.query(({}) => {
attempt++;
serverCall();
if (attempt < 3) {
throw new Error('Err ' + attempt);
}
return 'world';
}),
});
const { close, router, httpPort, trpcClientOptions } =
routerToServerAndClientNew(appRouter);
const client = createTRPCProxyClient<typeof router>({
...trpcClientOptions,
links: [
retryLink({ attempts: 3 }),
httpLink({
url: `http://localhost:${httpPort}`,
headers: {},
}),
],
});
const result = await client.hello.query();
expect(result).toBe('world');
await close();
});
describe('loggerLink', () => {
const logger = {
error: vi.fn(),
log: vi.fn(),
};
const logLink = loggerLink({
console: logger,
})(mockRuntime);
const okLink: OperationLink<AnyRouter> = () =>
observable((o) => {
o.next({
result: {
type: 'data',
data: undefined,
},
});
});
const errorLink: OperationLink<AnyRouter> = () =>
observable((o) => {
o.error(new TRPCClientError('..'));
});
beforeEach(() => {
logger.error.mockReset();
logger.log.mockReset();
});
test('query', () => {
createChain({
links: [logLink, okLink],
op: {
id: 1,
type: 'query',
input: null,
path: 'n/a',
context: {},
},
})
.subscribe({})
.unsubscribe();
expect(logger.log.mock.calls).toHaveLength(2);
expect(logger.log.mock.calls[0]![0]!).toMatchInlineSnapshot(
`"%c >> query #1 %cn/a%c %O"`,
);
expect(logger.log.mock.calls[0]![1]!).toMatchInlineSnapshot(`
"
background-color: #72e3ff;
color: black;
padding: 2px;
"
`);
});
test('subscription', () => {
createChain({
links: [logLink, okLink],
op: {
id: 1,
type: 'subscription',
input: null,
path: 'n/a',
context: {},
},
})
.subscribe({})
.unsubscribe();
expect(logger.log.mock.calls[0]![0]!).toMatchInlineSnapshot(
`"%c >> subscription #1 %cn/a%c %O"`,
);
expect(logger.log.mock.calls[1]![0]!).toMatchInlineSnapshot(
`"%c << subscription #1 %cn/a%c %O"`,
);
});
test('mutation', () => {
createChain({
links: [logLink, okLink],
op: {
id: 1,
type: 'mutation',
input: null,
path: 'n/a',
context: {},
},
})
.subscribe({})
.unsubscribe();
expect(logger.log.mock.calls[0]![0]!).toMatchInlineSnapshot(
`"%c >> mutation #1 %cn/a%c %O"`,
);
expect(logger.log.mock.calls[1]![0]!).toMatchInlineSnapshot(
`"%c << mutation #1 %cn/a%c %O"`,
);
});
test('query 2', () => {
createChain({
links: [logLink, errorLink],
op: {
id: 1,
type: 'query',
input: null,
path: 'n/a',
context: {},
},
})
.subscribe({})
.unsubscribe();
expect(logger.log.mock.calls[0]![0]!).toMatchInlineSnapshot(
`"%c >> query #1 %cn/a%c %O"`,
);
expect(logger.error.mock.calls[0]![0]!).toMatchInlineSnapshot(
`"%c << query #1 %cn/a%c %O"`,
);
});
test('ansi color mode', () => {
const logger = {
error: vi.fn(),
log: vi.fn(),
};
createChain({
links: [
loggerLink({ console: logger, colorMode: 'ansi' })(mockRuntime),
okLink,
],
op: {
id: 1,
type: 'query',
input: null,
path: 'n/a',
context: {},
},
})
.subscribe({})
.unsubscribe();
expect(logger.log.mock.calls[0]![0]!).toMatchInlineSnapshot(
`"\x1b[30;46m >> query \x1b[1;30;46m #1 n/a \x1b[0m"`,
);
expect(logger.log.mock.calls[1]![0]!).toMatchInlineSnapshot(
`"\x1b[97;46m << query \x1b[1;97;46m #1 n/a \x1b[0m"`,
);
});
test('custom logger', () => {
const logFn = vi.fn();
createChain({
links: [loggerLink({ logger: logFn })(mockRuntime), errorLink],
op: {
id: 1,
type: 'query',
input: null,
path: 'n/a',
context: {},
},
})
.subscribe({})
.unsubscribe();
const [firstCall, secondCall] = logFn.mock.calls.map((args) => args[0]);
expect(firstCall).toMatchInlineSnapshot(`
Object {
"context": Object {},
"direction": "up",
"id": 1,
"input": null,
"path": "n/a",
"type": "query",
}
`);
// omit elapsedMs
const { elapsedMs, ...other } = secondCall;
expect(typeof elapsedMs).toBe('number');
expect(other).toMatchInlineSnapshot(`
Object {
"context": Object {},
"direction": "down",
"id": 1,
"input": null,
"path": "n/a",
"result": [TRPCClientError: ..],
"type": "query",
}
`);
});
});
test('chain makes unsub', async () => {
const firstLinkUnsubscribeSpy = vi.fn();
const firstLinkCompleteSpy = vi.fn();
const secondLinkUnsubscribeSpy = vi.fn();
const t = initTRPC.create();
const appRouter = t.router({
hello: t.procedure.query(({}) => {
return 'world';
}),
});
const { proxy, close } = routerToServerAndClientNew(appRouter, {
client() {
return {
links: [
() =>
({ next, op }) =>
observable((observer) => {
next(op).subscribe({
error(err) {
observer.error(err);
},
next(v) {
observer.next(v);
},
complete() {
firstLinkCompleteSpy();
observer.complete();
},
});
return () => {
firstLinkUnsubscribeSpy();
observer.complete();
};
}),
() => () =>
observable((observer) => {
observer.next({
result: {
type: 'data',
data: 'world',
},
});
observer.complete();
return () => {
secondLinkUnsubscribeSpy();
};
}),
],
};
},
});
expect(await proxy.hello.query()).toBe('world');
expect(firstLinkCompleteSpy).toHaveBeenCalledTimes(1);
expect(firstLinkUnsubscribeSpy).toHaveBeenCalledTimes(1);
expect(secondLinkUnsubscribeSpy).toHaveBeenCalledTimes(1);
await close();
});
test('init with URL object', async () => {
const serverCall = vi.fn();
const t = initTRPC.create();
const router = t.router({
hello: t.procedure.query(({}) => {
serverCall();
return 'world';
}),
});
const { httpPort, close } = routerToServerAndClientNew(router);
const url = new URL(`http://localhost:${httpPort}`);
const chain = createChain({
links: [httpLink({ url: url })(mockRuntime)],
op: {
id: 1,
type: 'query',
path: 'hello',
input: null,
context: {},
},
});
const result = await observableToPromise(chain).promise;
expect(result?.context?.response).toBeTruthy();
result.context!.response = '[redacted]' as any;
expect(result).toMatchInlineSnapshot(`
Object {
"context": Object {
"response": "[redacted]",
"responseJSON": Object {
"result": Object {
"data": "world",
},
},
},
"result": Object {
"data": "world",
"type": "data",
},
}
`);
expect(serverCall).toHaveBeenCalledTimes(1);
await close();
});
|
5,179 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/meta.test.ts | import { routerToServerAndClientNew } from './___testHelpers';
import { initTRPC } from '@trpc/server/src';
import { konn } from 'konn';
test('meta is undefined in a middleware', () => {
type Meta = {
permissions: string[];
};
const t = initTRPC.meta<Meta>().create();
t.middleware((opts) => {
expectTypeOf(opts.meta).toEqualTypeOf<Meta | undefined>();
return opts.next();
});
});
describe('meta', () => {
type Meta = {
foo: 'bar';
};
const t = initTRPC.meta<Meta>().create();
const ctx = konn()
.beforeEach(() => {
const middlewareCalls = vi.fn((_opts: Meta | undefined) => {
// noop
});
const baseProc = t.procedure.use(({ next, meta }) => {
middlewareCalls(meta);
return next();
});
const appRouter = t.router({
withMeta: baseProc
.meta({
foo: 'bar',
})
.query(() => {
return null;
}),
noMeta: baseProc.query(() => {
return null;
}),
});
const opts = routerToServerAndClientNew(appRouter);
return { ...opts, middlewareCalls };
})
.afterEach(async (ctx) => {
await ctx?.close?.();
})
.done();
it('is available in middlewares', async () => {
await ctx.proxy.noMeta.query();
await ctx.proxy.withMeta.query();
await ctx.proxy.noMeta.query();
await ctx.proxy.withMeta.query();
expect(ctx.middlewareCalls.mock.calls.map((calls) => calls[0])).toEqual([
undefined,
{ foo: 'bar' },
undefined,
{ foo: 'bar' },
]);
});
it('is queryable in _def', async () => {
const meta = ctx.router.withMeta._def.meta;
expectTypeOf(meta).toEqualTypeOf<Meta | undefined>();
expect(meta).toEqual({
foo: 'bar',
});
});
});
|
5,180 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/middlewares.test.ts | import {
experimental_standaloneMiddleware,
initTRPC,
TRPCError,
} from '@trpc/server/src';
import * as z from 'zod';
test('decorate independently', () => {
type User = {
id: string;
name: string;
};
type Context = {
user: User;
};
const t = initTRPC.context<Context>().create();
const fooMiddleware = t.middleware((opts) => {
expectTypeOf(opts.ctx.user).toEqualTypeOf<User>();
return opts.next({
ctx: {
// ...opts.ctx,
foo: 'foo' as const,
},
});
});
const barMiddleware = fooMiddleware.unstable_pipe((opts) => {
expectTypeOf(opts.ctx).toEqualTypeOf<{
user: User;
foo: 'foo';
}>();
return opts.next({
ctx: {
bar: 'bar' as const,
},
});
});
const bazMiddleware = barMiddleware.unstable_pipe((opts) => {
expectTypeOf(opts.ctx).toEqualTypeOf<{
user: User;
foo: 'foo';
bar: 'bar';
}>();
return opts.next({
ctx: {
baz: 'baz' as const,
},
});
});
t.procedure.use(bazMiddleware).query(({ ctx }) => {
expectTypeOf(ctx).toEqualTypeOf<{
user: User;
foo: 'foo';
bar: 'bar';
baz: 'baz';
}>();
});
});
test('standalone middlewares that define the ctx/input they require and can be used in different tRPC instances', () => {
type Human = {
id: string;
name: string;
};
type HumanContext = {
user: Human;
};
const tHuman = initTRPC.context<HumanContext>().create();
type Alien = {
id: string;
name: Buffer; // aliens have weird names
};
type AlienContext = {
user: Alien;
planet: 'mars' | 'venus';
};
const tAlien = initTRPC.context<AlienContext>().create();
const addFooToCtxMiddleware = experimental_standaloneMiddleware().create(
(opts) => {
expectTypeOf(opts.ctx).toEqualTypeOf<object>();
return opts.next({
ctx: {
foo: 'foo' as const,
},
});
},
);
const addUserNameLengthToCtxMiddleware = experimental_standaloneMiddleware<{
ctx: { user: Human | Alien };
}>().create((opts) => {
expectTypeOf(opts.ctx).toEqualTypeOf<{
user: Human | Alien;
}>();
return opts.next({
ctx: {
nameLength: opts.ctx.user.name.length,
},
});
});
const determineIfUserNameIsLongMiddleware =
experimental_standaloneMiddleware<{
ctx: { nameLength: number };
}>().create((opts) => {
expectTypeOf(opts.ctx).toEqualTypeOf<{
nameLength: number;
}>();
return opts.next({
ctx: {
nameIsLong: opts.ctx.nameLength > 10,
},
});
});
const mapUserToUserTypeMiddleware = experimental_standaloneMiddleware<{
ctx: { user: Human | Alien };
}>().create((opts) => {
expectTypeOf(opts.ctx).toEqualTypeOf<{
user: Human | Alien;
}>();
return opts.next({
ctx: {
user:
typeof opts.ctx.user.name === 'string'
? ('human' as const)
: ('alien' as const),
},
});
});
// This is not OK because determineIfUserNameIsLongMiddleware requires { nameLength: number } which is not in either context:
tHuman.procedure.use(
// @ts-expect-error: no user in context
determineIfUserNameIsLongMiddleware,
);
tAlien.procedure.use(
// @ts-expect-error: no user in context
determineIfUserNameIsLongMiddleware,
);
// This is not OK because determineIfUserNameIsLongMiddleware requires { nameLength: number } which is not in HumanContext & { foo: string }
tHuman.procedure
.use(addFooToCtxMiddleware)
// @ts-expect-error: no nameLength in context
.use(determineIfUserNameIsLongMiddleware);
// This is OK because the context provides { user: Human } or { user: Alien } which is what addUserNameLengthToCtx requires
tHuman.procedure
.use(addFooToCtxMiddleware)
.use(addUserNameLengthToCtxMiddleware)
// determineIfUserNameIsLongMiddleware only needs { nameLength: number }, so overwriting user is fine
.use(mapUserToUserTypeMiddleware)
.use(determineIfUserNameIsLongMiddleware)
.query(({ ctx }) => {
expectTypeOf(ctx).toEqualTypeOf<{
user: 'human' | 'alien';
nameLength: number;
nameIsLong: boolean;
foo: 'foo';
}>();
});
tAlien.procedure
.use(addFooToCtxMiddleware)
.use(addUserNameLengthToCtxMiddleware)
// determineIfUserNameIsLongMiddleware only needs { nameLength: number }, so overwriting user is fine
.use(mapUserToUserTypeMiddleware)
.use(determineIfUserNameIsLongMiddleware)
.query(({ ctx }) => {
expectTypeOf(ctx).toEqualTypeOf<{
user: 'human' | 'alien';
nameLength: number;
nameIsLong: boolean;
planet: 'mars' | 'venus';
foo: 'foo';
}>();
});
addFooToCtxMiddleware
// This is not OK because the requirements of the later middlewares are not met
// @ts-expect-error: No user in context at this point
.unstable_pipe(addUserNameLengthToCtxMiddleware)
// @ts-expect-error: No user in context at this point
.unstable_pipe(mapUserToUserTypeMiddleware)
.unstable_pipe(determineIfUserNameIsLongMiddleware);
const requireUserAndAddFooToCtxMiddleware =
experimental_standaloneMiddleware<{
ctx: { user: Human | Alien };
}>().create((opts) => {
expectTypeOf(opts.ctx).toEqualTypeOf<{
user: Human | Alien;
}>();
return opts.next({
ctx: {
foo: 'foo' as const,
},
});
});
const validPipedVersion = requireUserAndAddFooToCtxMiddleware
.unstable_pipe(addUserNameLengthToCtxMiddleware)
.unstable_pipe(mapUserToUserTypeMiddleware)
.unstable_pipe(determineIfUserNameIsLongMiddleware);
tHuman.procedure.use(validPipedVersion).query(({ ctx }) => {
expectTypeOf(ctx).toEqualTypeOf<{
user: 'human' | 'alien';
nameLength: number;
nameIsLong: boolean;
foo: 'foo';
}>();
});
tAlien.procedure.use(validPipedVersion).query(({ ctx }) => {
expectTypeOf(ctx).toEqualTypeOf<{
user: 'human' | 'alien';
nameLength: number;
nameIsLong: boolean;
planet: 'mars' | 'venus';
foo: 'foo';
}>();
});
// Middleware chain using standalone middleware that requires a particular 'input' shape
const ensureMagicNumberIsNotLongerThanNameLength =
experimental_standaloneMiddleware<{
ctx: { nameLength: number };
input: { magicNumber: number };
}>().create((opts) => {
expectTypeOf(opts.ctx).toEqualTypeOf<{
nameLength: number;
}>();
expectTypeOf(opts.input).toEqualTypeOf<{
magicNumber: number;
}>();
if (opts.input.magicNumber > opts.ctx.nameLength) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: 'magicNumber is too high',
});
}
return opts.next();
});
// This is not OK because the input is not compatible with the middleware (magicNumber must always be number)
tHuman.procedure
.input(z.object({ magicNumber: z.number().optional() }))
.use(addUserNameLengthToCtxMiddleware)
// @ts-expect-error: magicNumber is required
.use(ensureMagicNumberIsNotLongerThanNameLength);
// This is OK because the input is compatible with the middleware
tHuman.procedure
.input(z.object({ magicNumber: z.number() }))
.use(addUserNameLengthToCtxMiddleware)
.use(ensureMagicNumberIsNotLongerThanNameLength)
.query(({ input, ctx }) => {
expectTypeOf(ctx).toEqualTypeOf<{
user: Human;
nameLength: number;
}>();
expectTypeOf(input).toEqualTypeOf<{
magicNumber: number;
}>();
});
// Middleware that defines a particular 'meta' shape
const shamefullyLogIfProcedureIsNotCoolMiddleware =
experimental_standaloneMiddleware<{
meta: {
cool: boolean;
};
}>().create((opts) => {
expectTypeOf(opts.meta).toEqualTypeOf<
| {
cool: boolean;
}
| undefined
>();
if (!opts.meta?.cool) {
globalThis.console.log('This procedure is not cool');
}
return opts.next();
});
// This is not OK because the meta is not compatible with the middleware (cool must always be boolean)
const tHumanWithWrongMeta = initTRPC
.context<HumanContext>()
.meta<{ cool: string }>()
.create();
tHumanWithWrongMeta.procedure
.meta({ cool: 'true' })
// @ts-expect-error: cool must be boolean
.use(shamefullyLogIfProcedureIsNotCoolMiddleware);
// This is OK because the meta is compatible with the middleware
const tHumanWithMeta = initTRPC
.context<HumanContext>()
.meta<{ cool: boolean }>()
.create();
tHumanWithMeta.procedure
.meta({ cool: false })
.use(shamefullyLogIfProcedureIsNotCoolMiddleware);
// Works without the .meta() addition as well, since Meta is always a union with undefined
tHumanWithMeta.procedure.use(shamefullyLogIfProcedureIsNotCoolMiddleware);
});
test('pipe middlewares - inlined', async () => {
const t = initTRPC
.context<{
init: 'init';
}>()
.create();
const fooMiddleware = t.middleware((opts) => {
return opts.next({
ctx: {
foo: 'foo' as const,
},
});
});
const barMiddleware = fooMiddleware.unstable_pipe((opts) => {
expectTypeOf(opts.ctx).toMatchTypeOf<{
foo: 'foo';
}>();
return opts.next({
ctx: {
bar: 'bar' as const,
},
});
});
const bazMiddleware = barMiddleware.unstable_pipe((opts) => {
expectTypeOf(opts.ctx).toMatchTypeOf<{
foo: 'foo';
bar: 'bar';
}>();
return opts.next({
ctx: {
baz: 'baz' as const,
},
});
});
const testProcedure = t.procedure.use(bazMiddleware);
const router = t.router({
test: testProcedure.query(({ ctx }) => {
expect(ctx).toEqual({
init: 'init',
foo: 'foo',
bar: 'bar',
baz: 'baz',
});
expectTypeOf(ctx).toEqualTypeOf<{
init: 'init';
foo: 'foo';
bar: 'bar';
baz: 'baz';
}>();
return ctx;
}),
});
const caller = router.createCaller({
init: 'init',
});
expect(await caller.test()).toMatchInlineSnapshot(`
Object {
"bar": "bar",
"baz": "baz",
"foo": "foo",
"init": "init",
}
`);
});
test('pipe middlewares - standalone', async () => {
const t = initTRPC
.context<{
init: 'init';
}>()
.create();
const fooMiddleware = t.middleware((opts) => {
return opts.next({
ctx: {
foo: 'foo' as const,
},
});
});
const barMiddleware = t.middleware((opts) => {
return opts.next({
ctx: {
bar: 'bar' as const,
},
});
});
const bazMiddleware = fooMiddleware
.unstable_pipe(barMiddleware)
.unstable_pipe((opts) => {
expectTypeOf(opts.ctx).toMatchTypeOf<{
foo: 'foo';
bar: 'bar';
}>();
return opts.next({
ctx: {
baz: 'baz' as const,
},
});
});
const testProcedure = t.procedure.use(bazMiddleware);
const router = t.router({
test: testProcedure.query(({ ctx }) => {
expect(ctx).toEqual({
init: 'init',
foo: 'foo',
bar: 'bar',
baz: 'baz',
});
expectTypeOf(ctx).toEqualTypeOf<{
init: 'init';
foo: 'foo';
bar: 'bar';
baz: 'baz';
}>();
return ctx;
}),
});
const caller = router.createCaller({
init: 'init',
});
expect(await caller.test()).toMatchInlineSnapshot(`
Object {
"bar": "bar",
"baz": "baz",
"foo": "foo",
"init": "init",
}
`);
});
test('pipe middlewares - failure', async () => {
const t = initTRPC
.context<{
init: {
a: 'a';
b: 'b';
c: {
d: 'd';
e: 'e';
};
};
}>()
.create();
const fooMiddleware = t.middleware((opts) => {
expectTypeOf(opts.ctx).toMatchTypeOf<{
init: { a: 'a'; b: 'b'; c: { d: 'd'; e: 'e' } };
}>();
opts.ctx.init.a;
return opts.next({
ctx: {
init: { a: 'a' as const },
foo: 'foo' as const,
},
});
});
const barMiddleware = t.middleware((opts) => {
expectTypeOf(opts.ctx).toMatchTypeOf<{
init: { a: 'a'; b: 'b'; c: { d: 'd'; e: 'e' } };
}>();
return opts.next({
ctx: {
bar: 'bar' as const,
},
});
});
// @ts-expect-error barMiddleware accessing invalid property
const bazMiddleware = fooMiddleware.unstable_pipe(barMiddleware);
const testProcedure = t.procedure.use(bazMiddleware);
testProcedure.query(({ ctx }) => {
expectTypeOf(ctx).toEqualTypeOf<{
init: { a: 'a' };
foo: 'foo';
bar: 'bar';
}>();
});
});
test('pipe middlewares - override', async () => {
const t = initTRPC
.context<{
init: {
foundation: 'foundation';
};
}>()
.create();
const fooMiddleware = t.middleware((opts) => {
return opts.next({
ctx: {
init: 'override' as const,
foo: 'foo' as const,
},
});
});
const barMiddleware = fooMiddleware.unstable_pipe((opts) => {
// @ts-expect-error foundation has been overwritten
opts.ctx.init.foundation;
expectTypeOf(opts.ctx).toMatchTypeOf<{
init: 'override';
foo: 'foo';
}>();
return opts.next({
ctx: {
bar: 'bar' as const,
},
});
});
const testProcedure = t.procedure.use(barMiddleware);
const router = t.router({
test: testProcedure.query(({ ctx }) => {
expect(ctx).toEqual({
init: 'override',
foo: 'foo',
bar: 'bar',
});
expectTypeOf(ctx).toEqualTypeOf<{
init: 'override';
foo: 'foo';
bar: 'bar';
}>();
return ctx;
}),
});
const caller = router.createCaller({
init: {
foundation: 'foundation',
},
});
expect(await caller.test()).toMatchInlineSnapshot(`
Object {
"bar": "bar",
"foo": "foo",
"init": "override",
}
`);
});
test('pipe middlewares - failure', async () => {
const t = initTRPC
.context<{
init: {
a: 'a';
b: 'b';
};
}>()
.create();
const fooMiddleware = t.middleware((opts) => {
return opts.next({
ctx: {
init: 'override' as const,
foo: 'foo' as const,
},
});
});
const barMiddleware = fooMiddleware.unstable_pipe((opts) => {
expectTypeOf(opts.ctx).toMatchTypeOf<{
init: 'override';
foo: 'foo';
}>();
return opts.next({
ctx: {
bar: 'bar' as const,
},
});
});
const testProcedure = t.procedure.use(barMiddleware);
const router = t.router({
test: testProcedure.query(({ ctx }) => {
expect(ctx).toEqual({
init: 'override',
foo: 'foo',
bar: 'bar',
});
expectTypeOf(ctx).toEqualTypeOf<{
init: 'override';
foo: 'foo';
bar: 'bar';
}>();
return ctx;
}),
});
const caller = router.createCaller({
init: {
a: 'a',
b: 'b',
},
});
expect(await caller.test()).toMatchInlineSnapshot(`
Object {
"bar": "bar",
"foo": "foo",
"init": "override",
}
`);
});
test('meta', () => {
type Meta = {
permissions: string[];
};
const t = initTRPC.meta<Meta>().create();
t.middleware(({ meta, next }) => {
expectTypeOf(meta).toMatchTypeOf<Meta | undefined>();
return next();
});
});
|
5,181 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/outputParser.test.ts | import { routerToServerAndClientNew } from './___testHelpers';
import { wrap } from '@decs/typeschema';
import { initTRPC } from '@trpc/server/src';
import myzod from 'myzod';
import * as t from 'superstruct';
import * as v from 'valibot';
import * as yup from 'yup';
import { z } from 'zod';
test('zod', async () => {
const trpc = initTRPC.create();
const router = trpc.router({
q: trpc.procedure
.input(z.string().or(z.number()))
.output(
z.object({
input: z.string(),
}),
)
.query(({ input }) => {
return { input: input as string };
}),
});
const { proxy, close } = routerToServerAndClientNew(router);
const output = await proxy.q.query('foobar');
expectTypeOf(output.input).toBeString();
expect(output).toMatchInlineSnapshot(`
Object {
"input": "foobar",
}
`);
await expect(proxy.q.query(1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('zod async', async () => {
const trpc = initTRPC.create();
const router = trpc.router({
q: trpc.procedure
.input(z.string().or(z.number()))
.output(
z
.object({
input: z.string(),
})
.refine(async (value) => !!value),
)
.query(({ input }) => {
return { input: input as string };
}),
});
const { proxy, close } = routerToServerAndClientNew(router);
const output = await proxy.q.query('foobar');
expectTypeOf(output.input).toBeString();
expect(output).toMatchInlineSnapshot(`
Object {
"input": "foobar",
}
`);
await expect(proxy.q.query(1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('zod transform', async () => {
const trpc = initTRPC.create();
const router = trpc.router({
q: trpc.procedure
.input(z.string().or(z.number()))
.output(
z.object({
input: z.string().transform((s) => s.length),
}),
)
.query(({ input }) => {
return { input: input as string };
}),
});
const { proxy, close } = routerToServerAndClientNew(router);
const output = await proxy.q.query('foobar');
expectTypeOf(output.input).toBeNumber();
expect(output).toMatchInlineSnapshot(`
Object {
"input": 6,
}
`);
await expect(proxy.q.query(1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('valibot', async () => {
const trpc = initTRPC.create();
const router = trpc.router({
q: trpc.procedure
.input(wrap(v.union([v.string(), v.number()])))
.output(wrap(v.object({ input: v.string() })))
.query(({ input }) => {
return { input: input as string };
}),
});
const { proxy, close } = routerToServerAndClientNew(router);
const output = await proxy.q.query('foobar');
expectTypeOf(output.input).toBeString();
expect(output).toMatchInlineSnapshot(`
Object {
"input": "foobar",
}
`);
await expect(proxy.q.query(1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('valibot async', async () => {
const trpc = initTRPC.create();
const router = trpc.router({
q: trpc.procedure
.input(wrap(v.unionAsync([v.stringAsync(), v.numberAsync()])))
.output(
wrap(
v.objectAsync({ input: v.stringAsync() }, [
v.customAsync(async (value) => !!value),
]),
),
)
.query(({ input }) => {
return { input: input as string };
}),
});
const { proxy, close } = routerToServerAndClientNew(router);
const output = await proxy.q.query('foobar');
expectTypeOf(output.input).toBeString();
expect(output).toMatchInlineSnapshot(`
Object {
"input": "foobar",
}
`);
await expect(proxy.q.query(1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('valibot transform', async () => {
const trpc = initTRPC.create();
const router = trpc.router({
q: trpc.procedure
.input(wrap(v.union([v.string(), v.number()])))
.output(
wrap(
v.object({
input: v.transform(v.string(), (s) => s.length),
}),
),
)
.query(({ input }) => {
return { input: input as string };
}),
});
const { proxy, close } = routerToServerAndClientNew(router);
const output = await proxy.q.query('foobar');
expectTypeOf(output.input).toBeNumber();
expect(output).toMatchInlineSnapshot(`
Object {
"input": 6,
}
`);
await expect(proxy.q.query(1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('superstruct', async () => {
const trpc = initTRPC.create();
const router = trpc.router({
q: trpc.procedure
.input(t.union([t.string(), t.number()]))
.output(
t.object({
input: t.string(),
}),
)
.query(({ input }) => {
return { input: input as string };
}),
});
const { proxy, close } = routerToServerAndClientNew(router);
const output = await proxy.q.query('foobar');
expectTypeOf(output.input).toBeString();
expect(output).toMatchInlineSnapshot(`
Object {
"input": "foobar",
}
`);
await expect(proxy.q.query(1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('yup', async () => {
const yupStringOrNumber = (value: unknown) => {
switch (typeof value) {
case 'number':
return yup.number().required();
case 'string':
return yup.string().required();
default:
throw new Error('Fail');
}
};
const trpc = initTRPC.create();
const router = trpc.router({
q: trpc.procedure
.input(yup.lazy(yupStringOrNumber))
.output(
yup.object({
input: yup.string().strict().required(),
}),
)
.query(({ input }) => {
return { input: input as string };
}),
});
const { proxy, close } = routerToServerAndClientNew(router);
const output = await proxy.q.query('foobar');
expectTypeOf(output.input).toBeString();
expect(output).toMatchInlineSnapshot(`
Object {
"input": "foobar",
}
`);
await expect(proxy.q.query(1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('myzod', async () => {
const trpc = initTRPC.create();
const router = trpc.router({
q: trpc.procedure
.input(myzod.string().or(myzod.number()))
.output(
myzod.object({
input: myzod.string(),
}),
)
.query(({ input }) => {
return { input: input as string };
}),
});
const { proxy, close } = routerToServerAndClientNew(router);
const output = await proxy.q.query('foobar');
expectTypeOf(output.input).toBeString();
expect(output).toMatchInlineSnapshot(`
Object {
"input": "foobar",
}
`);
await expect(proxy.q.query(1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('validator fn', async () => {
const trpc = initTRPC.create();
const router = trpc.router({
q: trpc.procedure
.input((value: unknown) => value as number | string)
.output((value: unknown) => {
if (typeof (value as any).input === 'string') {
return value as { input: string };
}
throw new Error('Fail');
})
.query(({ input }) => {
return { input: input as string };
}),
});
const { proxy, close } = routerToServerAndClientNew(router);
const output = await proxy.q.query('foobar');
expectTypeOf(output.input).toBeString();
expect(output).toMatchInlineSnapshot(`
Object {
"input": "foobar",
}
`);
await expect(proxy.q.query(1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
test('async validator fn', async () => {
const trpc = initTRPC.create();
const router = trpc.router({
q: trpc.procedure
.input((value: unknown) => value as number | string)
.output(async (value: any): Promise<{ input: string }> => {
if (value && typeof value.input === 'string') {
return { input: value.input };
}
throw new Error('Fail');
})
.query(({ input }) => {
return { input: input as string };
}),
});
const { proxy, close } = routerToServerAndClientNew(router);
const output = await proxy.q.query('foobar');
expectTypeOf(output.input).toBeString();
expect(output).toMatchInlineSnapshot(`
Object {
"input": "foobar",
}
`);
await expect(proxy.q.query(1234)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Output validation failed]`,
);
await close();
});
|
5,182 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/rawFetch.test.tsx | import { routerToServerAndClientNew } from './___testHelpers';
import { initTRPC } from '@trpc/server/src';
import { z } from 'zod';
const factory = () => {
const t = initTRPC.context().create();
const router = t.router({
myQuery: t.procedure
.input(
z
.object({
name: z.string(),
})
.optional(),
)
.query(({ input }) => {
return input?.name ?? 'default';
}),
myMutation: t.procedure
.input(
z.object({
name: z.string(),
}),
)
.mutation(async ({ input }) => {
return { input };
}),
});
return routerToServerAndClientNew(router);
};
test('batching with raw batch', async () => {
const { close, httpUrl } = factory();
{
const res = await fetch(
`${httpUrl}/myQuery?batch=1&input=${JSON.stringify({
'0': { name: 'alexdotjs' },
})}`,
);
const json: any = await res.json();
expect(json[0]).toHaveProperty('result');
expect(json[0].result).toMatchInlineSnapshot(`
Object {
"data": "alexdotjs",
}
`);
}
await close();
});
|
5,183 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/responseMeta.test.ts | import { IncomingMessage, ServerResponse } from 'http';
import { routerToServerAndClientNew } from './___testHelpers';
import { initTRPC } from '@trpc/server/src';
import fetch from 'node-fetch';
test('set custom headers in beforeEnd', async () => {
const onError = vi.fn();
interface Context {
req: IncomingMessage;
res: ServerResponse<IncomingMessage>;
}
const t = initTRPC.context<Context>().create();
const appRouter = t.router({
['public.q']: t.procedure.query(({}) => {
return 'public endpoint';
}),
nonCachedEndpoint: t.procedure.query(({}) => {
return 'not cached endpoint';
}),
});
const { close, httpUrl } = routerToServerAndClientNew(appRouter, {
server: {
onError,
responseMeta({ ctx, paths, type, errors }) {
// assuming you have all your public routes with the keyword `public` in them
const allPublic = paths?.every((path) => path.includes('public'));
// checking that no procedures errored
const allOk = errors.length === 0;
// checking we're doing a query request
const isQuery = type === 'query';
if (ctx?.res && allPublic && allOk && isQuery) {
// cache request for 1 day + revalidate once every second
const ONE_DAY_IN_SECONDS = 60 * 60 * 24;
return {
headers: {
'cache-control': `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
},
};
}
return {};
},
},
});
{
const res = await fetch(`${httpUrl}/public.q`);
expect(await res.json()).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": "public endpoint",
},
}
`);
expect(res.headers.get('cache-control')).toMatchInlineSnapshot(
`"s-maxage=1, stale-while-revalidate=86400"`,
);
}
{
const res = await fetch(`${httpUrl}/nonCachedEndpoint`);
expect(await res.json()).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": "not cached endpoint",
},
}
`);
expect(res.headers.get('cache-control')).toBeNull();
}
await close();
});
test('cookie headers', async () => {
const onError = vi.fn();
interface Context {
req: IncomingMessage;
res: ServerResponse<IncomingMessage>;
}
const t = initTRPC.context<Context>().create();
const appRouter = t.router({
cookieEndpoint: t.procedure.query(() => {
return 'cookie endpoint';
}),
});
const { close, httpUrl } = routerToServerAndClientNew(appRouter, {
server: {
onError,
responseMeta() {
return {
headers: {
'Set-Cookie': ['a=b', 'b=c'],
},
};
},
},
});
{
const res = await fetch(`${httpUrl}/cookieEndpoint`);
expect(res.headers.get('set-cookie')).toMatchInlineSnapshot(`
"a=b, b=c"
`);
expect(await res.json()).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": "cookie endpoint",
},
}
`);
}
await close();
});
|
5,184 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/router.test.ts | import './___packages';
import { initTRPC } from '@trpc/server/src/core';
const t = initTRPC.create();
describe('router', () => {
test('is a reserved word', async () => {
expect(() => {
return t.router({
then: t.procedure.query(() => 'hello'),
});
}).toThrowErrorMatchingInlineSnapshot(
`"Reserved words used in \`router({})\` call: then"`,
);
});
// Regression https://github.com/trpc/trpc/pull/2562
test('because it creates async fns that returns proxy objects', async () => {
const appRouter = t.router({});
const asyncFnThatReturnsCaller = async () => appRouter.createCaller({});
await asyncFnThatReturnsCaller();
});
test('should not duplicate key', async () => {
expect(() =>
t.router({
foo: t.router({
'.bar': t.procedure.query(() => 'bar' as const),
}),
'foo.': t.router({
bar: t.procedure.query(() => 'bar' as const),
}),
}),
).toThrow('Duplicate key: foo..bar');
});
});
|
5,185 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/routerMeta.test.ts | import { routerToServerAndClientNew } from './___testHelpers';
import { inferRouterMeta, initTRPC } from '@trpc/server/src';
import { observable } from '@trpc/server/src/observable';
test('route meta types', async () => {
const testMeta = { data: 'foo' };
const t = initTRPC.meta<typeof testMeta>().create();
const middleware = t.middleware(async ({ next }) => {
return next();
});
const procedure = t.procedure.use(middleware);
const router = t.router({
query: procedure.meta(testMeta).query(({ input }) => {
input;
}),
subscription: procedure
.meta(testMeta)
.subscription(() => observable(() => () => '')),
mutation: procedure.meta(testMeta).mutation(({ input }) => {
input;
}),
});
type TMeta = inferRouterMeta<typeof router>;
expectTypeOf<TMeta>().toMatchTypeOf(testMeta);
expect(router._def.procedures.query).not.toEqual({});
expect(router._def.procedures.query).toMatchInlineSnapshot(`[Function]`);
const queryMeta = router._def.procedures.query._def.meta;
expectTypeOf(queryMeta).toMatchTypeOf<TMeta | undefined>();
expect(queryMeta).toEqual(testMeta);
const mutationMeta = router._def.procedures.mutation._def.meta;
expectTypeOf(mutationMeta).toMatchTypeOf<TMeta | undefined>();
expect(mutationMeta).toEqual(testMeta);
const subscriptionMeta = router._def.procedures.subscription._def.meta;
expectTypeOf(subscriptionMeta).toMatchTypeOf<TMeta | undefined>();
expect(subscriptionMeta).toEqual(testMeta);
});
test('route meta in middleware', async () => {
const t = initTRPC
.meta<{
data: string;
}>()
.create();
const middleware = vi.fn((opts) => {
return opts.next();
});
const procedure = t.procedure.use(middleware);
const router = t.router({
foo1: procedure.meta({ data: 'foo1' }).query(() => 'bar1'),
foo2: procedure.meta({ data: 'foo2' }).mutation(() => 'bar2'),
});
const { close, proxy } = routerToServerAndClientNew(router);
const calls = middleware.mock.calls;
expect(await proxy.foo1.query()).toBe('bar1');
expect(calls[0]![0]!).toHaveProperty('meta');
expect(calls[0]![0]!.meta).toEqual({
data: 'foo1',
});
expect(await proxy.foo2.mutate()).toBe('bar2');
expect(calls[1]![0]!).toHaveProperty('meta');
expect(calls[1]![0]!.meta).toEqual({
data: 'foo2',
});
expect(middleware).toHaveBeenCalledTimes(2);
await close();
});
test('default meta', async () => {
const t = initTRPC
.meta<{
data: string;
}>()
.create({
defaultMeta: { data: 'foobar' },
});
const middleware = vi.fn((opts) => {
return opts.next();
});
const procedure = t.procedure.use(middleware);
const router = t.router({
foo1: procedure.query(() => 'bar1'),
foo2: procedure.mutation(() => 'bar2'),
});
const { close, proxy } = routerToServerAndClientNew(router);
const calls = middleware.mock.calls;
expect(await proxy.foo1.query()).toBe('bar1');
expect(calls[0]![0]!).toHaveProperty('meta');
expect(calls[0]![0]!.meta).toEqual({
data: 'foobar',
});
expect(await proxy.foo2.mutate()).toBe('bar2');
expect(calls[1]![0]!).toHaveProperty('meta');
expect(calls[1]![0]!.meta).toEqual({
data: 'foobar',
});
expect(middleware).toHaveBeenCalledTimes(2);
await close();
});
test('default meta with merging', async () => {
const t = initTRPC
.meta<{
data: string;
}>()
.create({ defaultMeta: { data: 'foobar' } });
const middleware = vi.fn((opts) => {
return opts.next();
});
const procedure = t.procedure.use(middleware);
const router = t.router({
foo1: procedure.meta({ data: 'foo1' }).query(() => 'bar1'),
foo2: procedure.meta({ data: 'foo2' }).mutation(() => 'bar2'),
});
const { close, proxy } = routerToServerAndClientNew(router);
const calls = middleware.mock.calls;
expect(await proxy.foo1.query()).toBe('bar1');
expect(calls[0]![0]!).toHaveProperty('meta');
expect(calls[0]![0]!.meta).toEqual({
data: 'foo1',
});
expect(await proxy.foo2.mutate()).toBe('bar2');
expect(calls[1]![0]!).toHaveProperty('meta');
expect(calls[1]![0]!.meta).toEqual({
data: 'foo2',
});
expect(middleware).toHaveBeenCalledTimes(2);
await close();
});
test('meta chaining with merging', async () => {
const t = initTRPC
.meta<{
data: string;
}>()
.create();
const middleware = vi.fn((opts) => {
return opts.next();
});
const procedure = t.procedure.use(middleware);
const router = t.router({
foo1: procedure
.meta({ data: 'foo1' })
.meta({ data: 'foo2' })
.query(() => 'bar1'),
});
const { close, proxy } = routerToServerAndClientNew(router);
const calls = middleware.mock.calls;
expect(await proxy.foo1.query()).toBe('bar1');
expect(calls[0]![0]!).toHaveProperty('meta');
expect(calls[0]![0]!.meta).toEqual({
data: 'foo2',
});
expect(middleware).toHaveBeenCalledTimes(1);
await close();
});
test('complex meta merging', async () => {
const t = initTRPC
.meta<{
data1?: string;
data2?: number;
dataObj?: {
obj1: string;
obj2: string;
};
}>()
.create({
defaultMeta: {
data1: 'foobar',
},
});
const middleware = vi.fn((opts) => {
return opts.next();
});
const procedure = t.procedure.use(middleware);
const router = t.router({
foo1: procedure
.meta({ data2: 11 })
.meta({ data1: 'bazbar', dataObj: { obj1: 'a', obj2: 'b' } })
.query(() => 'bar1'),
});
const { close, proxy } = routerToServerAndClientNew(router);
const calls = middleware.mock.calls;
expect(await proxy.foo1.query()).toBe('bar1');
expect(calls[0]![0]!).toHaveProperty('meta');
expect(calls[0]![0]!.meta).toEqual({
data1: 'bazbar',
data2: 11,
dataObj: {
obj1: 'a',
obj2: 'b',
},
});
expect(middleware).toHaveBeenCalledTimes(1);
await close();
});
|
5,186 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/smoke.test.ts | import { EventEmitter } from 'events';
import { routerToServerAndClientNew, waitError } from './___testHelpers';
import { waitFor } from '@testing-library/react';
import { TRPCClientError, wsLink } from '@trpc/client/src';
import { inferProcedureParams, initTRPC } from '@trpc/server/src';
import { observable, Unsubscribable } from '@trpc/server/src/observable';
import { z } from 'zod';
const t = initTRPC
.context<{
foo?: 'bar';
}>()
.create({
errorFormatter({ shape }) {
return {
...shape,
data: {
...shape.data,
foo: 'bar' as const,
},
};
},
});
const { procedure } = t;
test('old client - happy path w/o input', async () => {
const router = t.router({
hello: procedure.query(() => 'world'),
});
const { client, close } = routerToServerAndClientNew(router);
// @ts-expect-error cannot call new procedure with old client
expect(await client.query('hello')).toBe('world');
await close();
});
test('old client - happy path with input', async () => {
const router = t.router({
greeting: procedure
.input(z.string())
.query(({ input }) => `hello ${input}`),
});
const { client, close } = routerToServerAndClientNew(router);
// @ts-expect-error cannot call new procedure with old client
expect(await client.query('greeting', 'KATT')).toBe('hello KATT');
await close();
});
test('very happy path', async () => {
const greeting = t.procedure
.input(z.string())
.use(({ next }) => {
return next();
})
.query(({ input }) => `hello ${input}`);
const router = t.router({
greeting,
});
{
type TContext = typeof greeting._def._config.$types.ctx;
expectTypeOf<TContext>().toMatchTypeOf<{
foo?: 'bar';
}>();
}
{
type TParams = inferProcedureParams<(typeof router)['greeting']>;
type TConfig = TParams['_config'];
type TContext = TConfig['$types']['ctx'];
type TError = TConfig['$types']['errorShape'];
expectTypeOf<NonNullable<TContext['foo']>>().toMatchTypeOf<'bar'>();
expectTypeOf<TError['data']['foo']>().toMatchTypeOf<'bar'>();
}
const { proxy, close } = routerToServerAndClientNew(router);
expect(await proxy.greeting.query('KATT')).toBe('hello KATT');
await close();
});
test('middleware', async () => {
const router = t.router({
greeting: procedure
.use(({ next }) => {
return next({
ctx: {
prefix: 'hello',
},
});
})
.use(({ next }) => {
return next({
ctx: {
user: 'KATT',
},
});
})
.query(({ ctx }) => `${ctx.prefix} ${ctx.user}`),
});
const { proxy, close } = routerToServerAndClientNew(router);
expect(await proxy.greeting.query()).toBe('hello KATT');
await close();
});
test('sad path', async () => {
const router = t.router({
hello: procedure.query(() => 'world'),
});
const { proxy, close } = routerToServerAndClientNew(router);
// @ts-expect-error this procedure does not exist
const result = await waitError(proxy.not.found.query(), TRPCClientError);
expect(result).toMatchInlineSnapshot(
`[TRPCClientError: No "query"-procedure on path "not.found"]`,
);
await close();
});
test('call a mutation as a query', async () => {
const router = t.router({
hello: procedure.query(() => 'world'),
});
const { proxy, close } = routerToServerAndClientNew(router);
await expect((proxy.hello as any).mutate()).rejects.toMatchInlineSnapshot(
`[TRPCClientError: No "mutation"-procedure on path "hello"]`,
);
await close();
});
test('flat router', async () => {
const hello = procedure.query(() => 'world');
const bye = procedure.query(() => 'bye');
const router1 = t.router({
hello,
child: t.router({
bye,
}),
});
expect(router1.hello).toBe(hello);
expect(router1.child.bye).toBe(bye);
expectTypeOf(router1.hello).toMatchTypeOf(hello);
expectTypeOf(router1.child.bye).toMatchTypeOf(bye);
const router2 = t.router({
router2hello: hello,
});
const merged = t.mergeRouters(router1, router2);
expectTypeOf(merged.hello).toMatchTypeOf(hello);
expectTypeOf(merged.child.bye).toMatchTypeOf(bye);
expectTypeOf(merged.router2hello).toMatchTypeOf(hello);
expect(merged.hello).toBe(hello);
expect(merged.child.bye).toBe(bye);
});
test('subscriptions', async () => {
const ee = new EventEmitter();
const subscriptionMock = vi.fn();
const onStartedMock = vi.fn();
const onDataMock = vi.fn();
const onCompleteMock = vi.fn();
const router = t.router({
onEvent: t.procedure.input(z.number()).subscription(({ input }) => {
subscriptionMock(input);
return observable<number>((emit) => {
const onData = (data: number) => {
emit.next(data + input);
};
ee.on('data', onData);
return () => {
ee.off('data', onData);
};
});
}),
});
const { proxy, close } = routerToServerAndClientNew(router, {
client: ({ wsClient }) => ({
links: [wsLink({ client: wsClient })],
}),
});
const subscription = proxy.onEvent.subscribe(10, {
onStarted: onStartedMock,
onData: (data) => {
expectTypeOf(data).toMatchTypeOf<number>();
onDataMock(data);
},
onComplete: onCompleteMock,
});
expectTypeOf(subscription).toMatchTypeOf<Unsubscribable>();
await waitFor(() => {
expect(onStartedMock).toBeCalledTimes(1);
});
await waitFor(() => {
expect(subscriptionMock).toBeCalledTimes(1);
});
await waitFor(() => {
expect(subscriptionMock).toHaveBeenNthCalledWith(1, 10);
});
ee.emit('data', 20);
await waitFor(() => {
expect(onDataMock).toBeCalledTimes(1);
});
await waitFor(() => {
expect(onDataMock).toHaveBeenNthCalledWith(1, 30);
});
subscription.unsubscribe();
await waitFor(() => {
expect(onCompleteMock).toBeCalledTimes(1);
});
await close();
});
|
5,187 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/streaming.test.ts | import { routerToServerAndClientNew } from './___testHelpers';
import { TRPCLink, unstable_httpBatchStreamLink } from '@trpc/client';
import { initTRPC, TRPCError } from '@trpc/server';
import { observable } from '@trpc/server/observable';
import { konn } from 'konn';
import superjson from 'superjson';
import { z } from 'zod';
describe('no transformer', () => {
const orderedResults: number[] = [];
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create({});
orderedResults.length = 0;
const router = t.router({
deferred: t.procedure
.input(
z.object({
wait: z.number(),
}),
)
.query(async (opts) => {
await new Promise<void>((resolve) =>
setTimeout(resolve, opts.input.wait * 10),
);
return opts.input.wait;
}),
error: t.procedure.query(() => {
throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR' });
}),
});
const linkSpy: TRPCLink<typeof router> = () => {
// here we just got initialized in the app - this happens once per app
// useful for storing cache for instance
return ({ next, op }) => {
// this is when passing the result to the next link
// each link needs to return an observable which propagates results
return observable((observer) => {
const unsubscribe = next(op).subscribe({
next(value) {
orderedResults.push((value.result as any).data);
observer.next(value);
},
error: observer.error,
});
return unsubscribe;
});
};
};
const opts = routerToServerAndClientNew(router, {
server: {},
client(opts) {
return {
links: [
linkSpy,
unstable_httpBatchStreamLink({
url: opts.httpUrl,
}),
],
};
},
});
return opts;
})
.afterEach(async (opts) => {
await opts?.close?.();
})
.done();
test('out-of-order streaming', async () => {
const { proxy } = ctx;
const results = await Promise.all([
proxy.deferred.query({ wait: 3 }),
proxy.deferred.query({ wait: 1 }),
proxy.deferred.query({ wait: 2 }),
]);
// batch preserves request order
expect(results).toEqual([3, 1, 2]);
// streaming preserves response order
expect(orderedResults).toEqual([1, 2, 3]);
});
test('out-of-order streaming with error', async () => {
const { proxy } = ctx;
const results = await Promise.allSettled([
proxy.deferred.query({ wait: 1 }),
proxy.error.query(),
]);
expect(results).toMatchInlineSnapshot(`
Array [
Object {
"status": "fulfilled",
"value": 1,
},
Object {
"reason": [TRPCClientError: INTERNAL_SERVER_ERROR],
"status": "rejected",
},
]
`);
});
});
describe('with transformer', () => {
const orderedResults: number[] = [];
const ctx = konn()
.beforeEach(() => {
const t = initTRPC.create({
transformer: superjson,
});
orderedResults.length = 0;
const router = t.router({
deferred: t.procedure
.input(
z.object({
wait: z.number(),
}),
)
.query(async (opts) => {
await new Promise<void>((resolve) =>
setTimeout(resolve, opts.input.wait * 10),
);
return opts.input.wait;
}),
error: t.procedure.query(() => {
throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR' });
}),
});
const linkSpy: TRPCLink<typeof router> = () => {
// here we just got initialized in the app - this happens once per app
// useful for storing cache for instance
return ({ next, op }) => {
// this is when passing the result to the next link
// each link needs to return an observable which propagates results
return observable((observer) => {
const unsubscribe = next(op).subscribe({
next(value) {
orderedResults.push((value.result as any).data);
observer.next(value);
},
error: observer.error,
});
return unsubscribe;
});
};
};
const opts = routerToServerAndClientNew(router, {
server: {},
client(opts) {
return {
transformer: superjson,
links: [
linkSpy,
unstable_httpBatchStreamLink({
url: opts.httpUrl,
}),
],
};
},
});
return opts;
})
.afterEach(async (opts) => {
await opts?.close?.();
})
.done();
test('out-of-order streaming', async () => {
const { proxy } = ctx;
const results = await Promise.all([
proxy.deferred.query({ wait: 3 }),
proxy.deferred.query({ wait: 1 }),
proxy.deferred.query({ wait: 2 }),
]);
// batch preserves request order
expect(results).toEqual([3, 1, 2]);
// streaming preserves response order
expect(orderedResults).toEqual([1, 2, 3]);
});
test('out-of-order streaming with error', async () => {
const { proxy } = ctx;
const results = await Promise.allSettled([
proxy.deferred.query({ wait: 1 }),
proxy.error.query(),
]);
expect(results).toMatchInlineSnapshot(`
Array [
Object {
"status": "fulfilled",
"value": 1,
},
Object {
"reason": [TRPCClientError: INTERNAL_SERVER_ERROR],
"status": "rejected",
},
]
`);
});
});
|
5,188 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/transformer.test.ts | import { routerToServerAndClientNew, waitError } from './___testHelpers';
import {
createTRPCProxyClient,
createWSClient,
httpBatchLink,
httpLink,
TRPCClientError,
wsLink,
} from '@trpc/client';
import {
CombinedDataTransformer,
DataTransformer,
initTRPC,
TRPCError,
} from '@trpc/server';
import { observable } from '@trpc/server/src/observable';
import { uneval } from 'devalue';
import superjson from 'superjson';
import { createTson, tsonDate } from 'tupleson';
import { z } from 'zod';
test('superjson up and down', async () => {
const transformer = superjson;
const date = new Date();
const fn = vi.fn();
const t = initTRPC.create({ transformer });
const router = t.router({
hello: t.procedure.input(z.date()).query(({ input }) => {
fn(input);
return input;
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
});
const res = await proxy.hello.query(date);
expect(res.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
await close();
});
test('empty superjson up and down', async () => {
const transformer = superjson;
const t = initTRPC.create({ transformer });
const router = t.router({
emptyUp: t.procedure.query(() => 'hello world'),
emptyDown: t.procedure.input(z.string()).query(() => 'hello world'),
});
const { close, proxy } = routerToServerAndClientNew(router, {
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
});
const res1 = await proxy.emptyUp.query();
expect(res1).toBe('hello world');
const res2 = await proxy.emptyDown.query('');
expect(res2).toBe('hello world');
await close();
});
test('wsLink: empty superjson up and down', async () => {
const transformer = superjson;
let ws: any = null;
const t = initTRPC.create({ transformer });
const router = t.router({
emptyUp: t.procedure.query(() => 'hello world'),
emptyDown: t.procedure.input(z.string()).query(() => 'hello world'),
});
const { close, proxy } = routerToServerAndClientNew(router, {
client({ wssUrl }) {
ws = createWSClient({ url: wssUrl });
return {
transformer,
links: [wsLink({ client: ws })],
};
},
});
const res1 = await proxy.emptyUp.query();
expect(res1).toBe('hello world');
const res2 = await proxy.emptyDown.query('');
expect(res2).toBe('hello world');
await close();
ws.close();
});
test('devalue up and down', async () => {
const transformer: DataTransformer = {
serialize: (object) => uneval(object),
deserialize: (object) => eval(`(${object})`),
};
const date = new Date();
const fn = vi.fn();
const t = initTRPC.create({ transformer });
const router = t.router({
hello: t.procedure.input(z.date()).query(({ input }) => {
fn(input);
return input;
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
});
const res = await proxy.hello.query(date);
expect(res.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
await close();
});
test('not batching: superjson up and devalue down', async () => {
const transformer: CombinedDataTransformer = {
input: superjson,
output: {
serialize: (object) => uneval(object),
deserialize: (object) => eval(`(${object})`),
},
};
const date = new Date();
const fn = vi.fn();
const t = initTRPC.create({ transformer });
const router = t.router({
hello: t.procedure.input(z.date()).query(({ input }) => {
fn(input);
return input;
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
client({ httpUrl }) {
return {
transformer,
links: [httpLink({ url: httpUrl })],
};
},
});
const res = await proxy.hello.query(date);
expect(res.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
await close();
});
test('batching: superjson up and devalue down', async () => {
const transformer: CombinedDataTransformer = {
input: superjson,
output: {
serialize: (object) => uneval(object),
deserialize: (object) => eval(`(${object})`),
},
};
const date = new Date();
const fn = vi.fn();
const t = initTRPC.create({ transformer });
const router = t.router({
hello: t.procedure.input(z.date()).query(({ input }) => {
fn(input);
return input;
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
});
const res = await proxy.hello.query(date);
expect(res.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
await close();
});
test('batching: superjson up and f down', async () => {
const transformer: CombinedDataTransformer = {
input: superjson,
output: {
serialize: (object) => uneval(object),
deserialize: (object) => eval(`(${object})`),
},
};
const date = new Date();
const fn = vi.fn();
const t = initTRPC.create({ transformer });
const router = t.router({
hello: t.procedure.input(z.date()).query(({ input }) => {
fn(input);
return input;
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
client: ({ httpUrl }) => ({
transformer,
links: [httpBatchLink({ url: httpUrl })],
}),
});
const res = await proxy.hello.query(date);
expect(res.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
await close();
});
test('all transformers running in correct order', async () => {
const world = 'foo';
const fn = vi.fn();
const transformer: CombinedDataTransformer = {
input: {
serialize: (object) => {
fn('client:serialized');
return object;
},
deserialize: (object) => {
fn('server:deserialized');
return object;
},
},
output: {
serialize: (object) => {
fn('server:serialized');
return object;
},
deserialize: (object) => {
fn('client:deserialized');
return object;
},
},
};
const t = initTRPC.create({ transformer });
const router = t.router({
hello: t.procedure.input(z.string()).query(({ input }) => {
fn(input);
return input;
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
});
const res = await proxy.hello.query(world);
expect(res).toBe(world);
expect(fn.mock.calls[0]![0]!).toBe('client:serialized');
expect(fn.mock.calls[1]![0]!).toBe('server:deserialized');
expect(fn.mock.calls[2]![0]!).toBe(world);
expect(fn.mock.calls[3]![0]!).toBe('server:serialized');
expect(fn.mock.calls[4]![0]!).toBe('client:deserialized');
await close();
});
describe('transformer on router', () => {
test('http', async () => {
const transformer = superjson;
const date = new Date();
const fn = vi.fn();
const t = initTRPC.create({ transformer });
const router = t.router({
hello: t.procedure.input(z.date()).query(({ input }) => {
fn(input);
return input;
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
});
const res = await proxy.hello.query(date);
expect(res.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
await close();
});
test('ws', async () => {
let wsClient: any;
const date = new Date();
const fn = vi.fn();
const transformer = superjson;
const t = initTRPC.create({ transformer });
const router = t.router({
hello: t.procedure.input(z.date()).query(({ input }) => {
fn(input);
return input;
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
client({ wssUrl }) {
wsClient = createWSClient({
url: wssUrl,
});
return {
transformer,
links: [wsLink({ client: wsClient })],
};
},
});
const res = await proxy.hello.query(date);
expect(res.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
wsClient.close();
await close();
});
test('subscription', async () => {
let wsClient: any;
const date = new Date();
const fn = vi.fn();
const transformer = superjson;
const t = initTRPC.create({ transformer });
const router = t.router({
hello: t.procedure.input(z.date()).subscription(({ input }) => {
return observable<Date>((emit) => {
fn(input);
emit.next(input);
return () => {
// noop
};
});
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
client({ wssUrl }) {
wsClient = createWSClient({
url: wssUrl,
});
return {
transformer,
links: [wsLink({ client: wsClient })],
};
},
});
const data = await new Promise<Date>((resolve) => {
const subscription = proxy.hello.subscribe(date, {
onData: (data) => {
subscription.unsubscribe();
resolve(data);
},
});
});
expect(data.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
wsClient.close();
await close();
});
test('superjson up and devalue down: transform errors correctly', async () => {
const transformer: CombinedDataTransformer = {
input: superjson,
output: {
serialize: (object) => uneval(object),
deserialize: (object) => eval(`(${object})`),
},
};
class MyError extends Error {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, MyError.prototype);
}
}
const onError = vi.fn();
const t = initTRPC.create({ transformer });
const router = t.router({
err: t.procedure.query(() => {
throw new MyError('woop');
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
server: {
onError,
},
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
});
const clientError = await waitError(proxy.err.query(), TRPCClientError);
expect(clientError.shape.message).toMatchInlineSnapshot(`"woop"`);
expect(clientError.shape.code).toMatchInlineSnapshot(`-32603`);
expect(onError).toHaveBeenCalledTimes(1);
const serverError = onError.mock.calls[0]![0]!.error;
expect(serverError).toBeInstanceOf(TRPCError);
if (!(serverError instanceof TRPCError)) {
throw new Error('Wrong error');
}
expect(serverError.cause).toBeInstanceOf(MyError);
await close();
});
});
test('superjson - no input', async () => {
const transformer = superjson;
const fn = vi.fn();
const t = initTRPC.create({ transformer });
const router = t.router({
hello: t.procedure.query(({ input }) => {
fn(input);
return 'world';
}),
});
const { close, httpUrl } = routerToServerAndClientNew(router, {
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
});
const json = await (await fetch(`${httpUrl}/hello`)).json();
expect(json).not.toHaveProperty('error');
expect(json).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": Object {
"json": "world",
},
},
}
`);
await close();
});
describe('required transformers', () => {
test('works without transformer', () => {
const t = initTRPC.create({});
const router = t.router({});
createTRPCProxyClient<typeof router>({
links: [httpBatchLink({ url: '' })],
});
});
test('works with transformer', () => {
const transformer = superjson;
const t = initTRPC.create({
transformer,
});
const router = t.router({});
createTRPCProxyClient<typeof router>({
links: [httpBatchLink({ url: '' })],
transformer,
});
});
test('errors with transformer set on backend but not on frontend', () => {
const transformer = superjson;
const t = initTRPC.create({
transformer,
});
const router = t.router({});
// @ts-expect-error missing transformer on frontend
createTRPCProxyClient<typeof router>({
links: [httpBatchLink({ url: '' })],
});
});
test('errors with transformer set on frontend but not on backend', () => {
const transformer = superjson;
const t = initTRPC.create({});
const router = t.router({});
createTRPCProxyClient<typeof router>({
links: [httpBatchLink({ url: '' })],
// @ts-expect-error missing transformer on backend
transformer,
});
});
});
test('tupleson', async () => {
const transformer = createTson({
types: [tsonDate],
nonce: () => Math.random() + '',
});
const date = new Date();
const fn = vi.fn();
const t = initTRPC.create({ transformer });
const router = t.router({
hello: t.procedure.input(z.date()).query(({ input }) => {
fn(input);
return input;
}),
});
const { close, proxy } = routerToServerAndClientNew(router, {
client({ httpUrl }) {
return {
transformer,
links: [httpBatchLink({ url: httpUrl })],
};
},
});
const res = await proxy.hello.query(date);
expect(res.getTime()).toBe(date.getTime());
expect((fn.mock.calls[0]![0]! as Date).getTime()).toBe(date.getTime());
await close();
});
|
5,189 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/validators.test.ts | import { routerToServerAndClientNew } from './___testHelpers';
import { wrap } from '@decs/typeschema';
import * as S from '@effect/schema/Schema';
import { initTRPC } from '@trpc/server/src';
import * as arktype from 'arktype';
import myzod from 'myzod';
import * as T from 'runtypes';
import * as $ from 'scale-codec';
import * as st from 'superstruct';
import * as v from 'valibot';
import * as yup from 'yup';
import { z } from 'zod';
test('no validator', async () => {
const t = initTRPC.create();
const router = t.router({
hello: t.procedure.query(({ input }) => {
expectTypeOf(input).toBeUndefined();
return 'test';
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const res = await proxy.hello.query();
expect(res).toBe('test');
await close();
});
test('zod', async () => {
const t = initTRPC.create();
const router = t.router({
num: t.procedure.input(z.number()).query(({ input }) => {
expectTypeOf(input).toBeNumber();
return {
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const res = await proxy.num.query(123);
await expect(proxy.num.query('123' as any)).rejects.toMatchInlineSnapshot(`
[TRPCClientError: [
{
"code": "invalid_type",
"expected": "number",
"received": "string",
"path": [],
"message": "Expected number, received string"
}
]]
`);
expect(res.input).toBe(123);
await close();
});
test('zod async', async () => {
const t = initTRPC.create();
const input = z.string().refine(async (value) => value === 'foo');
const router = t.router({
q: t.procedure.input(input).query(({ input }) => {
expectTypeOf(input).toBeString();
return {
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
await expect(proxy.q.query('bar')).rejects.toMatchInlineSnapshot(`
[TRPCClientError: [
{
"code": "custom",
"message": "Invalid input",
"path": []
}
]]
`);
const res = await proxy.q.query('foo');
expect(res).toMatchInlineSnapshot(`
Object {
"input": "foo",
}
`);
await close();
});
test('zod transform mixed input/output', async () => {
const t = initTRPC.create();
const input = z.object({
length: z.string().transform((s) => s.length),
});
const router = t.router({
num: t.procedure.input(input).query(({ input }) => {
expectTypeOf(input.length).toBeNumber();
return {
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
await expect(proxy.num.query({ length: '123' })).resolves
.toMatchInlineSnapshot(`
Object {
"input": Object {
"length": 3,
},
}
`);
await expect(
// @ts-expect-error this should only accept a string
proxy.num.query({ length: 123 }),
).rejects.toMatchInlineSnapshot(`
[TRPCClientError: [
{
"code": "invalid_type",
"expected": "string",
"received": "number",
"path": [
"length"
],
"message": "Expected string, received number"
}
]]
`);
await close();
});
test('valibot', async () => {
const t = initTRPC.create();
const router = t.router({
num: t.procedure.input(wrap(v.number())).query(({ input }) => {
expectTypeOf(input).toBeNumber();
return {
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const res = await proxy.num.query(123);
await expect(proxy.num.query('123' as any)).rejects.toMatchInlineSnapshot(
'[TRPCClientError: Assertion failed]',
);
expect(res.input).toBe(123);
await close();
});
test('valibot async', async () => {
const t = initTRPC.create();
const input = wrap(
v.stringAsync([v.customAsync(async (value) => value === 'foo')]),
);
const router = t.router({
q: t.procedure.input(input).query(({ input }) => {
expectTypeOf(input).toBeString();
return {
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
await expect(proxy.q.query('bar')).rejects.toMatchInlineSnapshot(
'[TRPCClientError: Assertion failed]',
);
const res = await proxy.q.query('foo');
expect(res).toMatchInlineSnapshot(`
Object {
"input": "foo",
}
`);
await close();
});
test('valibot transform mixed input/output', async () => {
const t = initTRPC.create();
const input = wrap(
v.object({
length: v.transform(v.string(), (s) => s.length),
}),
);
const router = t.router({
num: t.procedure.input(input).query(({ input }) => {
expectTypeOf(input.length).toBeNumber();
return {
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
await expect(proxy.num.query({ length: '123' })).resolves
.toMatchInlineSnapshot(`
Object {
"input": Object {
"length": 3,
},
}
`);
await expect(
// @ts-expect-error this should only accept a string
proxy.num.query({ length: 123 }),
).rejects.toMatchInlineSnapshot('[TRPCClientError: Assertion failed]');
await close();
});
test('superstruct', async () => {
const t = initTRPC.create();
const router = t.router({
num: t.procedure.input(st.number()).query(({ input }) => {
expectTypeOf(input).toBeNumber();
return {
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const res = await proxy.num.query(123);
// @ts-expect-error this only accepts a `number`
await expect(proxy.num.query('123')).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Expected a number, but received: "123"]`,
);
expect(res.input).toBe(123);
await close();
});
test('yup', async () => {
const t = initTRPC.create();
const router = t.router({
num: t.procedure.input(yup.number().required()).query(({ input }) => {
expectTypeOf(input).toMatchTypeOf<number>();
return {
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const res = await proxy.num.query(123);
// @ts-expect-error this only accepts a `number`
await expect(proxy.num.query('asd')).rejects.toMatchInlineSnapshot(
`[TRPCClientError: this must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`"asd"\`).]`,
);
expect(res.input).toBe(123);
await close();
});
test('scale', async () => {
const t = initTRPC.create();
const router = t.router({
num: t.procedure.input($.i8).query(({ input }) => {
expectTypeOf(input).toMatchTypeOf<number>();
return {
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const res = await proxy.num.query(16);
// @ts-expect-error this only accepts a `number`
await expect(proxy.num.query('asd')).rejects.toMatchInlineSnapshot(
`[TRPCClientError: typeof value !== "number"]`,
);
expect(res.input).toBe(16);
await close();
});
test('myzod', async () => {
const t = initTRPC.create();
const router = t.router({
num: t.procedure.input(myzod.number()).query(({ input }) => {
expectTypeOf(input).toMatchTypeOf<number>();
return {
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const res = await proxy.num.query(123);
await expect(proxy.num.query('123' as any)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: expected type to be number but got string]`,
);
expect(res.input).toBe(123);
await close();
});
test('arktype schema - [not officially supported]', async () => {
const t = initTRPC.create();
const router = t.router({
num: t.procedure
.input(arktype.type({ text: 'string' }).assert)
.query(({ input }) => {
expectTypeOf(input).toMatchTypeOf<{ text: string }>();
return {
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const res = await proxy.num.query({ text: '123' });
expect(res.input).toMatchObject({ text: '123' });
// @ts-expect-error this only accepts a `number`
await expect(proxy.num.query('13')).rejects.toMatchInlineSnapshot(`
[TRPCClientError: Must be an object (was string)]
`);
await close();
});
test('effect schema - [not officially supported]', async () => {
const t = initTRPC.create();
const router = t.router({
num: t.procedure
.input(S.parseSync(S.struct({ text: S.string })))
.query(({ input }) => {
expectTypeOf(input).toMatchTypeOf<{ text: string }>();
return {
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const res = await proxy.num.query({ text: '123' });
expect(res.input).toMatchObject({ text: '123' });
// @ts-expect-error this only accepts a `number`
await expect(proxy.num.query('13')).rejects.toMatchInlineSnapshot(`
[TRPCClientError: error(s) found
└─ Expected a generic object, actual "13"]
`);
await close();
});
test('runtypes', async () => {
const t = initTRPC.create();
const router = t.router({
num: t.procedure.input(T.Record({ text: T.String })).query(({ input }) => {
expectTypeOf(input).toMatchTypeOf<{ text: string }>();
return {
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const res = await proxy.num.query({ text: '123' });
expect(res.input).toMatchObject({ text: '123' });
// @ts-expect-error this only accepts a `number`
await expect(proxy.num.query('13')).rejects.toMatchInlineSnapshot(`
[TRPCClientError: Expected { text: string; }, but was string]
`);
await close();
});
test('validator fn', async () => {
const t = initTRPC.create();
const numParser = (input: unknown) => {
if (typeof input !== 'number') {
throw new Error('Not a number');
}
return input;
};
const router = t.router({
num: t.procedure.input(numParser).query(({ input }) => {
expectTypeOf(input).toBeNumber();
return {
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const res = await proxy.num.query(123);
await expect(proxy.num.query('123' as any)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Not a number]`,
);
expect(res.input).toBe(123);
await close();
});
test('async validator fn', async () => {
const t = initTRPC.create();
async function numParser(input: unknown) {
if (typeof input !== 'number') {
throw new Error('Not a number');
}
return input;
}
const router = t.router({
num: t.procedure.input(numParser).query(({ input }) => {
expectTypeOf(input).toBeNumber();
return {
input,
};
}),
});
const { close, proxy } = routerToServerAndClientNew(router);
const res = await proxy.num.query(123);
await expect(proxy.num.query('123' as any)).rejects.toMatchInlineSnapshot(
`[TRPCClientError: Not a number]`,
);
expect(res.input).toBe(123);
await close();
});
|
5,190 | 0 | petrpan-code/trpc/trpc/packages/tests | petrpan-code/trpc/trpc/packages/tests/server/websockets.test.ts | import { EventEmitter } from 'events';
import { routerToServerAndClientNew, waitMs } from './___testHelpers';
import { waitFor } from '@testing-library/react';
import { createWSClient, TRPCClientError, wsLink } from '@trpc/client/src';
import { AnyRouter, initTRPC, TRPCError } from '@trpc/server/src';
import { applyWSSHandler } from '@trpc/server/src/adapters/ws';
import { observable, Observer } from '@trpc/server/src/observable';
import {
TRPCClientOutgoingMessage,
TRPCRequestMessage,
} from '@trpc/server/src/rpc';
import WebSocket, { Server } from 'ws';
import { z } from 'zod';
type Message = {
id: string;
};
function factory(config?: { createContext: () => Promise<any> }) {
const ee = new EventEmitter();
const subRef: {
current: Observer<Message, unknown>;
} = {} as any;
const onNewMessageSubscription = vi.fn();
const subscriptionEnded = vi.fn();
const onNewClient = vi.fn();
const t = initTRPC.create();
const appRouter = t.router({
greeting: t.procedure.input(z.string().nullish()).query(({ input }) => {
return `hello ${input ?? 'world'}`;
}),
slow: t.procedure.mutation(async ({}) => {
await waitMs(50);
return 'slow query resolved';
}),
['post.edit']: t.procedure
.input(
z.object({
id: z.string(),
data: z.object({
title: z.string(),
text: z.string(),
}),
}),
)
.mutation(({ input }) => {
const { id, data } = input;
return {
id,
...data,
};
}),
onMessage: t.procedure.input(z.string().nullish()).subscription(({}) => {
const sub = observable<Message>((emit) => {
subRef.current = emit;
const onMessage = (data: Message) => {
emit.next(data);
};
ee.on('server:msg', onMessage);
return () => {
subscriptionEnded();
ee.off('server:msg', onMessage);
};
});
ee.emit('subscription:created');
onNewMessageSubscription();
return sub;
}),
});
const onOpenMock = vi.fn();
const onCloseMock = vi.fn();
expectTypeOf(appRouter).toMatchTypeOf<AnyRouter>();
// TODO: Uncomment when the expect-type library gets fixed
// expectTypeOf<AnyRouter>().toMatchTypeOf<typeof appRouter>();
const opts = routerToServerAndClientNew(appRouter, {
wsClient: {
retryDelayMs: () => 10,
onOpen: onOpenMock,
onClose: onCloseMock,
},
client({ wsClient }) {
return {
links: [wsLink({ client: wsClient })],
};
},
server: {
...(config ?? {}),
},
wssServer: {
...(config ?? {}),
},
});
opts.wss.addListener('connection', onNewClient);
return {
...opts,
ee,
subRef,
onNewMessageSubscription,
onNewClient,
onOpenMock,
onCloseMock,
};
}
test('query', async () => {
const { proxy: proxy, close } = factory();
expect(await proxy.greeting.query()).toBe('hello world');
expect(await proxy.greeting.query(null)).toBe('hello world');
expect(await proxy.greeting.query('alexdotjs')).toBe('hello alexdotjs');
await close();
});
test('mutation', async () => {
const { proxy, close } = factory();
expect(
await proxy['post.edit'].mutate({
id: 'id',
data: { title: 'title', text: 'text' },
}),
).toMatchInlineSnapshot(`
Object {
"id": "id",
"text": "text",
"title": "title",
}
`);
await close();
});
test('basic subscription test', async () => {
const { proxy, close, ee } = factory();
ee.once('subscription:created', () => {
setTimeout(() => {
ee.emit('server:msg', {
id: '1',
});
ee.emit('server:msg', {
id: '2',
});
});
});
const onStartedMock = vi.fn();
const onDataMock = vi.fn();
const subscription = proxy.onMessage.subscribe(undefined, {
onStarted() {
onStartedMock();
},
onData(data) {
expectTypeOf(data).not.toBeAny();
expectTypeOf(data).toMatchTypeOf<Message>();
onDataMock(data);
},
});
await waitFor(() => {
expect(onStartedMock).toHaveBeenCalledTimes(1);
expect(onDataMock).toHaveBeenCalledTimes(2);
});
ee.emit('server:msg', {
id: '2',
});
await waitFor(() => {
expect(onDataMock).toHaveBeenCalledTimes(3);
});
expect(onDataMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
Object {
"id": "1",
},
],
Array [
Object {
"id": "2",
},
],
Array [
Object {
"id": "2",
},
],
]
`);
subscription.unsubscribe();
await waitFor(() => {
expect(ee.listenerCount('server:msg')).toBe(0);
expect(ee.listenerCount('server:error')).toBe(0);
});
await close();
});
test.skip('$subscription() - server randomly stop and restart (this test might be flaky, try re-running)', async () => {
const { proxy, close, ee, wssPort, applyWSSHandlerOpts } = factory();
ee.once('subscription:created', () => {
setTimeout(() => {
ee.emit('server:msg', {
id: '1',
});
ee.emit('server:msg', {
id: '2',
});
});
});
const onStartedMock = vi.fn();
const onDataMock = vi.fn();
const onErrorMock = vi.fn();
const onCompleteMock = vi.fn();
proxy.onMessage.subscribe(undefined, {
onStarted: onStartedMock,
onData: onDataMock,
onError: onErrorMock,
onComplete: onCompleteMock,
});
await waitFor(() => {
expect(onStartedMock).toHaveBeenCalledTimes(1);
expect(onDataMock).toHaveBeenCalledTimes(2);
});
// close websocket server
await close();
await waitFor(() => {
expect(onErrorMock).toHaveBeenCalledTimes(1);
expect(onCompleteMock).toHaveBeenCalledTimes(0);
});
expect(onErrorMock.mock.calls[0]![0]!).toMatchInlineSnapshot(
`[TRPCClientError: WebSocket closed prematurely]`,
);
expect(onErrorMock.mock.calls[0]![0]!.originalError.name).toBe(
'TRPCWebSocketClosedError',
);
// start a new wss server on same port, and trigger a message
onStartedMock.mockClear();
onDataMock.mockClear();
onCompleteMock.mockClear();
ee.once('subscription:created', () => {
setTimeout(() => {
ee.emit('server:msg', {
id: '3',
});
}, 1);
});
const wss = new Server({ port: wssPort });
applyWSSHandler({ ...applyWSSHandlerOpts, wss });
await waitFor(() => {
expect(onStartedMock).toHaveBeenCalledTimes(1);
expect(onDataMock).toHaveBeenCalledTimes(1);
});
expect(onDataMock.mock.calls.map((args) => args[0])).toMatchInlineSnapshot(`
Array [
Object {
"id": "3",
},
]
`);
await new Promise((resolve) => {
wss.close(resolve);
});
});
test('server subscription ended', async () => {
const { proxy, close, ee, subRef } = factory();
ee.once('subscription:created', () => {
setTimeout(() => {
ee.emit('server:msg', {
id: '1',
});
ee.emit('server:msg', {
id: '2',
});
});
});
const onStartedMock = vi.fn();
const onDataMock = vi.fn();
const onErrorMock = vi.fn();
const onCompleteMock = vi.fn();
proxy.onMessage.subscribe(undefined, {
onStarted: onStartedMock,
onData: onDataMock,
onError: onErrorMock,
onComplete: onCompleteMock,
});
await waitFor(() => {
expect(onStartedMock).toHaveBeenCalledTimes(1);
expect(onDataMock).toHaveBeenCalledTimes(2);
});
// destroy server subscription (called by server)
subRef.current.complete();
await waitFor(() => {
expect(onCompleteMock).toHaveBeenCalledTimes(1);
});
await close();
});
test('can close wsClient when subscribed', async () => {
const {
proxy,
close,
onCloseMock: wsClientOnCloseMock,
wsClient,
wss,
} = factory();
const serversideWsOnCloseMock = vi.fn();
wss.addListener('connection', (ws) =>
ws.on('close', serversideWsOnCloseMock),
);
const onStartedMock = vi.fn();
const onDataMock = vi.fn();
const onErrorMock = vi.fn();
const onCompleteMock = vi.fn();
proxy.onMessage.subscribe(undefined, {
onStarted: onStartedMock,
onData: onDataMock,
onError: onErrorMock,
onComplete: onCompleteMock,
});
await waitFor(() => {
expect(onStartedMock).toHaveBeenCalledTimes(1);
});
wsClient.close();
await waitFor(() => {
expect(onCompleteMock).toHaveBeenCalledTimes(1);
expect(wsClientOnCloseMock).toHaveBeenCalledTimes(1);
expect(serversideWsOnCloseMock).toHaveBeenCalledTimes(1);
});
await close();
});
test('sub emits errors', async () => {
const { proxy, close, wss, ee, subRef } = factory();
ee.once('subscription:created', () => {
setTimeout(() => {
ee.emit('server:msg', {
id: '1',
});
subRef.current.error(new Error('test'));
});
});
const onNewClient = vi.fn();
wss.addListener('connection', onNewClient);
const onStartedMock = vi.fn();
const onDataMock = vi.fn();
const onErrorMock = vi.fn();
const onCompleteMock = vi.fn();
proxy.onMessage.subscribe(undefined, {
onStarted: onStartedMock,
onData: onDataMock,
onError: onErrorMock,
onComplete: onCompleteMock,
});
await waitFor(() => {
expect(onStartedMock).toHaveBeenCalledTimes(1);
expect(onDataMock).toHaveBeenCalledTimes(1);
expect(onErrorMock).toHaveBeenCalledTimes(1);
expect(onCompleteMock).toHaveBeenCalledTimes(0);
});
await close();
});
test(
'wait for slow queries/mutations before disconnecting',
async () => {
const { proxy, close, wsClient, onNewClient } = factory();
await waitFor(() => {
expect(onNewClient).toHaveBeenCalledTimes(1);
});
const promise = proxy.slow.mutate();
wsClient.close();
expect(await promise).toMatchInlineSnapshot(`"slow query resolved"`);
await close();
await waitFor(() => {
expect(wsClient.getConnection().readyState).toBe(WebSocket.CLOSED);
});
await close();
},
{ retry: 5 },
);
test(
'subscriptions are automatically resumed',
async () => {
const { proxy, close, ee, wssHandler, wss, onOpenMock, onCloseMock } =
factory();
ee.once('subscription:created', () => {
setTimeout(() => {
ee.emit('server:msg', {
id: '1',
});
});
});
function createSub() {
const onStartedMock = vi.fn();
const onDataMock = vi.fn();
const onErrorMock = vi.fn();
const onStoppedMock = vi.fn();
const onCompleteMock = vi.fn();
const unsub = proxy.onMessage.subscribe(undefined, {
onStarted: onStartedMock(),
onData: onDataMock,
onError: onErrorMock,
onStopped: onStoppedMock,
onComplete: onCompleteMock,
});
return {
onStartedMock,
onDataMock,
onErrorMock,
onStoppedMock,
onCompleteMock,
unsub,
};
}
const sub1 = createSub();
await waitFor(() => {
expect(sub1.onStartedMock).toHaveBeenCalledTimes(1);
expect(sub1.onDataMock).toHaveBeenCalledTimes(1);
expect(onOpenMock).toHaveBeenCalledTimes(1);
expect(onCloseMock).toHaveBeenCalledTimes(0);
});
wssHandler.broadcastReconnectNotification();
await waitFor(() => {
expect(wss.clients.size).toBe(1);
expect(onOpenMock).toHaveBeenCalledTimes(2);
expect(onCloseMock).toHaveBeenCalledTimes(1);
});
await waitFor(() => {
expect(sub1.onStartedMock).toHaveBeenCalledTimes(1);
expect(sub1.onDataMock).toHaveBeenCalledTimes(1);
});
ee.emit('server:msg', {
id: '2',
});
await waitFor(() => {
expect(sub1.onDataMock).toHaveBeenCalledTimes(2);
});
expect(sub1.onDataMock.mock.calls.map((args) => args[0]))
.toMatchInlineSnapshot(`
Array [
Object {
"id": "1",
},
Object {
"id": "2",
},
]
`);
await waitFor(() => {
expect(wss.clients.size).toBe(1);
});
await close();
await waitFor(() => {
expect(onCloseMock).toHaveBeenCalledTimes(2);
});
},
{ retry: 5 },
);
test('not found error', async () => {
const { proxy, close, router } = factory();
const error: TRPCClientError<typeof router> = await new Promise(
// @ts-expect-error - testing runtime typeerrors
(resolve, reject) => proxy.notFound.query().then(reject).catch(resolve),
);
expect(error.name).toBe('TRPCClientError');
expect(error.shape?.data.code).toMatchInlineSnapshot(`"NOT_FOUND"`);
await close();
});
test('batching', async () => {
const t = factory();
const promises = [
t.proxy.greeting.query(),
t.proxy['post.edit'].mutate({ id: '', data: { text: '', title: '' } }),
] as const;
expect(await Promise.all(promises)).toMatchInlineSnapshot(`
Array [
"hello world",
Object {
"id": "",
"text": "",
"title": "",
},
]
`);
await t.close();
});
describe('regression test - slow createContext', () => {
test(
'send messages immediately on connection',
async () => {
const t = factory({
async createContext() {
await waitMs(50);
return {};
},
});
const rawClient = new WebSocket(t.wssUrl);
const msg: TRPCRequestMessage = {
id: 1,
method: 'query',
params: {
path: 'greeting',
input: null,
},
};
const msgStr = JSON.stringify(msg);
rawClient.onopen = () => {
rawClient.send(msgStr);
};
const data = await new Promise<string>((resolve) => {
rawClient.addEventListener('message', (msg) => {
resolve(msg.data as any);
});
});
expect(JSON.parse(data)).toMatchInlineSnapshot(`
Object {
"id": 1,
"result": Object {
"data": "hello world",
"type": "data",
},
}
`);
rawClient.close();
await t.close();
},
{ retry: 5 },
);
test(
'createContext throws',
async () => {
const createContext = vi.fn(async () => {
await waitMs(20);
throw new TRPCError({ code: 'UNAUTHORIZED', message: 'test' });
});
const t = factory({
createContext,
});
// close built-in client immediately to prevent connection
t.wsClient.close();
const rawClient = new WebSocket(t.wssUrl);
const msg: TRPCRequestMessage = {
id: 1,
method: 'query',
params: {
path: 'greeting',
input: null,
},
};
const msgStr = JSON.stringify(msg);
rawClient.onopen = () => {
rawClient.send(msgStr);
};
const responses: any[] = [];
rawClient.addEventListener('message', (msg) => {
responses.push(JSON.parse(msg.data as any));
});
await new Promise<void>((resolve) => {
rawClient.addEventListener('close', () => {
resolve();
});
});
for (const res of responses) {
expect(res).toHaveProperty('error');
expect(typeof res.error.data.stack).toBe('string');
res.error.data.stack = '[redacted]';
}
expect(responses).toHaveLength(2);
const [first, second] = responses;
expect(first.id).toBe(null);
expect(second.id).toBe(1);
expect(responses).toMatchInlineSnapshot(`
Array [
Object {
"error": Object {
"code": -32001,
"data": Object {
"code": "UNAUTHORIZED",
"httpStatus": 401,
"stack": "[redacted]",
},
"message": "test",
},
"id": null,
},
Object {
"error": Object {
"code": -32001,
"data": Object {
"code": "UNAUTHORIZED",
"httpStatus": 401,
"path": "greeting",
"stack": "[redacted]",
},
"message": "test",
},
"id": 1,
},
]
`);
expect(createContext).toHaveBeenCalledTimes(1);
await t.close();
},
{ retry: 5 },
);
});
test('malformatted JSON', async () => {
const t = factory();
// close built-in client immediately to prevent connection
t.wsClient.close();
const rawClient = new WebSocket(t.wssUrl);
rawClient.onopen = () => {
rawClient.send('not json');
};
const res: any = await new Promise<string>((resolve) => {
rawClient.addEventListener('message', (msg) => {
resolve(JSON.parse(msg.data as any));
});
});
expect(res).toHaveProperty('error');
expect(typeof res.error.data.stack).toBe('string');
res.error.data.stack = '[redacted]';
expect(res.id).toBe(null);
// replace "Unexpected token "o" with aaa
res.error.message = res.error.message.replace(
/^Unexpected token.*/,
'Unexpected token [... redacted b/c it is different in node 20]',
);
expect(res).toMatchInlineSnapshot(`
Object {
"error": Object {
"code": -32700,
"data": Object {
"code": "PARSE_ERROR",
"httpStatus": 400,
"stack": "[redacted]",
},
"message": "Unexpected token [... redacted b/c it is different in node 20]",
},
"id": null,
}
`);
await t.close();
});
test('regression - badly shaped request', async () => {
const t = factory();
const rawClient = new WebSocket(t.wssUrl);
const msg: TRPCRequestMessage = {
id: null,
method: 'query',
params: {
path: 'greeting',
input: null,
},
};
const msgStr = JSON.stringify(msg);
rawClient.onopen = () => {
rawClient.send(msgStr);
};
const result = await new Promise<string>((resolve) => {
rawClient.addEventListener('message', (msg) => {
resolve(msg.data as any);
});
});
const data = JSON.parse(result);
data.error.data.stack = '[redacted]';
expect(data).toMatchInlineSnapshot(`
Object {
"error": Object {
"code": -32700,
"data": Object {
"code": "PARSE_ERROR",
"httpStatus": 400,
"stack": "[redacted]",
},
"message": "\`id\` is required",
},
"id": null,
}
`);
rawClient.close();
await t.close();
});
describe('include "jsonrpc" in response if sent with message', () => {
test('queries & mutations', async () => {
const t = factory();
const rawClient = new WebSocket(t.wssUrl);
const queryMessageWithJsonRPC: TRPCClientOutgoingMessage = {
id: 1,
jsonrpc: '2.0',
method: 'query',
params: {
path: 'greeting',
input: null,
},
};
rawClient.onopen = () => {
rawClient.send(JSON.stringify(queryMessageWithJsonRPC));
};
const queryResult = await new Promise<string>((resolve) => {
rawClient.addEventListener('message', (msg) => {
resolve(msg.data as any);
});
});
const queryData = JSON.parse(queryResult);
expect(queryData).toMatchInlineSnapshot(`
Object {
"id": 1,
"jsonrpc": "2.0",
"result": Object {
"data": "hello world",
"type": "data",
},
}
`);
const mutationMessageWithJsonRPC: TRPCClientOutgoingMessage = {
id: 1,
jsonrpc: '2.0',
method: 'mutation',
params: {
path: 'slow',
input: undefined,
},
};
rawClient.send(JSON.stringify(mutationMessageWithJsonRPC));
const mutationResult = await new Promise<string>((resolve) => {
rawClient.addEventListener('message', (msg) => {
resolve(msg.data as any);
});
});
const mutationData = JSON.parse(mutationResult);
expect(mutationData).toMatchInlineSnapshot(`
Object {
"id": 1,
"jsonrpc": "2.0",
"result": Object {
"data": "slow query resolved",
"type": "data",
},
}
`);
rawClient.close();
await t.close();
});
test('subscriptions', async () => {
const t = factory();
const rawClient = new WebSocket(t.wssUrl);
const subscriptionMessageWithJsonRPC: TRPCClientOutgoingMessage = {
id: 1,
jsonrpc: '2.0',
method: 'subscription',
params: {
path: 'onMessage',
input: null,
},
};
rawClient.onopen = () => {
rawClient.send(JSON.stringify(subscriptionMessageWithJsonRPC));
};
const startedResult = await new Promise<string>((resolve) => {
rawClient.addEventListener('message', (msg) => {
resolve(msg.data as any);
});
});
const startedData = JSON.parse(startedResult);
expect(startedData).toMatchInlineSnapshot(`
Object {
"id": 1,
"jsonrpc": "2.0",
"result": Object {
"type": "started",
},
}
`);
const messageResult = await new Promise<string>((resolve) => {
rawClient.addEventListener('message', (msg) => {
resolve(msg.data as any);
});
t.ee.emit('server:msg', { id: '1' });
});
const messageData = JSON.parse(messageResult);
expect(messageData).toMatchInlineSnapshot(`
Object {
"id": 1,
"jsonrpc": "2.0",
"result": Object {
"data": Object {
"id": "1",
},
"type": "data",
},
}
`);
const subscriptionStopNotificationWithJsonRPC: TRPCClientOutgoingMessage = {
id: 1,
jsonrpc: '2.0',
method: 'subscription.stop',
};
const stoppedResult = await new Promise<string>((resolve) => {
rawClient.addEventListener('message', (msg) => {
resolve(msg.data as any);
});
rawClient.send(JSON.stringify(subscriptionStopNotificationWithJsonRPC));
});
const stoppedData = JSON.parse(stoppedResult);
expect(stoppedData).toMatchInlineSnapshot(`
Object {
"id": 1,
"jsonrpc": "2.0",
"result": Object {
"type": "stopped",
},
}
`);
rawClient.close();
await t.close();
});
});
test('wsClient stops reconnecting after .close()', async () => {
const badWsUrl = 'ws://localhost:9999';
const retryDelayMsMock = vi.fn();
retryDelayMsMock.mockReturnValue(100);
const wsClient = createWSClient({
url: badWsUrl,
retryDelayMs: retryDelayMsMock,
});
await waitFor(() => {
expect(retryDelayMsMock).toHaveBeenCalledTimes(1);
});
await waitFor(() => {
expect(retryDelayMsMock).toHaveBeenCalledTimes(2);
});
wsClient.close();
await waitMs(100);
expect(retryDelayMsMock).toHaveBeenCalledTimes(2);
});
|
5,192 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/adapters/awsLambda.test.tsx | import { initTRPC } from '@trpc/server/src';
import * as trpcLambda from '@trpc/server/src/adapters/aws-lambda';
import type { APIGatewayProxyEvent, APIGatewayProxyEventV2 } from 'aws-lambda';
import { z } from 'zod';
import {
mockAPIGatewayContext,
mockAPIGatewayProxyEventBase64Encoded,
mockAPIGatewayProxyEventV1,
mockAPIGatewayProxyEventV2,
} from './lambda.utils';
const createContext = async ({
event,
}: trpcLambda.CreateAWSLambdaContextOptions<APIGatewayProxyEvent>) => {
return {
user: event.headers['X-USER'],
};
};
type Context = Awaited<ReturnType<typeof createContext>>;
const t = initTRPC.context<Context>().create();
const router = t.router({
hello: t.procedure
.input(
z
.object({
who: z.string().nullish(),
})
.nullish(),
)
.query(({ input, ctx }) => ({
text: `hello ${input?.who ?? ctx.user ?? 'world'}`,
})),
echo: t.procedure
.input(
z.object({
who: z.object({ name: z.string().nullish() }),
}),
)
.query(({ input }) => ({
text: `hello ${input.who.name}`,
})),
['hello/darkness/my/old/friend']: t.procedure.query(() => {
return {
text: "I've come to talk with you again",
};
}),
addOne: t.procedure
.input(z.object({ counter: z.number().int().min(0) }))
.mutation(({ input }) => {
return {
counter: input.counter + 1,
};
}),
});
const tC = initTRPC.create();
const contextlessApp = tC.router({
hello: tC.procedure
.input(z.object({ who: z.string() }))
.query(({ input }) => {
return {
text: `hello ${input.who}`,
};
}),
});
const handler = trpcLambda.awsLambdaRequestHandler({
router,
createContext,
});
test('basic test', async () => {
const { body, ...result } = await handler(
mockAPIGatewayProxyEventV1({
body: JSON.stringify({}),
headers: { 'Content-Type': 'application/json', 'X-USER': 'Lilja' },
method: 'GET',
path: 'hello',
queryStringParameters: {},
resource: '/hello',
}),
mockAPIGatewayContext(),
);
const parsedBody = JSON.parse(body || '');
expect(result).toMatchInlineSnapshot(`
Object {
"headers": Object {
"Content-Type": "application/json",
},
"statusCode": 200,
}
`);
expect(parsedBody).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": Object {
"text": "hello Lilja",
},
},
}
`);
});
test('test v1 with leading prefix', async () => {
const { body, ...result } = await handler(
mockAPIGatewayProxyEventV1({
body: JSON.stringify({}),
headers: { 'Content-Type': 'application/json', 'X-USER': 'Lilja' },
method: 'GET',
path: '/leading/prefix/hello',
queryStringParameters: {},
pathParameters: { proxy: 'hello' },
resource: '/leading/prefix/{proxy+}',
}),
mockAPIGatewayContext(),
);
const parsedBody = JSON.parse(body || '');
expect(result).toMatchInlineSnapshot(`
Object {
"headers": Object {
"Content-Type": "application/json",
},
"statusCode": 200,
}
`);
expect(parsedBody).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": Object {
"text": "hello Lilja",
},
},
}
`);
});
test('test v1 can find procedure even if resource is not proxied', async () => {
const { body, ...result } = await handler(
mockAPIGatewayProxyEventV1({
body: JSON.stringify({}),
headers: { 'Content-Type': 'application/json', 'X-USER': 'Robin' },
method: 'GET',
path: '/leading/prefix/hello',
queryStringParameters: {},
// No pathParameters since we hit a direct resource, i.e. no {proxy+} on resource
resource: '/leading/prefix/hello',
}),
mockAPIGatewayContext(),
);
const parsedBody = JSON.parse(body || '');
expect(result).toMatchInlineSnapshot(`
Object {
"headers": Object {
"Content-Type": "application/json",
},
"statusCode": 200,
}
`);
expect(parsedBody).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": Object {
"text": "hello Robin",
},
},
}
`);
});
test('bad type', async () => {
const { body, ...result } = await handler(
mockAPIGatewayProxyEventV1({
body: JSON.stringify({ who: [[]] }),
headers: { 'Content-Type': 'application/json' },
method: 'GET',
path: 'echo',
queryStringParameters: {},
resource: '/echo',
}),
mockAPIGatewayContext(),
);
const parsedBody = JSON.parse(body || '');
expect(result).toMatchInlineSnapshot(`
Object {
"headers": Object {
"Content-Type": "application/json",
},
"statusCode": 400,
}
`);
parsedBody.error.data.stack = '[redacted]';
expect(parsedBody).toMatchInlineSnapshot(`
Object {
"error": Object {
"code": -32600,
"data": Object {
"code": "BAD_REQUEST",
"httpStatus": 400,
"path": "echo",
"stack": "[redacted]",
},
"message": "[
{
\\"code\\": \\"invalid_type\\",
\\"expected\\": \\"object\\",
\\"received\\": \\"undefined\\",
\\"path\\": [],
\\"message\\": \\"Required\\"
}
]",
},
}
`);
});
test('test v2 format', async () => {
const createContext = async ({
event,
}: trpcLambda.CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => {
return {
user: event.headers['X-USER'],
};
};
const handler2 = trpcLambda.awsLambdaRequestHandler({
router,
createContext,
});
const { body, ...result } = await handler2(
mockAPIGatewayProxyEventV2({
body: JSON.stringify({}),
headers: { 'Content-Type': 'application/json', 'X-USER': 'Lilja' },
method: 'GET',
path: 'hello',
queryStringParameters: {},
routeKey: '$default',
}),
mockAPIGatewayContext(),
);
expect(result).toMatchInlineSnapshot(`
Object {
"headers": Object {
"Content-Type": "application/json",
},
"statusCode": 200,
}
`);
const parsedBody = JSON.parse(body ?? '');
expect(parsedBody).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": Object {
"text": "hello Lilja",
},
},
}
`);
});
test('test v2 format with multiple / in query key', async () => {
const createContext = async ({
event,
}: trpcLambda.CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => {
return {
user: event.headers['X-USER'],
};
};
const handler2 = trpcLambda.awsLambdaRequestHandler({
router,
createContext,
});
const { body, ...result } = await handler2(
mockAPIGatewayProxyEventV2({
body: JSON.stringify({}),
headers: { 'Content-Type': 'application/json', 'X-USER': 'Lilja' },
method: 'GET',
path: 'hello/darkness/my/old/friend',
queryStringParameters: {},
routeKey: '$default',
}),
mockAPIGatewayContext(),
);
expect(result).toMatchInlineSnapshot(`
Object {
"headers": Object {
"Content-Type": "application/json",
},
"statusCode": 200,
}
`);
const parsedBody = JSON.parse(body ?? '');
expect(parsedBody).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": Object {
"text": "I've come to talk with you again",
},
},
}
`);
});
test('test v2 format with non default routeKey', async () => {
const createContext = async ({
event,
}: trpcLambda.CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => {
return {
user: event.headers['X-USER'],
};
};
const handler2 = trpcLambda.awsLambdaRequestHandler({
router,
createContext,
});
const { body, ...result } = await handler2(
mockAPIGatewayProxyEventV2({
body: JSON.stringify({}),
headers: { 'Content-Type': 'application/json', 'X-USER': 'Lilja' },
method: 'GET',
routeKey: 'ANY /trpc/{a}/{path+}',
path: 'trpc/abc/hello',
queryStringParameters: {},
pathParameters: { a: 'abc', path: 'hello' },
}),
mockAPIGatewayContext(),
);
expect(result).toMatchInlineSnapshot(`
Object {
"headers": Object {
"Content-Type": "application/json",
},
"statusCode": 200,
}
`);
const parsedBody = JSON.parse(body ?? '');
expect(parsedBody).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": Object {
"text": "hello Lilja",
},
},
}
`);
});
test('test v2 format with non default routeKey and nested router', async () => {
const createContext = async ({
event,
}: trpcLambda.CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => {
return {
user: event.headers['X-USER'],
};
};
const handler2 = trpcLambda.awsLambdaRequestHandler({
router,
createContext,
});
const { body, ...result } = await handler2(
mockAPIGatewayProxyEventV2({
body: JSON.stringify({}),
headers: { 'Content-Type': 'application/json', 'X-USER': 'Lilja' },
method: 'GET',
routeKey: 'ANY /trpc/{a}/{path+}',
path: 'trpc/abc/hello/darkness/my/old/friend',
queryStringParameters: {},
pathParameters: { a: 'abc', path: 'hello/darkness/my/old/friend' },
}),
mockAPIGatewayContext(),
);
expect(result).toMatchInlineSnapshot(`
Object {
"headers": Object {
"Content-Type": "application/json",
},
"statusCode": 200,
}
`);
const parsedBody = JSON.parse(body ?? '');
expect(parsedBody).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": Object {
"text": "I've come to talk with you again",
},
},
}
`);
});
test('router with no context', async () => {
const handler2 = trpcLambda.awsLambdaRequestHandler({
router: contextlessApp,
});
const { body, ...result } = await handler2(
mockAPIGatewayProxyEventV1({
body: JSON.stringify({}),
headers: { 'Content-Type': 'application/json', 'X-USER': 'Lilja' },
method: 'GET',
path: 'hello',
queryStringParameters: {
input: JSON.stringify({ who: 'kATT' }),
},
resource: '/hello',
}),
mockAPIGatewayContext(),
);
expect(result).toMatchInlineSnapshot(`
Object {
"headers": Object {
"Content-Type": "application/json",
},
"statusCode": 200,
}
`);
const parsedBody = JSON.parse(body ?? '');
expect(parsedBody).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": Object {
"text": "hello kATT",
},
},
}
`);
});
test('test base64 encoded apigateway proxy integration', async () => {
const { body, ...result } = await handler(
mockAPIGatewayProxyEventBase64Encoded(
mockAPIGatewayProxyEventV1({
body: JSON.stringify({ counter: 1 }),
headers: { 'Content-Type': 'application/json', 'X-USER': 'Eliot' },
method: 'POST',
path: 'addOne',
queryStringParameters: {},
resource: '/addOne',
}),
),
mockAPIGatewayContext(),
);
const parsedBody = JSON.parse(body || '');
expect(result).toMatchInlineSnapshot(`
Object {
"headers": Object {
"Content-Type": "application/json",
},
"statusCode": 200,
}
`);
expect(parsedBody).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": Object {
"counter": 2,
},
},
}
`);
});
|
5,193 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/adapters/express.test.tsx | import http from 'http';
import { Context, router } from './__router';
import {
createTRPCProxyClient,
httpBatchLink,
TRPCClientError,
} from '@trpc/client/src';
import * as trpc from '@trpc/server/src';
import * as trpcExpress from '@trpc/server/src/adapters/express';
import express from 'express';
import fetch from 'node-fetch';
async function startServer() {
const createContext = (
_opts: trpcExpress.CreateExpressContextOptions,
): Context => {
const getUser = () => {
if (_opts.req.headers.authorization === 'meow') {
return {
name: 'KATT',
};
}
return null;
};
return {
user: getUser(),
};
};
// express implementation
const app = express();
app.use(
'/trpc',
trpcExpress.createExpressMiddleware({
router,
maxBodySize: 10, // 10 bytes,
createContext,
}),
);
const { server, port } = await new Promise<{
server: http.Server;
port: number;
}>((resolve) => {
const server = app.listen(0, () => {
resolve({
server,
port: (server.address() as any).port,
});
});
});
const client = createTRPCProxyClient<typeof router>({
links: [
httpBatchLink({
url: `http://localhost:${port}/trpc`,
AbortController,
fetch: fetch as any,
}),
],
});
return {
close: () =>
new Promise<void>((resolve, reject) =>
server.close((err) => {
err ? reject(err) : resolve();
}),
),
port,
router,
client,
};
}
let t: Awaited<ReturnType<typeof startServer>>;
beforeAll(async () => {
t = await startServer();
});
afterAll(async () => {
await t.close();
});
test('simple query', async () => {
expect(
await t.client.hello.query({
who: 'test',
}),
).toMatchInlineSnapshot(`
Object {
"text": "hello test",
}
`);
const res = await t.client.hello.query();
expect(res).toMatchInlineSnapshot(`
Object {
"text": "hello world",
}
`);
});
test('error query', async () => {
try {
await t.client.exampleError.query();
} catch (e) {
expect(e).toStrictEqual(new TRPCClientError('Unexpected error'));
}
});
test('payload too large', async () => {
try {
await t.client.exampleMutation.mutate({ payload: 'a'.repeat(100) });
expect(true).toBe(false); // should not be reached
} catch (e) {
expect(e).toStrictEqual(new TRPCClientError('PAYLOAD_TOO_LARGE'));
}
});
|
5,194 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/adapters/fastify.test.ts | import { EventEmitter } from 'events';
import ws from '@fastify/websocket';
import { waitFor } from '@testing-library/react';
import {
createTRPCProxyClient,
createWSClient,
HTTPHeaders,
splitLink,
TRPCLink,
unstable_httpBatchStreamLink,
wsLink,
} from '@trpc/client/src';
import { initTRPC } from '@trpc/server';
import {
CreateFastifyContextOptions,
fastifyTRPCPlugin,
} from '@trpc/server/src/adapters/fastify';
import { observable } from '@trpc/server/src/observable';
import fastify from 'fastify';
import fp from 'fastify-plugin';
import fetch from 'node-fetch';
import { z } from 'zod';
const config = {
logger: false,
prefix: '/trpc',
};
function createContext({ req, res }: CreateFastifyContextOptions) {
const user = { name: req.headers.username ?? 'anonymous' };
return { req, res, user };
}
type Context = Awaited<ReturnType<typeof createContext>>;
interface Message {
id: string;
}
function createAppRouter() {
const ee = new EventEmitter();
const onNewMessageSubscription = vi.fn();
const onSubscriptionEnded = vi.fn();
const t = initTRPC.context<Context>().create();
const router = t.router;
const publicProcedure = t.procedure;
const appRouter = router({
ping: publicProcedure.query(() => {
return 'pong';
}),
hello: publicProcedure
.input(
z
.object({
username: z.string().nullish(),
})
.nullish(),
)
.query(({ input, ctx }) => ({
text: `hello ${input?.username ?? ctx.user?.name ?? 'world'}`,
})),
['post.edit']: publicProcedure
.input(
z.object({
id: z.string(),
data: z.object({
title: z.string(),
text: z.string(),
}),
}),
)
.mutation(async ({ input, ctx }) => {
if (ctx.user.name === 'anonymous') {
return { error: 'Unauthorized user' };
}
const { id, data } = input;
return { id, ...data };
}),
onMessage: publicProcedure.input(z.string()).subscription(() => {
const sub = observable<Message>((emit) => {
const onMessage = (data: Message) => {
emit.next(data);
};
ee.on('server:msg', onMessage);
return () => {
onSubscriptionEnded();
ee.off('server:msg', onMessage);
};
});
ee.emit('subscription:created');
onNewMessageSubscription();
return sub;
}),
deferred: publicProcedure
.input(
z.object({
wait: z.number(),
}),
)
.query(async (opts) => {
await new Promise<void>((resolve) =>
setTimeout(resolve, opts.input.wait * 10),
);
return opts.input.wait;
}),
});
return { appRouter, ee, onNewMessageSubscription, onSubscriptionEnded };
}
type CreateAppRouter = Awaited<ReturnType<typeof createAppRouter>>;
type AppRouter = CreateAppRouter['appRouter'];
interface ServerOptions {
appRouter: AppRouter;
fastifyPluginWrapper?: boolean;
withContentTypeParser?: boolean;
}
type PostPayload = { Body: { text: string; life: number } };
function createServer(opts: ServerOptions) {
const instance = fastify({ logger: config.logger });
if (opts.withContentTypeParser) {
instance.addContentTypeParser(
'application/json',
{ parseAs: 'string' },
function (_, body, _done) {
_done(null, body);
},
);
}
const plugin = !!opts.fastifyPluginWrapper
? fp(fastifyTRPCPlugin)
: fastifyTRPCPlugin;
const router = opts.appRouter;
instance.register(ws);
instance.register(plugin, {
useWSS: true,
prefix: config.prefix,
trpcOptions: { router, createContext },
});
instance.get('/hello', async () => {
return { hello: 'GET' };
});
instance.post<PostPayload>('/hello', async ({ body }) => {
return { hello: 'POST', body };
});
const stop = async () => {
await instance.close();
};
return { instance, stop };
}
const orderedResults: number[] = [];
const linkSpy: TRPCLink<AppRouter> = () => {
// here we just got initialized in the app - this happens once per app
// useful for storing cache for instance
return ({ next, op }) => {
// this is when passing the result to the next link
// each link needs to return an observable which propagates results
return observable((observer) => {
const unsubscribe = next(op).subscribe({
next(value) {
orderedResults.push((value.result as any).data);
observer.next(value);
},
error: observer.error,
});
return unsubscribe;
});
};
};
interface ClientOptions {
headers?: HTTPHeaders;
port: number | string;
}
function createClient(opts: ClientOptions) {
const host = `localhost:${opts.port}${config.prefix}`;
const wsClient = createWSClient({ url: `ws://${host}` });
const client = createTRPCProxyClient<AppRouter>({
links: [
linkSpy,
splitLink({
condition(op) {
return op.type === 'subscription';
},
true: wsLink({ client: wsClient }),
false: unstable_httpBatchStreamLink({
url: `http://${host}`,
headers: opts.headers,
AbortController,
fetch: fetch as any,
}),
}),
],
});
return { client, wsClient };
}
interface AppOptions {
clientOptions?: Partial<ClientOptions>;
serverOptions?: Partial<ServerOptions>;
}
async function createApp(opts: AppOptions = {}) {
const { appRouter, ee } = createAppRouter();
const { instance, stop } = createServer({
...(opts.serverOptions ?? {}),
appRouter,
});
const url = new URL(await instance.listen({ port: 0 }));
const { client } = createClient({ ...opts.clientOptions, port: url.port });
return { server: instance, stop, client, ee, url };
}
let app: Awaited<ReturnType<typeof createApp>>;
describe('anonymous user', () => {
beforeEach(async () => {
orderedResults.length = 0;
app = await createApp();
});
afterEach(async () => {
await app.stop();
});
test('fetch POST', async () => {
const data = { text: 'life', life: 42 };
const req = await fetch(`http://localhost:${app.url.port}/hello`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
// body should be object
expect(await req.json()).toMatchInlineSnapshot(`
Object {
"body": Object {
"life": 42,
"text": "life",
},
"hello": "POST",
}
`);
});
test('query', async () => {
expect(await app.client.ping.query()).toMatchInlineSnapshot(`"pong"`);
expect(await app.client.hello.query()).toMatchInlineSnapshot(`
Object {
"text": "hello anonymous",
}
`);
expect(
await app.client.hello.query({
username: 'test',
}),
).toMatchInlineSnapshot(`
Object {
"text": "hello test",
}
`);
});
test('mutation', async () => {
expect(
await app.client['post.edit'].mutate({
id: '42',
data: { title: 'new_title', text: 'new_text' },
}),
).toMatchInlineSnapshot(`
Object {
"error": "Unauthorized user",
}
`);
});
test('subscription', async () => {
app.ee.once('subscription:created', () => {
setTimeout(() => {
app.ee.emit('server:msg', {
id: '1',
});
app.ee.emit('server:msg', {
id: '2',
});
});
});
const onStartedMock = vi.fn();
const onDataMock = vi.fn();
const sub = app.client.onMessage.subscribe('onMessage', {
onStarted: onStartedMock,
onData(data) {
expectTypeOf(data).not.toBeAny();
expectTypeOf(data).toMatchTypeOf<Message>();
onDataMock(data);
},
});
await waitFor(() => {
expect(onStartedMock).toHaveBeenCalledTimes(1);
expect(onDataMock).toHaveBeenCalledTimes(2);
});
app.ee.emit('server:msg', {
id: '3',
});
await waitFor(() => {
expect(onDataMock).toHaveBeenCalledTimes(3);
});
expect(onDataMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
Object {
"id": "1",
},
],
Array [
Object {
"id": "2",
},
],
Array [
Object {
"id": "3",
},
],
]
`);
sub.unsubscribe();
await waitFor(() => {
expect(app.ee.listenerCount('server:msg')).toBe(0);
expect(app.ee.listenerCount('server:error')).toBe(0);
});
});
test('streaming', async () => {
const results = await Promise.all([
app.client.deferred.query({ wait: 3 }),
app.client.deferred.query({ wait: 1 }),
app.client.deferred.query({ wait: 2 }),
]);
expect(results).toEqual([3, 1, 2]);
expect(orderedResults).toEqual([1, 2, 3]);
});
});
describe('authorized user', () => {
beforeEach(async () => {
app = await createApp({ clientOptions: { headers: { username: 'nyan' } } });
});
afterEach(async () => {
await app.stop();
});
test('query', async () => {
expect(await app.client.hello.query()).toMatchInlineSnapshot(`
Object {
"text": "hello nyan",
}
`);
});
test('mutation', async () => {
expect(
await app.client['post.edit'].mutate({
id: '42',
data: { title: 'new_title', text: 'new_text' },
}),
).toMatchInlineSnapshot(`
Object {
"id": "42",
"text": "new_text",
"title": "new_title",
}
`);
});
});
describe('anonymous user with fastify-plugin', () => {
beforeEach(async () => {
app = await createApp({ serverOptions: { fastifyPluginWrapper: true } });
});
afterEach(async () => {
await app.stop();
});
test('fetch GET', async () => {
const req = await fetch(`http://localhost:${app.url.port}/hello`);
expect(await req.json()).toEqual({ hello: 'GET' });
});
test('fetch POST', async () => {
const data = { text: 'life', life: 42 };
const req = await fetch(`http://localhost:${app.url.port}/hello`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
// body should be string
expect(await req.json()).toMatchInlineSnapshot(`
Object {
"body": "{\\"text\\":\\"life\\",\\"life\\":42}",
"hello": "POST",
}
`);
});
test('query', async () => {
expect(await app.client.ping.query()).toMatchInlineSnapshot(`"pong"`);
expect(await app.client.hello.query()).toMatchInlineSnapshot(`
Object {
"text": "hello anonymous",
}
`);
expect(
await app.client.hello.query({
username: 'test',
}),
).toMatchInlineSnapshot(`
Object {
"text": "hello test",
}
`);
});
});
// https://github.com/trpc/trpc/issues/4820
describe('regression #4820 - content type parser already set', () => {
beforeEach(async () => {
app = await createApp({
serverOptions: {
fastifyPluginWrapper: true,
withContentTypeParser: true,
},
});
});
afterEach(async () => {
await app.stop();
});
test('query', async () => {
expect(await app.client.ping.query()).toMatchInlineSnapshot(`"pong"`);
});
});
|
5,195 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/adapters/fetch.test.ts | // @vitest-environment miniflare
/// <reference types="@cloudflare/workers-types" />
import '../___packages';
import { ReadableStream as MiniflareReadableStream } from 'stream/web';
import { Response as MiniflareResponse } from '@miniflare/core';
import {
createTRPCProxyClient,
httpBatchLink,
TRPCLink,
unstable_httpBatchStreamLink,
} from '@trpc/client';
import { initTRPC } from '@trpc/server';
import {
FetchCreateContextFnOptions,
fetchRequestHandler,
} from '@trpc/server/adapters/fetch';
import { observable, tap } from '@trpc/server/observable';
import { Miniflare } from 'miniflare';
import { z } from 'zod';
// miniflare does an instanceof check
globalThis.Response = MiniflareResponse as any;
// miniflare must use the web stream "polyfill"
globalThis.ReadableStream = MiniflareReadableStream as any;
const createContext = ({ req, resHeaders }: FetchCreateContextFnOptions) => {
const getUser = () => {
if (req.headers.get('authorization') === 'meow') {
return {
name: 'KATT',
};
}
return null;
};
return {
user: getUser(),
resHeaders,
};
};
type Context = Awaited<ReturnType<typeof createContext>>;
function createAppRouter() {
const t = initTRPC.context<Context>().create();
const router = t.router;
const publicProcedure = t.procedure;
const appRouter = router({
hello: publicProcedure
.input(
z
.object({
who: z.string().nullish(),
})
.nullish(),
)
.query(({ input, ctx }) => ({
text: `hello ${input?.who ?? ctx.user?.name ?? 'world'}`,
})),
foo: publicProcedure.query(({ ctx }) => {
ctx.resHeaders.set('x-foo', 'bar');
return 'foo';
}),
deferred: publicProcedure
.input(
z.object({
wait: z.number(),
}),
)
.query(async (opts) => {
await new Promise<void>((resolve) =>
setTimeout(resolve, opts.input.wait * 10),
);
return opts.input.wait;
}),
});
return appRouter;
}
type AppRouter = ReturnType<typeof createAppRouter>;
async function startServer(endpoint = '') {
const router = createAppRouter();
const mf = new Miniflare({
script: '//',
port: 0,
compatibilityFlags: ['streams_enable_constructors'],
});
const globalScope = await mf.getGlobalScope();
globalScope.addEventListener('fetch', (event: FetchEvent) => {
const response = fetchRequestHandler({
endpoint,
req: event.request,
router,
createContext,
responseMeta() {
return {
headers: {},
};
},
});
event.respondWith(response);
});
const server = await mf.startServer();
const port = (server.address() as any).port;
const trimSlashes = (path: string): string => {
path = path.startsWith('/') ? path.slice(1) : path;
path = path.endsWith('/') ? path.slice(0, -1) : path;
return path;
};
const path = trimSlashes(endpoint);
const url = `http://localhost:${port}${path && `/${path}`}`;
const client = createTRPCProxyClient<typeof router>({
links: [httpBatchLink({ url, fetch: fetch as any })],
});
return {
url,
close: () =>
new Promise<void>((resolve, reject) =>
server.close((err) => {
err ? reject(err) : resolve();
}),
),
router,
client,
};
}
describe('with default server', () => {
let t: Awaited<ReturnType<typeof startServer>>;
beforeAll(async () => {
t = await startServer();
});
afterAll(async () => {
await t.close();
});
test('simple query', async () => {
expect(
await t.client.hello.query({
who: 'test',
}),
).toMatchInlineSnapshot(`
Object {
"text": "hello test",
}
`);
expect(await t.client.hello.query()).toMatchInlineSnapshot(`
Object {
"text": "hello world",
}
`);
});
test('streaming', async () => {
const orderedResults: number[] = [];
const linkSpy: TRPCLink<AppRouter> = () => {
// here we just got initialized in the app - this happens once per app
// useful for storing cache for instance
return ({ next, op }) => {
// this is when passing the result to the next link
// each link needs to return an observable which propagates results
return observable((observer) => {
const unsubscribe = next(op).subscribe({
next(value) {
orderedResults.push((value.result as any).data);
observer.next(value);
},
error: observer.error,
});
return unsubscribe;
});
};
};
const client = createTRPCProxyClient<AppRouter>({
links: [
linkSpy,
unstable_httpBatchStreamLink({
url: t.url,
fetch: fetch as any,
}),
],
});
const results = await Promise.all([
client.deferred.query({ wait: 3 }),
client.deferred.query({ wait: 1 }),
client.deferred.query({ wait: 2 }),
]);
expect(results).toEqual([3, 1, 2]);
expect(orderedResults).toEqual([1, 2, 3]);
});
test('query with headers', async () => {
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: t.url,
fetch: fetch as any,
headers: { authorization: 'meow' },
}),
],
});
expect(await client.hello.query()).toMatchInlineSnapshot(`
Object {
"text": "hello KATT",
}
`);
});
test('response with headers', async () => {
const customLink: TRPCLink<AppRouter> = () => {
return ({ next, op }) => {
return next(op).pipe(
tap({
next(result) {
const context = result.context as { response: Response };
expect(context.response.headers.get('x-foo')).toBe('bar');
},
}),
);
};
};
const client = createTRPCProxyClient<AppRouter>({
links: [
customLink,
httpBatchLink({
url: t.url,
fetch: fetch as any,
headers: { authorization: 'meow' },
}),
],
});
await client.foo.query();
});
});
test.each([
// https://github.com/trpc/trpc/pull/4893
'/',
'trpc',
/// https://github.com/trpc/trpc/issues/5089
'trpc/',
'/trpc/',
'/x/y/z',
])('with "%s" endpoint', async (endpoint) => {
const custom = await startServer(endpoint);
expect(
await custom.client.hello.query({
who: 'test',
}),
).toEqual({
text: 'hello test',
});
await custom.close();
});
|
5,196 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/adapters/lambda.test.tsx | /**
* @deprecated
* TODO: remove in next major
*/
import * as trpc from '@trpc/server/src';
import * as trpcLambda from '@trpc/server/src/adapters/lambda';
import type { APIGatewayProxyEvent, APIGatewayProxyEventV2 } from 'aws-lambda';
import { z } from 'zod';
import {
mockAPIGatewayContext,
mockAPIGatewayProxyEventV1,
mockAPIGatewayProxyEventV2,
} from './lambda.utils';
const createContext = async ({
event,
}: trpcLambda.CreateLambdaContextOptions<APIGatewayProxyEvent>) => {
return {
user: event.headers['X-USER'],
};
};
type Context = Awaited<ReturnType<typeof createContext>>;
const router = trpc
.router<Context>()
.query('hello', {
input: z
.object({
who: z.string().nullish(),
})
.nullish(),
resolve({ input, ctx }) {
return {
text: `hello ${input?.who ?? ctx.user ?? 'world'}`,
};
},
})
.query('echo', {
input: z.object({
who: z.object({ name: z.string().nullish() }),
}),
resolve({ input }) {
return {
text: `hello ${input.who.name}`,
};
},
})
.interop();
const contextlessApp = trpc
.router()
.query('hello', {
input: z.object({
who: z.string(),
}),
resolve({ input }) {
return {
text: `hello ${input.who}`,
};
},
})
.interop();
const handler = trpcLambda.lambdaRequestHandler({
router,
createContext,
});
test('basic test', async () => {
const { body, ...result } = await handler(
mockAPIGatewayProxyEventV1({
body: JSON.stringify({}),
headers: { 'Content-Type': 'application/json', 'X-USER': 'Lilja' },
method: 'GET',
path: 'hello',
queryStringParameters: {},
resource: '/hello',
}),
mockAPIGatewayContext(),
);
const parsedBody = JSON.parse(body || '');
expect(result).toMatchInlineSnapshot(`
Object {
"headers": Object {
"Content-Type": "application/json",
},
"statusCode": 200,
}
`);
expect(parsedBody).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": Object {
"text": "hello Lilja",
},
},
}
`);
});
test('bad type', async () => {
const { body, ...result } = await handler(
mockAPIGatewayProxyEventV1({
body: JSON.stringify({ who: [[]] }),
headers: { 'Content-Type': 'application/json' },
method: 'GET',
path: 'echo',
queryStringParameters: {},
resource: '/echo',
}),
mockAPIGatewayContext(),
);
const parsedBody = JSON.parse(body || '');
expect(result).toMatchInlineSnapshot(`
Object {
"headers": Object {
"Content-Type": "application/json",
},
"statusCode": 400,
}
`);
parsedBody.error.data.stack = '[redacted]';
expect(parsedBody).toMatchInlineSnapshot(`
Object {
"error": Object {
"code": -32600,
"data": Object {
"code": "BAD_REQUEST",
"httpStatus": 400,
"path": "echo",
"stack": "[redacted]",
},
"message": "[
{
\\"code\\": \\"invalid_type\\",
\\"expected\\": \\"object\\",
\\"received\\": \\"undefined\\",
\\"path\\": [],
\\"message\\": \\"Required\\"
}
]",
},
}
`);
});
test('test v2 format', async () => {
const createContext = async ({
event,
}: trpcLambda.CreateLambdaContextOptions<APIGatewayProxyEventV2>) => {
return {
user: event.headers['X-USER'],
};
};
const handler2 = trpcLambda.lambdaRequestHandler({
router,
createContext,
});
const { body, ...result } = await handler2(
mockAPIGatewayProxyEventV2({
body: JSON.stringify({}),
headers: { 'Content-Type': 'application/json', 'X-USER': 'Lilja' },
method: 'GET',
path: 'hello',
queryStringParameters: {},
routeKey: '$default',
}),
mockAPIGatewayContext(),
);
expect(result).toMatchInlineSnapshot(`
Object {
"headers": Object {
"Content-Type": "application/json",
},
"statusCode": 200,
}
`);
const parsedBody = JSON.parse(body ?? '');
expect(parsedBody).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": Object {
"text": "hello Lilja",
},
},
}
`);
});
test('router with no context', async () => {
const handler2 = trpcLambda.lambdaRequestHandler({
router: contextlessApp,
});
const { body, ...result } = await handler2(
mockAPIGatewayProxyEventV1({
body: JSON.stringify({}),
headers: { 'Content-Type': 'application/json', 'X-USER': 'Lilja' },
method: 'GET',
path: 'hello',
queryStringParameters: {
input: JSON.stringify({ who: 'kATT' }),
},
resource: '/hello',
}),
mockAPIGatewayContext(),
);
expect(result).toMatchInlineSnapshot(`
Object {
"headers": Object {
"Content-Type": "application/json",
},
"statusCode": 200,
}
`);
const parsedBody = JSON.parse(body ?? '');
expect(parsedBody).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": Object {
"text": "hello kATT",
},
},
}
`);
});
|
5,198 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/adapters/next.test.ts | import { EventEmitter } from 'events';
import { initTRPC } from '@trpc/server';
import * as trpcNext from '@trpc/server/src/adapters/next';
function mockReq({
query,
method = 'GET',
body,
}: {
query: Record<string, any>;
method?:
| 'CONNECT'
| 'DELETE'
| 'GET'
| 'HEAD'
| 'OPTIONS'
| 'POST'
| 'PUT'
| 'TRACE';
body?: unknown;
}) {
const req = new EventEmitter() as any;
req.method = method;
req.query = query;
req.headers = {};
const socket = {
destroy: vi.fn(),
};
req.socket = socket;
setTimeout(() => {
if (body) {
req.emit('data', JSON.stringify(body));
}
req.emit('end');
});
return { req, socket };
}
function mockRes() {
const res = new EventEmitter() as any;
const json = vi.fn(() => res);
const setHeader = vi.fn(() => res);
const end = vi.fn(() => res);
res.json = json;
res.setHeader = setHeader;
res.end = end;
return { res, json, setHeader, end };
}
test('bad setup', async () => {
const t = initTRPC.create();
const router = t.router({
hello: t.procedure.query(() => 'world'),
});
const handler = trpcNext.createNextApiHandler({
router,
});
const { req } = mockReq({ query: {} });
const { res, json } = mockRes();
await handler(req, res);
const responseJson: any = (json.mock.calls[0] as any)[0];
expect(responseJson.ok).toMatchInlineSnapshot(`undefined`);
expect(responseJson.error.message).toMatchInlineSnapshot(
`"Query \\"trpc\\" not found - is the file named \`[trpc]\`.ts or \`[...trpc].ts\`?"`,
);
expect(responseJson.statusCode).toMatchInlineSnapshot(`undefined`);
});
describe('ok request', () => {
const t = initTRPC.create();
const router = t.router({
hello: t.procedure.query(() => 'world'),
});
const handler = trpcNext.createNextApiHandler({
router,
});
test('[...trpc].ts', async () => {
const { req } = mockReq({
query: {
trpc: ['hello'],
},
});
const { res, end } = mockRes();
await handler(req, res);
expect(res.statusCode).toBe(200);
const json: any = JSON.parse((end.mock.calls[0] as any)[0]);
expect(json).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": "world",
},
}
`);
});
test('[trpc].ts', async () => {
const { req } = mockReq({
query: {
trpc: 'hello',
},
});
const { res, end } = mockRes();
await handler(req, res);
expect(res.statusCode).toBe(200);
const json: any = JSON.parse((end.mock.calls[0] as any)[0]);
expect(json).toMatchInlineSnapshot(`
Object {
"result": Object {
"data": "world",
},
}
`);
});
});
test('404', async () => {
const t = initTRPC.create();
const router = t.router({
hello: t.procedure.query(() => 'world'),
});
const handler = trpcNext.createNextApiHandler({
router,
});
const { req } = mockReq({
query: {
trpc: ['not-found-path'],
},
});
const { res, end } = mockRes();
await handler(req, res);
expect(res.statusCode).toBe(404);
const json: any = JSON.parse((end.mock.calls[0] as any)[0]);
expect(json.error.message).toMatchInlineSnapshot(
`"No \\"query\\"-procedure on path \\"not-found-path\\""`,
);
});
test('payload too large', async () => {
const t = initTRPC.create();
const router = t.router({
hello: t.procedure.query(() => 'world'),
});
const handler = trpcNext.createNextApiHandler({
router,
maxBodySize: 1,
});
const { req } = mockReq({
query: {
trpc: ['hello'],
},
method: 'POST',
body: '123456789',
});
const { res, end } = mockRes();
await handler(req, res);
expect(res.statusCode).toBe(413);
const json: any = JSON.parse((end.mock.calls[0] as any)[0]);
expect(json.error.message).toMatchInlineSnapshot(`"PAYLOAD_TOO_LARGE"`);
});
test('HEAD request', async () => {
const t = initTRPC.create();
const router = t.router({
hello: t.procedure.query(() => 'world'),
});
const handler = trpcNext.createNextApiHandler({
router,
});
const { req } = mockReq({
query: {
trpc: [],
},
method: 'HEAD',
});
const { res } = mockRes();
await handler(req, res);
expect(res.statusCode).toBe(204);
});
test('PUT request (fails)', async () => {
const t = initTRPC.create();
const router = t.router({
hello: t.procedure.query(() => 'world'),
});
const handler = trpcNext.createNextApiHandler({
router,
});
const { req } = mockReq({
query: {
trpc: [],
},
method: 'PUT',
});
const { res } = mockRes();
await handler(req, res);
expect(res.statusCode).toBe(405);
});
test('middleware intercepts request', async () => {
const t = initTRPC.create();
const router = t.router({
hello: t.procedure.query(() => 'world'),
});
const handler = trpcNext.createNextApiHandler({
middleware: (_req, res, _next) => {
res.statusCode = 419;
res.end();
return;
},
router,
});
const { req } = mockReq({
query: {
trpc: [],
},
method: 'PUT',
});
const { res } = mockRes();
await handler(req, res);
expect(res.statusCode).toBe(419);
});
test('middleware passes the request', async () => {
const t = initTRPC.create();
const router = t.router({
hello: t.procedure.query(() => 'world'),
});
const handler = trpcNext.createNextApiHandler({
middleware: (_req, _res, next) => {
return next();
},
router,
});
const { req } = mockReq({
query: {
trpc: [],
},
method: 'PUT',
});
const { res } = mockRes();
await handler(req, res);
expect(res.statusCode).toBe(405);
});
|
5,199 | 0 | petrpan-code/trpc/trpc/packages/tests/server | petrpan-code/trpc/trpc/packages/tests/server/adapters/standalone.test.ts | import {
createTRPCProxyClient,
httpBatchLink,
TRPCClientError,
} from '@trpc/client/src';
import { initTRPC, TRPCError } from '@trpc/server';
import {
CreateHTTPHandlerOptions,
createHTTPServer,
} from '@trpc/server/src/adapters/standalone';
import fetch from 'node-fetch';
import { z } from 'zod';
const t = initTRPC.create();
const router = t.router({
hello: t.procedure
.input(
z.object({
who: z.string().nullish(),
}),
)
.query(({ input }) => ({
text: `hello ${input?.who}`,
})),
exampleError: t.procedure.query(() => {
throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: 'Unexpected error',
});
}),
});
let app: ReturnType<typeof createHTTPServer>;
async function startServer(opts: CreateHTTPHandlerOptions<any>) {
app = createHTTPServer(opts);
app.server.addListener('error', (err) => {
throw err;
});
const { port } = app.listen(0);
const client = createTRPCProxyClient<typeof router>({
links: [
httpBatchLink({
url: `http://localhost:${port}`,
AbortController,
fetch: fetch as any,
}),
],
});
return {
port,
router,
client,
};
}
afterEach(async () => {
if (app) {
app.server.close();
}
});
test('simple query', async () => {
const t = await startServer({
router,
});
expect(
await t.client.hello.query({
who: 'test',
}),
).toMatchInlineSnapshot(`
Object {
"text": "hello test",
}
`);
});
test('error query', async () => {
const t = await startServer({
router,
});
try {
await t.client.exampleError.query();
} catch (e) {
expect(e).toStrictEqual(new TRPCClientError('Unexpected error'));
}
});
test('middleware intercepts request', async () => {
const t = await startServer({
middleware: (_req, res, _next) => {
res.statusCode = 419;
res.end();
return;
},
router,
});
const result = await fetch(`http://localhost:${t.port}`);
expect(result.status).toBe(419);
});
test('middleware passes the request', async () => {
const t = await startServer({
middleware: (_req, _res, next) => {
return next();
},
router,
});
const result = await t.client.hello.query({ who: 'test' });
expect(result).toMatchInlineSnapshot(`
Object {
"text": "hello test",
}
`);
});
|
Subsets and Splits