level_0
int64 0
10k
| index
int64 0
0
| repo_id
stringlengths 22
152
| file_path
stringlengths 41
203
| content
stringlengths 11
11.5M
|
---|---|---|---|---|
282 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/common/DSLConversions | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/common/DSLConversions/tests/fixedToAutoLayout.test.ts | import {
Positioning,
ResponsiveBehavior,
} from "layoutSystems/common/utils/constants";
import type { DSLWidget } from "WidgetProvider/constants";
import {
fitChildWidgetsIntoLayers,
getAutoCanvasWidget,
getCondensedGroupedWidgets,
getTopLeftMostWidget,
processGroupedWidgets,
} from "../fixedToAutoLayout";
jest.mock("WidgetProvider/factory/index", () => ({
widgetConfigMap: {
get: jest.fn(() => {
/**/
}),
},
getWidgetAutoLayoutConfig: jest.fn(() => {
/**/
}),
}));
describe("test fixed to Auto Conversion methods", () => {
const childWidgets = [
{
boxShadow: "none",
widgetName: "Button1",
topRow: 0.0,
bottomRow: 4.0,
type: "BUTTON_WIDGET",
leftColumn: 0.0,
rightColumn: 16.0,
widgetId: "oc0e52x3mq",
},
{
widgetName: "Button3",
topRow: 0.0,
bottomRow: 4.0,
type: "BUTTON_WIDGET",
leftColumn: 48.0,
rightColumn: 64.0,
widgetId: "em4ubqs787",
},
{
widgetName: "Input1",
topRow: 2.0,
bottomRow: 9.0,
type: "INPUT_WIDGET_V2",
leftColumn: 23.0,
rightColumn: 43.0,
widgetId: "50rdpq2yow",
},
{
widgetName: "Form1",
topRow: 11.0,
bottomRow: 50.0,
type: "FORM_WIDGET",
leftColumn: 2.0,
children: [
{
widgetName: "Canvas1",
topRow: 0.0,
bottomRow: 390.0,
type: "CANVAS_WIDGET",
minHeight: 390.0,
leftColumn: 0.0,
children: [
{
widgetName: "Text1",
topRow: 1.0,
bottomRow: 5.0,
type: "TEXT_WIDGET",
leftColumn: 1.5,
rightColumn: 25.5,
widgetId: "y1u22x7gj9",
parentId: "lwl0t7o358",
},
{
widgetName: "Button4",
topRow: 33.0,
bottomRow: 37.0,
type: "BUTTON_WIDGET",
leftColumn: 46.0,
rightColumn: 62.0,
widgetId: "7dnsyyas3b",
parentId: "lwl0t7o358",
},
{
widgetName: "Button5",
topRow: 33.0,
bottomRow: 37.0,
type: "BUTTON_WIDGET",
leftColumn: 30.0,
rightColumn: 46.0,
parentId: "lwl0t7o358",
},
],
widgetId: "lwl0t7o358",
parentId: "quvrkp960y",
},
],
rightColumn: 26.0,
widgetId: "quvrkp960y",
parentId: "0",
},
{
widgetName: "Button6",
topRow: 26.0,
bottomRow: 30.0,
parentRowSpace: 10.0,
type: "BUTTON_WIDGET",
leftColumn: 30.0,
rightColumn: 46.0,
widgetId: "e9fhrq8uvf",
parentId: "0",
},
{
widgetName: "Modal1",
topRow: 16.0,
bottomRow: 256.0,
parentRowSpace: 10.0,
type: "MODAL_WIDGET",
leftColumn: 9.0,
children: [],
rightColumn: 33.0,
widgetId: "tf847brtfd",
parentId: "0",
},
{
widgetName: "Container1",
topRow: 36.0,
bottomRow: 61.0,
type: "CONTAINER_WIDGET",
leftColumn: 38.0,
children: [
{
widgetName: "Canvas3",
topRow: 0.0,
bottomRow: 250.0,
type: "CANVAS_WIDGET",
minHeight: 250.0,
leftColumn: 0.0,
children: [
{
widgetName: "Container2Copy",
topRow: 0.0,
bottomRow: 13.0,
type: "CONTAINER_WIDGET",
leftColumn: 36.0,
children: [
{
widgetName: "Canvas4Copy",
topRow: 0.0,
bottomRow: 130.0,
type: "CANVAS_WIDGET",
minHeight: 130.0,
leftColumn: 0.0,
children: [
{
widgetName: "Button9Copy",
topRow: 0.0,
bottomRow: 4.0,
type: "BUTTON_WIDGET",
leftColumn: 2.0,
rightColumn: 18.0,
widgetId: "rbgq3cl9j0",
parentId: "vap4aivehm",
},
{
widgetName: "Button10Copy",
topRow: 7.0,
bottomRow: 11.0,
type: "BUTTON_WIDGET",
leftColumn: 33.0,
rightColumn: 49.0,
widgetId: "to5e5cr2ph",
parentId: "vap4aivehm",
},
],
rightColumn: 105.5625,
widgetId: "vap4aivehm",
parentId: "pd2zln825w",
},
],
rightColumn: 60.0,
widgetId: "pd2zln825w",
parentId: "b6wgydyko8",
renderMode: "CANVAS",
},
{
widgetName: "Container2",
topRow: 10.0,
bottomRow: 23.0,
type: "CONTAINER_WIDGET",
leftColumn: 0.0,
children: [
{
widgetName: "Canvas4",
topRow: 0.0,
bottomRow: 130.0,
type: "CANVAS_WIDGET",
minHeight: 130.0,
leftColumn: 0.0,
children: [
{
widgetName: "Button9",
topRow: 0.0,
bottomRow: 4.0,
type: "BUTTON_WIDGET",
leftColumn: 2.0,
rightColumn: 18.0,
widgetId: "o529pnktws",
parentId: "se4m3djd2t",
},
{
widgetName: "Button10",
topRow: 7.0,
bottomRow: 11.0,
type: "BUTTON_WIDGET",
leftColumn: 33.0,
rightColumn: 49.0,
widgetId: "vf1wsdypci",
parentId: "se4m3djd2t",
},
],
rightColumn: 105.5625,
widgetId: "se4m3djd2t",
parentId: "x7ahy6olyf",
},
],
rightColumn: 24.0,
widgetId: "x7ahy6olyf",
parentId: "b6wgydyko8",
},
],
rightColumn: 301.5,
widgetId: "b6wgydyko8",
parentId: "vibz0hwj64",
},
],
rightColumn: 62.0,
parentId: "0",
},
] as unknown as DSLWidget[];
const convertedChildren = [
{
alignment: "start",
bottomRow: 4,
boxShadow: "none",
flexVerticalAlignment: "end",
leftColumn: 0,
responsiveBehavior: "hug",
rightColumn: 16,
topRow: 0,
type: "BUTTON_WIDGET",
widgetId: "oc0e52x3mq",
widgetName: "Button1",
},
{
alignment: "end",
bottomRow: 9,
flexVerticalAlignment: "end",
leftColumn: 23,
responsiveBehavior: "hug",
rightColumn: 43,
topRow: 2,
type: "INPUT_WIDGET_V2",
widgetId: "50rdpq2yow",
widgetName: "Input1",
},
{
alignment: "end",
bottomRow: 4,
flexVerticalAlignment: "end",
leftColumn: 48,
responsiveBehavior: "hug",
rightColumn: 64,
topRow: 0,
type: "BUTTON_WIDGET",
widgetId: "em4ubqs787",
widgetName: "Button3",
},
{
alignment: "start",
bottomRow: 50,
children: [
{
bottomRow: 100,
children: [
{
alignment: "start",
bottomRow: 5,
flexVerticalAlignment: "end",
leftColumn: 1.5,
parentId: "lwl0t7o358",
responsiveBehavior: "hug",
rightColumn: 25.5,
topRow: 1,
type: "TEXT_WIDGET",
widgetId: "y1u22x7gj9",
widgetName: "Text1",
},
{
alignment: "end",
bottomRow: 37,
flexVerticalAlignment: "end",
leftColumn: 30,
parentId: "lwl0t7o358",
responsiveBehavior: "hug",
rightColumn: 46,
topRow: 33,
type: "BUTTON_WIDGET",
widgetName: "Button5",
},
{
alignment: "end",
bottomRow: 37,
flexVerticalAlignment: "end",
leftColumn: 46,
parentId: "lwl0t7o358",
responsiveBehavior: "hug",
rightColumn: 62,
topRow: 33,
type: "BUTTON_WIDGET",
widgetId: "7dnsyyas3b",
widgetName: "Button4",
},
],
flexLayers: [
{
children: [
{
align: "start",
id: "y1u22x7gj9",
},
],
},
{
children: [
{
align: "end",
id: undefined,
},
{
align: "end",
id: "7dnsyyas3b",
},
],
},
],
leftColumn: 0,
minHeight: 100,
parentId: "quvrkp960y",
positioning: "vertical",
responsiveBehavior: "fill",
topRow: 0,
type: "CANVAS_WIDGET",
useAutoLayout: true,
widgetId: "lwl0t7o358",
widgetName: "Canvas1",
},
],
flexVerticalAlignment: "end",
leftColumn: 2,
parentId: "0",
responsiveBehavior: "hug",
rightColumn: 26,
topRow: 11,
type: "FORM_WIDGET",
widgetId: "quvrkp960y",
widgetName: "Form1",
},
{
alignment: "start",
bottomRow: 30,
flexVerticalAlignment: "end",
leftColumn: 30,
parentId: "0",
parentRowSpace: 10,
responsiveBehavior: "hug",
rightColumn: 46,
topRow: 26,
type: "BUTTON_WIDGET",
widgetId: "e9fhrq8uvf",
widgetName: "Button6",
},
{
alignment: "end",
bottomRow: 61,
children: [
{
bottomRow: 250,
children: [
{
alignment: "start",
bottomRow: 23,
children: [
{
bottomRow: 100,
children: [
{
alignment: "start",
bottomRow: 4,
flexVerticalAlignment: "end",
leftColumn: 2,
parentId: "se4m3djd2t",
responsiveBehavior: "hug",
rightColumn: 18,
topRow: 0,
type: "BUTTON_WIDGET",
widgetId: "o529pnktws",
widgetName: "Button9",
},
{
alignment: "center",
bottomRow: 11,
flexVerticalAlignment: "end",
leftColumn: 33,
parentId: "se4m3djd2t",
responsiveBehavior: "hug",
rightColumn: 49,
topRow: 7,
type: "BUTTON_WIDGET",
widgetId: "vf1wsdypci",
widgetName: "Button10",
},
],
flexLayers: [
{
children: [
{
align: "start",
id: "o529pnktws",
},
],
},
{
children: [
{
align: "center",
id: "vf1wsdypci",
},
],
},
],
leftColumn: 0,
minHeight: 100,
parentId: "x7ahy6olyf",
positioning: "vertical",
responsiveBehavior: "fill",
rightColumn: 105.5625,
topRow: 0,
type: "CANVAS_WIDGET",
useAutoLayout: true,
widgetId: "se4m3djd2t",
widgetName: "Canvas4",
},
],
flexVerticalAlignment: "end",
leftColumn: 0,
parentId: "b6wgydyko8",
responsiveBehavior: "hug",
rightColumn: 24,
topRow: 10,
type: "CONTAINER_WIDGET",
widgetId: "x7ahy6olyf",
widgetName: "Container2",
},
{
alignment: "end",
bottomRow: 13,
children: [
{
bottomRow: 100,
children: [
{
alignment: "start",
bottomRow: 4,
flexVerticalAlignment: "end",
leftColumn: 2,
parentId: "vap4aivehm",
responsiveBehavior: "hug",
rightColumn: 18,
topRow: 0,
type: "BUTTON_WIDGET",
widgetId: "rbgq3cl9j0",
widgetName: "Button9Copy",
},
{
alignment: "center",
bottomRow: 11,
flexVerticalAlignment: "end",
leftColumn: 33,
parentId: "vap4aivehm",
responsiveBehavior: "hug",
rightColumn: 49,
topRow: 7,
type: "BUTTON_WIDGET",
widgetId: "to5e5cr2ph",
widgetName: "Button10Copy",
},
],
flexLayers: [
{
children: [
{
align: "start",
id: "rbgq3cl9j0",
},
],
},
{
children: [
{
align: "center",
id: "to5e5cr2ph",
},
],
},
],
leftColumn: 0,
minHeight: 100,
parentId: "pd2zln825w",
positioning: "vertical",
responsiveBehavior: "fill",
rightColumn: 105.5625,
topRow: 0,
type: "CANVAS_WIDGET",
useAutoLayout: true,
widgetId: "vap4aivehm",
widgetName: "Canvas4Copy",
},
],
flexVerticalAlignment: "end",
leftColumn: 36,
parentId: "b6wgydyko8",
renderMode: "CANVAS",
responsiveBehavior: "hug",
rightColumn: 60,
topRow: 0,
type: "CONTAINER_WIDGET",
widgetId: "pd2zln825w",
widgetName: "Container2Copy",
},
],
flexLayers: [
{
children: [
{
align: "start",
id: "x7ahy6olyf",
},
{
align: "end",
id: "pd2zln825w",
},
],
},
],
leftColumn: 0,
minHeight: 250,
parentId: "vibz0hwj64",
positioning: "vertical",
responsiveBehavior: "fill",
rightColumn: 301.5,
topRow: 0,
type: "CANVAS_WIDGET",
useAutoLayout: true,
widgetId: "b6wgydyko8",
widgetName: "Canvas3",
},
],
flexVerticalAlignment: "end",
leftColumn: 38,
parentId: "0",
responsiveBehavior: "hug",
rightColumn: 62,
topRow: 36,
type: "CONTAINER_WIDGET",
widgetName: "Container1",
},
{
bottomRow: 256,
children: [],
leftColumn: 9,
parentId: "0",
parentRowSpace: 10,
responsiveBehavior: "hug",
rightColumn: 33,
topRow: 16,
type: "MODAL_WIDGET",
widgetId: "tf847brtfd",
widgetName: "Modal1",
},
];
it("test getAutoCanvasWidget method to add responsive props to dsl", () => {
const canvasDsl = {
type: "CANVAS_WIDGET",
widgetId: "0",
leftColumn: 40,
rightColumn: 340,
topRow: 20,
bottomRow: 400,
minHeight: 400,
children: [],
};
const responsiveCanvasDsl = {
type: "CANVAS_WIDGET",
widgetId: "0",
leftColumn: 40,
rightColumn: 340,
topRow: 20,
bottomRow: 400,
minHeight: 400,
children: [],
useAutoLayout: true,
responsiveBehavior: ResponsiveBehavior.Fill,
positioning: Positioning.Vertical,
flexLayers: [],
};
expect(getAutoCanvasWidget(canvasDsl as unknown as DSLWidget)).toEqual(
responsiveCanvasDsl,
);
});
it("test fitChildWidgetsIntoLayers method", () => {
const flexLayers = [
{
children: [
{
align: "start",
id: "oc0e52x3mq",
},
{
align: "end",
id: "50rdpq2yow",
},
{
align: "end",
id: "em4ubqs787",
},
],
},
{
children: [
{
align: "start",
id: "quvrkp960y",
},
{
align: "start",
id: "e9fhrq8uvf",
},
],
},
{
children: [
{
align: "end",
id: undefined,
},
],
},
{
children: [
{
align: "center",
id: "tf847brtfd",
},
],
},
];
const calculatedBottomRow = 75;
expect(
fitChildWidgetsIntoLayers(childWidgets as unknown as DSLWidget[]),
).toEqual({ children: convertedChildren, flexLayers, calculatedBottomRow });
});
it("test getTopLeftMostWidget method should return the left most widget in the layer", () => {
const topLeftMostWidget = {
bottomRow: 4,
boxShadow: "none",
leftColumn: 0,
rightColumn: 16,
topRow: 0,
type: "BUTTON_WIDGET",
widgetId: "oc0e52x3mq",
widgetName: "Button1",
};
expect(getTopLeftMostWidget(childWidgets)).toEqual({
topLeftMostWidget,
index: 0,
});
});
it("test processGroupedWidgets and condensedGroupedWidgets to get Alignments based on groups", () => {
const groups = [
{
widgets: ["1", "2"],
leftColumn: 3,
rightColumn: 11, //7
},
{
widgets: ["3", "4"],
leftColumn: 18,
rightColumn: 27, //9
},
{
widgets: ["5", "6"],
leftColumn: 36,
rightColumn: 43, //7
},
{
widgets: ["7", "8"],
leftColumn: 50,
rightColumn: 54, //8
},
{
widgets: ["9", "10"],
leftColumn: 62,
rightColumn: 64,
},
];
const condensedGroups = [
{
leftColumn: 3,
rightColumn: 27,
widgets: ["1", "2", "3", "4"],
},
{
leftColumn: 3,
rightColumn: 54,
widgets: ["5", "6", "7", "8"],
},
{
leftColumn: 3,
rightColumn: 64,
widgets: ["9", "10"],
},
];
const widgetAlignments = {
"1": "start",
"2": "start",
"3": "start",
"4": "start",
"5": "center",
"6": "center",
"7": "center",
"8": "center",
"9": "end",
"10": "end",
};
expect(getCondensedGroupedWidgets(groups)).toEqual(condensedGroups);
expect(processGroupedWidgets(groups)).toEqual(widgetAlignments);
});
});
|
295 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/common | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/common/dropTarget/DragLayerComponent.test.tsx | import React from "react";
import { ThemeProvider } from "styled-components";
import TestRenderer from "react-test-renderer";
import DragLayerComponent from "./DragLayerComponent";
import { RenderModes } from "constants/WidgetConstants";
import { theme } from "constants/DefaultTheme";
describe("DragLayerComponent", () => {
it("it checks noPad prop", () => {
const dummyWidget = {
type: "CANVAS_WIDGET",
widgetId: "0",
widgetName: "canvas",
parentColumnSpace: 1,
parentRowSpace: 1,
parentRowHeight: 0,
canDropTargetExtend: false,
parentColumnWidth: 0,
leftColumn: 0,
visible: true,
rightColumn: 0,
topRow: 0,
bottomRow: 0,
version: 17,
isLoading: false,
renderMode: RenderModes.CANVAS,
children: [],
noPad: true,
onBoundsUpdate: () => {
//
},
isOver: true,
parentWidgetId: "parent",
force: true,
};
const testRenderer = TestRenderer.create(
<ThemeProvider theme={theme}>
<DragLayerComponent {...dummyWidget} />
</ThemeProvider>,
);
const testInstance = testRenderer.root;
expect(testInstance.findByType(DragLayerComponent).props.noPad).toBe(true);
});
});
|
308 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/common | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/common/resizer/ResizableUtils.test.ts | import { ReflowDirection } from "reflow/reflowTypes";
import { isHandleResizeAllowed } from "./ResizableUtils";
describe("Resizable Utils", () => {
it("Handle resize is allowed if directions are not provided", () => {
const input = {
horizontalEnabled: false,
verticalEnabled: false,
};
const result = isHandleResizeAllowed(
input.horizontalEnabled,
input.verticalEnabled,
);
expect(result).toBe(true);
});
it("Handle resize is allowed if directions provided are not vertical or horizontal", () => {
const input = {
horizontalEnabled: false,
verticalEnabled: false,
direction: ReflowDirection.BOTTOMLEFT,
};
const result = isHandleResizeAllowed(
input.horizontalEnabled,
input.verticalEnabled,
input.direction,
);
expect(result).toBe(true);
});
it("Handle resize is allowed if horizontal resize is enabled and directs are left and right", () => {
const input = [
{
horizontalEnabled: true,
verticalEnabled: false,
direction: ReflowDirection.LEFT,
},
{
horizontalEnabled: true,
verticalEnabled: false,
direction: ReflowDirection.RIGHT,
},
];
input.forEach((_input) => {
const result = isHandleResizeAllowed(
_input.horizontalEnabled,
_input.verticalEnabled,
_input.direction,
);
expect(result).toBe(true);
});
});
it("Handle resize is disallowed if horizontal resize is disabled and directs are left and right", () => {
const input = [
{
horizontalEnabled: false,
verticalEnabled: false,
direction: ReflowDirection.LEFT,
},
{
horizontalEnabled: false,
verticalEnabled: false,
direction: ReflowDirection.RIGHT,
},
];
input.forEach((_input) => {
const result = isHandleResizeAllowed(
_input.horizontalEnabled,
_input.verticalEnabled,
_input.direction,
);
expect(result).toBe(false);
});
});
it("Handle resize is allowed if vertical resize is enabled and directs are top and bottom", () => {
const input = [
{
horizontalEnabled: true,
verticalEnabled: true,
direction: ReflowDirection.TOP,
},
{
horizontalEnabled: true,
verticalEnabled: true,
direction: ReflowDirection.BOTTOM,
},
];
input.forEach((_input) => {
const result = isHandleResizeAllowed(
_input.horizontalEnabled,
_input.verticalEnabled,
_input.direction,
);
expect(result).toBe(true);
});
});
it("Handle resize is disallowed if vertical resize is disabled and directs are top and bottom", () => {
const input = [
{
horizontalEnabled: false,
verticalEnabled: false,
direction: ReflowDirection.TOP,
},
{
horizontalEnabled: false,
verticalEnabled: false,
direction: ReflowDirection.BOTTOM,
},
];
input.forEach((_input) => {
const result = isHandleResizeAllowed(
_input.horizontalEnabled,
_input.verticalEnabled,
_input.direction,
);
expect(result).toBe(false);
});
});
});
|
316 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/common | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/common/utils/canvasDraggingUtils.test.ts | import { GridDefaults } from "constants/WidgetConstants";
import {
HORIZONTAL_RESIZE_MIN_LIMIT,
ReflowDirection,
VERTICAL_RESIZE_MIN_LIMIT,
} from "reflow/reflowTypes";
import {
getEdgeDirection,
getMoveDirection,
getReflowedSpaces,
modifyBlockDimension,
modifyDrawingRectangles,
updateRectanglesPostReflow,
} from "./canvasDraggingUtils";
describe("test canvasDraggingUtils Methods", () => {
describe("test getEdgeDirection method", () => {
it("should return RIGHT if closest to left edge", () => {
expect(getEdgeDirection(5, 10, 100, ReflowDirection.UNSET)).toEqual(
ReflowDirection.RIGHT,
);
});
it("should return BOTTOM if closest to left edge", () => {
expect(getEdgeDirection(10, 5, 100, ReflowDirection.UNSET)).toEqual(
ReflowDirection.BOTTOM,
);
});
it("should return LEFT if closest to left edge", () => {
expect(getEdgeDirection(95, 10, 100, ReflowDirection.UNSET)).toEqual(
ReflowDirection.LEFT,
);
});
it("should return current direction if width is undefined", () => {
expect(getEdgeDirection(5, 10, undefined, ReflowDirection.UNSET)).toEqual(
ReflowDirection.UNSET,
);
});
});
it("test getReflowedSpaces method, should return reflowed spaces", () => {
const occupiedSpace = {
id: "id",
left: 10,
top: 10,
right: 50,
bottom: 70,
};
const reflowingWidgets = {
id: {
X: 30,
Y: 40,
width: 300,
height: 500,
},
};
const reflowedSpace = {
id: "id",
left: 13,
top: 14,
right: 43,
bottom: 64,
};
expect(getReflowedSpaces(occupiedSpace, reflowingWidgets, 10, 10)).toEqual(
reflowedSpace,
);
});
it("test modifyDrawingRectangles method, should return widgetDraggingBlock with dimensions of the space widget", () => {
const drawingRectangles = {
left: 104,
top: 102,
width: 600,
height: 900,
columnWidth: 60,
rowHeight: 90,
widgetId: "id",
isNotColliding: true,
type: "CANVAS_WIDGET",
};
const spaceMap = {
id: {
left: 25,
top: 30,
right: 65,
bottom: 80,
id: "id",
},
};
const modifiedRectangle = {
left: 254,
top: 302,
width: 400,
height: 500,
columnWidth: 40,
rowHeight: 50,
widgetId: "id",
isNotColliding: true,
type: "CANVAS_WIDGET",
};
expect(
modifyDrawingRectangles([drawingRectangles], spaceMap, 10, 10),
).toEqual([modifiedRectangle]);
});
describe("test getMoveDirection method", () => {
const prevPosition = {
id: "id",
left: 10,
top: 20,
right: 30,
bottom: 40,
};
it("should return RIGHT when moved to Right", () => {
const currentPosition = {
id: "id",
left: 11,
top: 20,
right: 31,
bottom: 40,
};
expect(
getMoveDirection(prevPosition, currentPosition, ReflowDirection.UNSET),
).toEqual(ReflowDirection.RIGHT);
});
it("should return BOTTOM when moved to bottom", () => {
const currentPosition = {
id: "id",
left: 10,
top: 21,
right: 30,
bottom: 41,
};
expect(
getMoveDirection(prevPosition, currentPosition, ReflowDirection.UNSET),
).toEqual(ReflowDirection.BOTTOM);
});
it("should return LEFT when moved to left", () => {
const currentPosition = {
id: "id",
left: 9,
top: 20,
right: 29,
bottom: 40,
};
expect(
getMoveDirection(prevPosition, currentPosition, ReflowDirection.UNSET),
).toEqual(ReflowDirection.LEFT);
});
it("should return TOP when moved to top", () => {
const currentPosition = {
id: "id",
left: 10,
top: 19,
right: 30,
bottom: 39,
};
expect(
getMoveDirection(prevPosition, currentPosition, ReflowDirection.UNSET),
).toEqual(ReflowDirection.TOP);
});
});
describe("test modifyBlockDimension method", () => {
it("should return resized dragging blocks while colliding with canvas edges, for top Left", () => {
const draggingBlock = {
left: -300,
top: -700,
width: 600,
height: 900,
columnWidth: 60,
rowHeight: 90,
widgetId: "id",
isNotColliding: true,
type: "CANVAS_WIDGET",
};
const modifiedBlock = {
left: 0,
top: 0,
width: 300,
height: 200,
columnWidth: 30,
rowHeight: 20,
widgetId: "id",
isNotColliding: true,
type: "CANVAS_WIDGET",
};
expect(
modifyBlockDimension(draggingBlock, 10, 10, 100, true, false),
).toEqual(modifiedBlock);
});
it("should return resized dragging blocks while colliding with canvas edges to it's limits, for top Left", () => {
const draggingBlock = {
left: -300,
top: -700,
width: 310,
height: 720,
columnWidth: 31,
rowHeight: 72,
widgetId: "id",
isNotColliding: true,
type: "CANVAS_WIDGET",
};
const modifiedBlock = {
left: -10,
top: -20,
width: HORIZONTAL_RESIZE_MIN_LIMIT * 10,
height: VERTICAL_RESIZE_MIN_LIMIT * 10,
columnWidth: HORIZONTAL_RESIZE_MIN_LIMIT,
rowHeight: VERTICAL_RESIZE_MIN_LIMIT,
widgetId: "id",
isNotColliding: true,
type: "CANVAS_WIDGET",
};
expect(
modifyBlockDimension(draggingBlock, 10, 10, 100, true, false),
).toEqual(modifiedBlock);
});
it("should return resized dragging blocks while colliding with canvas edges, for bottom right", () => {
const draggingBlock = {
left: 400,
top: 600,
width: 600,
height: 900,
columnWidth: 60,
rowHeight: 90,
widgetId: "id",
isNotColliding: true,
type: "CANVAS_WIDGET",
};
const modifiedBlock = {
left: 400,
top: 600,
width: GridDefaults.DEFAULT_GRID_COLUMNS * 10 - 400,
height: 400,
columnWidth: GridDefaults.DEFAULT_GRID_COLUMNS - 40,
rowHeight: 40,
widgetId: "id",
isNotColliding: true,
type: "CANVAS_WIDGET",
};
expect(
modifyBlockDimension(draggingBlock, 10, 10, 100, false, false),
).toEqual(modifiedBlock);
});
it("should return resized dragging blocks while colliding with canvas edges to it's limits, for bottom right", () => {
const draggingBlock = {
left: 630,
top: 600,
width: 600,
height: 900,
columnWidth: 60,
rowHeight: 90,
widgetId: "id",
isNotColliding: true,
fixedHeight: 90,
type: "CANVAS_WIDGET",
};
const modifiedBlock = {
left: 630,
top: 600,
width: HORIZONTAL_RESIZE_MIN_LIMIT * 10,
height: 900,
columnWidth: HORIZONTAL_RESIZE_MIN_LIMIT,
rowHeight: 90,
widgetId: "id",
isNotColliding: true,
fixedHeight: 90,
type: "CANVAS_WIDGET",
};
expect(
modifyBlockDimension(draggingBlock, 10, 10, 100, false, false),
).toEqual(modifiedBlock);
});
});
describe("should test updateRectanglesPostReflow method", () => {
it("should update noCollision properties based on respective rectangles", () => {
const rectanglesToDraw = [
{
left: -10,
top: 200,
width: 600,
height: 900,
columnWidth: 60,
rowHeight: 90,
widgetId: "1",
isNotColliding: true,
type: "CANVAS_WIDGET",
},
{
left: 100,
top: 200,
width: 700,
height: 950,
columnWidth: 70,
rowHeight: 95,
widgetId: "2",
isNotColliding: true,
type: "CANVAS_WIDGET",
},
{
left: 300,
top: 100,
width: 200,
height: 340,
columnWidth: 20,
rowHeight: 34,
widgetId: "3",
isNotColliding: true,
type: "CANVAS_WIDGET",
},
{
left: 400,
top: 500,
width: 200,
height: 120,
columnWidth: 20,
rowHeight: 12,
widgetId: "4",
isNotColliding: true,
type: "CANVAS_WIDGET",
},
];
const result = [
{
left: -10,
top: 200,
width: 600,
height: 900,
columnWidth: 60,
rowHeight: 90,
widgetId: "1",
isNotColliding: false,
type: "CANVAS_WIDGET",
},
{
left: 100,
top: 200,
width: 700,
height: 950,
columnWidth: 70,
rowHeight: 95,
widgetId: "2",
isNotColliding: false,
type: "CANVAS_WIDGET",
},
{
left: 300,
top: 100,
width: 200,
height: 340,
columnWidth: 20,
rowHeight: 34,
widgetId: "3",
isNotColliding: false,
type: "CANVAS_WIDGET",
},
{
left: 400,
top: 500,
width: 200,
height: 120,
columnWidth: 20,
rowHeight: 12,
widgetId: "4",
isNotColliding: true,
type: "CANVAS_WIDGET",
},
];
const movementLimitMap = {
"1": {
canHorizontalMove: true,
canVerticalMove: true,
},
"2": {
canHorizontalMove: true,
canVerticalMove: true,
},
"3": {
canHorizontalMove: true,
canVerticalMove: false,
},
"4": {
canHorizontalMove: true,
canVerticalMove: true,
},
};
expect(
updateRectanglesPostReflow(
movementLimitMap,
rectanglesToDraw,
10,
10,
2000,
),
).toEqual(result);
});
});
});
|
320 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/common | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/common/utils/commonUtils.test.tsx | import type {
AutoDimensionOptions,
AutoDimensionValues,
AutoLayoutConfig,
} from "WidgetProvider/constants";
import {
getAutoDimensionsConfig,
restructureWidgetSizeConfig,
} from "./commonUtils";
import InputWidget from "widgets/InputWidgetV2/widget";
import ButtonWidget from "widgets/ButtonWidget/widget";
import { mockInputProps } from "mocks/widgetProps/input";
describe("Common Utils tests", () => {
describe("getAutoDimensionsConfig", () => {
it("autoDimension.height for InputWidgetV2 should be true", () => {
const config: AutoLayoutConfig | undefined =
InputWidget.getAutoLayoutConfig();
const autoDimension: AutoDimensionOptions | undefined =
getAutoDimensionsConfig(config || {}, mockInputProps());
expect((autoDimension as AutoDimensionValues)?.height).toBeTruthy();
});
it("autoDimension.width for button widget should be true", () => {
const config: AutoLayoutConfig | undefined =
ButtonWidget.getAutoLayoutConfig();
const autoDimension: AutoDimensionOptions | undefined =
getAutoDimensionsConfig(config || {}, {
...mockInputProps(),
type: "BUTTON_WIDGET",
});
expect((autoDimension as AutoDimensionValues)?.width).toBeTruthy();
expect((autoDimension as AutoDimensionValues)?.height).toBeFalsy();
});
});
describe("restructureWidgetSizeConfig", () => {
it("should return widget size config in the structure accepted by WDS Flex component - BUTTON widget", () => {
const config: AutoLayoutConfig | undefined =
ButtonWidget.getAutoLayoutConfig();
const sizeConfig: {
maxHeight: Record<string, string | number>;
maxWidth: Record<string, string | number>;
minHeight: Record<string, string | number>;
minWidth: Record<string, string | number>;
} = restructureWidgetSizeConfig(config?.widgetSize || [], {
...mockInputProps(),
type: "BUTTON_WIDGET",
});
expect(sizeConfig.minWidth.base).toEqual("120px");
expect(sizeConfig.minHeight.base).toEqual("40px");
expect(sizeConfig.maxWidth.base).toEqual("360px");
expect(sizeConfig.maxHeight.base).toBeFalsy();
});
it("should return widget size config in the structure accepted by WDS Flex component - INPUT widget", () => {
const config: AutoLayoutConfig | undefined =
InputWidget.getAutoLayoutConfig();
const sizeConfig: {
maxHeight: Record<string, string | number>;
maxWidth: Record<string, string | number>;
minHeight: Record<string, string | number>;
minWidth: Record<string, string | number>;
} = restructureWidgetSizeConfig(
config?.widgetSize || [],
mockInputProps(),
);
expect(sizeConfig.minWidth.base).toEqual("120px");
expect(sizeConfig.minHeight.base).toBeFalsy();
expect(sizeConfig.maxWidth.base).toBeFalsy();
expect(sizeConfig.maxHeight.base).toBeFalsy();
});
});
});
|
340 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/fixedlayout/common | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/fixedlayout/common/autoHeight/AutoHeightContainer.test.tsx | import "@testing-library/jest-dom";
import { render } from "@testing-library/react";
import "jest-styled-components";
import React from "react";
import renderer from "react-test-renderer";
import { RenderModes } from "constants/WidgetConstants";
import AutoHeightContainer from "./AutoHeightContainer";
const DUMMY_WIDGET = {
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("<AutoHeightContainer />", () => {
it("should wrap the children in a div whose height is auto.", async () => {
const tree = renderer
.create(
<AutoHeightContainer
isAutoHeightWithLimits={false}
maxDynamicHeight={0}
minDynamicHeight={0}
widgetHeightInPixels={200}
widgetProps={DUMMY_WIDGET}
>
<div data-testid="test" />
</AutoHeightContainer>,
)
.toJSON();
expect(tree).toHaveStyleRule("height", "100%");
});
describe("when isAutoHeightWithLimits is false.", () => {
it("should wrap the children in a simple div with class auto-height-container", async () => {
const getTestComponent = () => (
<AutoHeightContainer
isAutoHeightWithLimits={false}
maxDynamicHeight={0}
minDynamicHeight={0}
widgetHeightInPixels={200}
widgetProps={DUMMY_WIDGET}
>
<div data-testid="test" />
</AutoHeightContainer>
);
const component = getTestComponent();
const renderResult = render(component);
const child = await renderResult.findByTestId("test");
expect(
child.parentElement?.classList.contains("auto-height-container"),
).toBe(true);
});
});
describe("when isAutoHeightWithLimits is true", () => {
it("should wrap the children in a div of class auto-height-container and then a div with class auto-height-scroll-container", async () => {
const getTestComponent = () => (
<AutoHeightContainer
isAutoHeightWithLimits
maxDynamicHeight={0}
minDynamicHeight={0}
widgetHeightInPixels={200}
widgetProps={DUMMY_WIDGET}
>
<div data-testid="test" />
</AutoHeightContainer>
);
const component = getTestComponent();
const renderResult = render(component);
const child = await renderResult.findByTestId("test");
expect(child.parentElement?.tagName).toBe("DIV");
expect(
child.parentElement?.classList.contains("auto-height-container"),
).toBe(true);
expect(
child.parentElement?.parentElement?.parentElement?.classList.contains(
"auto-height-scroll-container",
),
).toBe(true);
});
});
});
|
353 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/fixedlayout/common/autoHeightOverlay | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/fixedlayout/common/autoHeightOverlay/ui/AutoHeightLimitHandleBorder.test.tsx | import React from "react";
import "@testing-library/jest-dom";
import AutoHeightLimitHandleBorder from "./AutoHeightLimitHandleBorder";
import "jest-styled-components";
import renderer from "react-test-renderer";
import { OVERLAY_COLOR } from "../constants";
describe("<AutoHeightLimitHandleBorder />", () => {
it("should have background-color style set to OVERLAY_COLOR when isActive is true", () => {
const tree = renderer
.create(<AutoHeightLimitHandleBorder isActive />)
.toJSON();
expect(tree).toHaveStyleRule("background-color", OVERLAY_COLOR);
});
it("should have background-color style set to undefined when isActive is false", () => {
const tree = renderer
.create(<AutoHeightLimitHandleBorder isActive={false} />)
.toJSON();
expect(tree).toHaveStyleRule("background-color");
});
});
|
355 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/fixedlayout/common/autoHeightOverlay | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/fixedlayout/common/autoHeightOverlay/ui/AutoHeightLimitHandleDot.test.tsx | import React from "react";
import "@testing-library/jest-dom";
import AutoHeightLimitHandleDot from "./AutoHeightLimitHandleDot";
import "jest-styled-components";
import renderer from "react-test-renderer";
describe("<AutoHeightLimitHandleDot />", () => {
it("should have scale style set to 1 when isDragging is false", () => {
const tree = renderer
.create(<AutoHeightLimitHandleDot isDragging={false} />)
.toJSON();
expect(tree).toHaveStyleRule("transform", "translateX(-50%) scale( 1 )");
});
it("should have scale style set to 1.67 when isDragging is true", () => {
const tree = renderer
.create(<AutoHeightLimitHandleDot isDragging />)
.toJSON();
expect(tree).toHaveStyleRule("transform", "translateX(-50%) scale( 1.67 )");
});
});
|
357 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/fixedlayout/common/autoHeightOverlay | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/fixedlayout/common/autoHeightOverlay/ui/AutoHeightLimitHandleLabel.test.tsx | import React from "react";
import "@testing-library/jest-dom";
import AutoHeightLimitHandleLabel from "./AutoHeightLimitHandleLabel";
import "jest-styled-components";
import renderer from "react-test-renderer";
describe("<AutoHeightLimitHandleLabel />", () => {
it("should have display none when isActive is false", () => {
const tree = renderer
.create(<AutoHeightLimitHandleLabel isActive={false} />)
.toJSON();
expect(tree).toHaveStyleRule("display", "none");
});
it("should have display initial when isActive is true", () => {
const tree = renderer
.create(<AutoHeightLimitHandleLabel isActive />)
.toJSON();
expect(tree).toHaveStyleRule("display", "initial");
});
});
|
359 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/fixedlayout/common/autoHeightOverlay | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/fixedlayout/common/autoHeightOverlay/ui/AutoHeightLimitOverlayDisplay.test.tsx | import React from "react";
import "@testing-library/jest-dom";
import AutoHeightLimitOverlayDisplay from "./AutoHeightLimitOverlayDisplay";
import "jest-styled-components";
import renderer from "react-test-renderer";
describe("<AutoHeightLimitOverlayDisplay />", () => {
it("should have display none when isActive is false", () => {
const tree = renderer
.create(<AutoHeightLimitOverlayDisplay height={0} isActive={false} />)
.toJSON();
expect(tree).toHaveStyleRule("display", "none");
});
it("should have display block when isActive is true", () => {
const tree = renderer
.create(<AutoHeightLimitOverlayDisplay height={0} isActive />)
.toJSON();
expect(tree).toHaveStyleRule("display", "block");
});
it("should have height style equal to the height passed in props", () => {
const tree = renderer
.create(<AutoHeightLimitOverlayDisplay height={10} isActive />)
.toJSON();
expect(tree).toHaveStyleRule("height", "10px");
});
});
|
368 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/fixedlayout/editor | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/fixedlayout/editor/FixedLayoutCanvasArenas/CanvasSelectionArena.test.tsx | import { MAIN_CONTAINER_WIDGET_ID } from "constants/WidgetConstants";
import Canvas from "pages/Editor/Canvas";
import GlobalHotKeys from "pages/Editor/GlobalHotKeys";
import React from "react";
import { MemoryRouter } from "react-router-dom";
import * as dataTreeSelectors from "selectors/dataTreeSelectors";
import * as utilities from "selectors/editorSelectors";
import store from "store";
import {
buildChildren,
widgetCanvasFactory,
} from "test/factories/WidgetFactoryUtils";
import { sagasToRunForTests } from "test/sagas";
import {
MockApplication,
mockCreateCanvasWidget,
mockGetCanvasWidgetDsl,
mockGetWidgetEvalValues,
MockPageDSL,
syntheticTestMouseEvent,
} from "test/testCommon";
import { UpdatedEditor } from "test/testMockedWidgets";
import { act, fireEvent, render } from "test/testUtils";
import { generateReactKey } from "utils/generators";
import * as widgetRenderUtils from "utils/widgetRenderUtils";
import * as widgetSelectionsActions from "actions/widgetSelectionActions";
import { SelectionRequestType } from "sagas/WidgetSelectUtils";
describe("Canvas selection test cases", () => {
jest
.spyOn(dataTreeSelectors, "getWidgetEvalValues")
.mockImplementation(mockGetWidgetEvalValues);
jest
.spyOn(utilities, "computeMainContainerWidget")
.mockImplementation((widget) => widget as any);
jest
.spyOn(widgetRenderUtils, "createCanvasWidget")
.mockImplementation(mockCreateCanvasWidget);
const spyWidgetSelection = jest.spyOn(
widgetSelectionsActions,
"selectWidgetInitAction",
);
beforeEach(() => {
spyWidgetSelection.mockClear();
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
it("Should select using canvas draw", () => {
const children: any = buildChildren([
{
type: "TABS_WIDGET",
topRow: 5,
bottomRow: 30,
leftColumn: 5,
rightColumn: 30,
widgetId: "tabsWidgetId",
},
{
type: "SWITCH_WIDGET",
topRow: 5,
bottomRow: 10,
leftColumn: 40,
rightColumn: 48,
widgetId: "switchWidgetId",
},
]);
const dsl: any = widgetCanvasFactory.build({
children,
});
const mockGetIsFetchingPage = jest.spyOn(utilities, "getIsFetchingPage");
const spyGetCanvasWidgetDsl = jest.spyOn(utilities, "getCanvasWidgetDsl");
spyGetCanvasWidgetDsl.mockImplementation(mockGetCanvasWidgetDsl);
mockGetIsFetchingPage.mockImplementation(() => false);
const component = render(
<MemoryRouter
initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]}
>
<MockApplication>
<GlobalHotKeys>
<UpdatedEditor dsl={dsl} />
</GlobalHotKeys>
</MockApplication>
</MemoryRouter>,
{ initialState: store.getState(), sagasToRun: sagasToRunForTests },
);
let selectionCanvas: any = component.queryByTestId(
`canvas-selection-${MAIN_CONTAINER_WIDGET_ID}`,
);
const selectionDiv: any = component.queryByTestId(
`div-selection-${MAIN_CONTAINER_WIDGET_ID}`,
);
expect(selectionCanvas.style.zIndex).toBe("");
fireEvent.mouseDown(selectionDiv);
selectionCanvas = component.queryByTestId(
`canvas-selection-${MAIN_CONTAINER_WIDGET_ID}`,
);
expect(selectionCanvas.style.zIndex).toBe("2");
fireEvent.mouseUp(selectionDiv);
selectionCanvas = component.queryByTestId(
`canvas-selection-${MAIN_CONTAINER_WIDGET_ID}`,
);
expect(selectionCanvas.style.zIndex).toBe("");
});
it("Should select all elements using canvas from top to bottom", () => {
const children: any = buildChildren([
{
type: "TABS_WIDGET",
topRow: 1,
bottomRow: 3,
leftColumn: 1,
rightColumn: 3,
parentId: MAIN_CONTAINER_WIDGET_ID,
widgetId: "tabsWidgetId",
},
{
type: "SWITCH_WIDGET",
topRow: 1,
bottomRow: 2,
leftColumn: 5,
rightColumn: 13,
parentId: MAIN_CONTAINER_WIDGET_ID,
widgetId: "switchWidgetId",
},
]);
const dsl: any = widgetCanvasFactory.build({
children,
});
const mockGetIsFetchingPage = jest.spyOn(utilities, "getIsFetchingPage");
const spyGetCanvasWidgetDsl = jest.spyOn(utilities, "getCanvasWidgetDsl");
spyGetCanvasWidgetDsl.mockImplementation(mockGetCanvasWidgetDsl);
mockGetIsFetchingPage.mockImplementation(() => false);
const component = render(
<MemoryRouter
initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]}
>
<MockApplication>
<GlobalHotKeys>
<UpdatedEditor dsl={dsl} />
</GlobalHotKeys>
</MockApplication>
</MemoryRouter>,
{ initialState: store.getState(), sagasToRun: sagasToRunForTests },
);
const selectionDiv: any = component.queryByTestId(
`div-selection-${MAIN_CONTAINER_WIDGET_ID}`,
);
fireEvent(
selectionDiv,
syntheticTestMouseEvent(
new MouseEvent("mousedown", {
bubbles: true,
cancelable: true,
}),
{
offsetX: 10,
offsetY: 10,
},
),
);
fireEvent(
selectionDiv,
syntheticTestMouseEvent(
new MouseEvent("mousemove", {
bubbles: true,
cancelable: true,
}),
{
offsetX: dsl.rightColumn * 4,
offsetY: dsl.bottomRow * 4,
},
),
);
fireEvent(
selectionDiv,
syntheticTestMouseEvent(
new MouseEvent("mouseup", {
bubbles: true,
cancelable: true,
}),
{
offsetX: dsl.rightColumn * 4,
offsetY: dsl.bottomRow * 4,
},
),
);
expect(spyWidgetSelection).toHaveBeenCalledWith(
SelectionRequestType.Multiple,
["tabsWidgetId"],
);
expect(spyWidgetSelection).toHaveBeenCalledWith(
SelectionRequestType.Multiple,
["tabsWidgetId", "switchWidgetId"],
);
});
it("Should allow draw to select using cmd + draw in Container component", () => {
const containerId = generateReactKey();
const canvasId = generateReactKey();
const children: any = buildChildren([
{ type: "CHECKBOX_WIDGET", parentId: canvasId },
{ type: "SWITCH_WIDGET", parentId: canvasId },
{ type: "BUTTON_WIDGET", parentId: canvasId },
]);
const canvasWidget = buildChildren([
{
type: "CANVAS_WIDGET",
parentId: containerId,
children,
widgetId: canvasId,
},
]);
const containerChildren: any = buildChildren([
{
type: "CONTAINER_WIDGET",
children: canvasWidget,
widgetId: containerId,
parentId: "0",
},
{ type: "CHART_WIDGET", parentId: "0" },
]);
const dsl: any = widgetCanvasFactory.build({
children: containerChildren,
});
const mockGetIsFetchingPage = jest.spyOn(utilities, "getIsFetchingPage");
const spyGetCanvasWidgetDsl = jest.spyOn(utilities, "getCanvasWidgetDsl");
spyGetCanvasWidgetDsl.mockImplementation(mockGetCanvasWidgetDsl);
mockGetIsFetchingPage.mockImplementation(() => false);
const component = render(
<MemoryRouter
initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]}
>
<MockApplication>
<GlobalHotKeys>
<UpdatedEditor dsl={dsl} />
</GlobalHotKeys>
</MockApplication>
</MemoryRouter>,
{ initialState: store.getState(), sagasToRun: sagasToRunForTests },
);
let selectionCanvas: any = component.queryByTestId(
`canvas-selection-${canvasId}`,
);
const selectionDiv: any = component.queryByTestId(
`div-selection-${canvasId}`,
);
expect(selectionCanvas.style.zIndex).toBe("");
fireEvent.mouseDown(selectionDiv);
// should not allow draw when cmd/ctrl is not pressed
selectionCanvas = component.queryByTestId(`canvas-selection-${canvasId}`);
expect(selectionCanvas.style.zIndex).toBe("");
fireEvent.mouseDown(selectionDiv, {
metaKey: true,
});
selectionCanvas = component.queryByTestId(`canvas-selection-${canvasId}`);
expect(selectionCanvas.style.zIndex).toBe("2");
fireEvent.mouseUp(selectionDiv);
selectionCanvas = component.queryByTestId(`canvas-selection-${canvasId}`);
expect(selectionCanvas.style.zIndex).toBe("");
});
it("Should not allow draw to select using cmd + draw in drop disabled Canvas component", () => {
const containerId = generateReactKey();
const canvasId = generateReactKey();
const children: any = buildChildren([
{ type: "CHECKBOX_WIDGET", parentId: canvasId },
{ type: "SWITCH_WIDGET", parentId: canvasId },
{ type: "BUTTON_WIDGET", parentId: canvasId },
]);
const canvasWidget = buildChildren([
{
type: "CANVAS_WIDGET",
parentId: containerId,
children,
widgetId: canvasId,
dropDisabled: true,
},
]);
const containerChildren: any = buildChildren([
{
type: "CONTAINER_WIDGET",
children: canvasWidget,
widgetId: containerId,
parentId: "0",
},
{ type: "CHART_WIDGET", parentId: "0" },
]);
const dsl: any = widgetCanvasFactory.build({
children: containerChildren,
});
const component = render(
<MockPageDSL dsl={dsl}>
<Canvas
canvasWidth={dsl.rightColumn}
pageId="page_id"
widgetsStructure={dsl}
/>
</MockPageDSL>,
);
const selectionCanvas: any = component.queryByTestId(`canvas-${canvasId}`);
expect(selectionCanvas).toBeNull();
});
it("Should select all elements inside a CONTAINER using draw on canvas from top to bottom", () => {
const containerId = "containerWidget";
const canvasId = "canvasWidget";
const children: any = buildChildren([
{
type: "CHECKBOX_WIDGET",
parentColumnSpace: 10,
parentRowSpace: 10,
topRow: 1,
bottomRow: 2,
rightColumn: 1,
leftColumn: 0,
parentId: canvasId,
widgetId: "checkboxWidget",
},
{
type: "BUTTON_WIDGET",
parentColumnSpace: 10,
parentRowSpace: 10,
topRow: 1,
bottomRow: 3,
rightColumn: 2,
leftColumn: 1,
parentId: canvasId,
widgetId: "buttonWidget",
},
]);
const canvasWidget = buildChildren([
{
type: "CANVAS_WIDGET",
parentId: containerId,
bottomRow: 20,
rightColumn: 20,
children,
widgetId: canvasId,
},
]);
const containerChildren: any = buildChildren([
{
type: "CONTAINER_WIDGET",
children: canvasWidget,
widgetId: containerId,
parentColumnSpace: 10,
parentRowSpace: 10,
bottomRow: 20,
rightColumn: 20,
parentId: "0",
},
{ type: "CHART_WIDGET", parentId: "0", widgetId: "chartWidget" },
]);
const dsl: any = widgetCanvasFactory.build({
children: containerChildren,
});
const mockGetIsFetchingPage = jest.spyOn(utilities, "getIsFetchingPage");
const spyGetCanvasWidgetDsl = jest.spyOn(utilities, "getCanvasWidgetDsl");
spyGetCanvasWidgetDsl.mockImplementation(mockGetCanvasWidgetDsl);
mockGetIsFetchingPage.mockImplementation(() => false);
const component = render(
<MemoryRouter
initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]}
>
<MockApplication>
<GlobalHotKeys>
<UpdatedEditor dsl={dsl} />
</GlobalHotKeys>
</MockApplication>
</MemoryRouter>,
{ initialState: store.getState(), sagasToRun: sagasToRunForTests },
);
const selectionDiv: any = component.queryByTestId(
`div-selection-${canvasId}`,
);
fireEvent(
selectionDiv,
syntheticTestMouseEvent(
new MouseEvent("mousedown", {
metaKey: true,
bubbles: true,
cancelable: true,
}),
{
offsetX: 10,
offsetY: 10,
},
),
);
fireEvent(
selectionDiv,
syntheticTestMouseEvent(
new MouseEvent("mousemove", {
metaKey: true,
bubbles: true,
cancelable: true,
}),
{
offsetX: 800,
offsetY: 800,
},
),
);
fireEvent(
selectionDiv,
syntheticTestMouseEvent(
new MouseEvent("mouseup", {
metaKey: true,
bubbles: true,
cancelable: true,
}),
{
offsetX: 800,
offsetY: 800,
},
),
);
expect(spyWidgetSelection).toHaveBeenCalledWith(
SelectionRequestType.Multiple,
["checkboxWidget", "buttonWidget"],
);
});
it("Draw to select from outside of canvas(editor) ", () => {
const mockGetIsFetchingPage = jest.spyOn(utilities, "getIsFetchingPage");
const spyGetCanvasWidgetDsl = jest.spyOn(utilities, "getCanvasWidgetDsl");
const children: any = buildChildren([
{
type: "TABS_WIDGET",
topRow: 1,
bottomRow: 3,
leftColumn: 1,
rightColumn: 3,
parentId: MAIN_CONTAINER_WIDGET_ID,
widgetId: "tabsWidgetId",
},
{
type: "SWITCH_WIDGET",
topRow: 1,
bottomRow: 2,
leftColumn: 5,
rightColumn: 13,
parentId: MAIN_CONTAINER_WIDGET_ID,
widgetId: "switchWidgetId",
},
]);
const dsl: any = widgetCanvasFactory.build({
children,
});
spyGetCanvasWidgetDsl.mockImplementation(mockGetCanvasWidgetDsl);
mockGetIsFetchingPage.mockImplementation(() => false);
const component = render(
<MemoryRouter
initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]}
>
<MockApplication>
<GlobalHotKeys>
<UpdatedEditor dsl={dsl} />
</GlobalHotKeys>
</MockApplication>
</MemoryRouter>,
{ initialState: store.getState(), sagasToRun: sagasToRunForTests },
);
const widgetEditor: any = component.queryByTestId("widgets-editor");
let selectionCanvas: any = component.queryByTestId(
`canvas-selection-${MAIN_CONTAINER_WIDGET_ID}`,
);
const selectionDiv: any = component.queryByTestId(
`div-selection-${MAIN_CONTAINER_WIDGET_ID}`,
);
expect(selectionCanvas.style.zIndex).toBe("");
act(() => {
fireEvent.dragStart(widgetEditor);
});
selectionCanvas = component.queryByTestId(
`canvas-selection-${MAIN_CONTAINER_WIDGET_ID}`,
);
expect(selectionCanvas.style.zIndex).toBe("2");
fireEvent.mouseEnter(selectionDiv);
fireEvent.mouseUp(selectionDiv);
selectionCanvas = component.queryByTestId(
`canvas-selection-${MAIN_CONTAINER_WIDGET_ID}`,
);
jest.runOnlyPendingTimers();
expect(selectionCanvas.style.zIndex).toBe("");
act(() => {
fireEvent.dragStart(widgetEditor);
});
fireEvent.mouseEnter(selectionDiv);
fireEvent(
selectionDiv,
syntheticTestMouseEvent(
new MouseEvent("mousemove", {
bubbles: true,
cancelable: true,
}),
{
offsetX: dsl.rightColumn * 4,
offsetY: dsl.bottomRow * 4,
},
),
);
fireEvent(
selectionDiv,
syntheticTestMouseEvent(
new MouseEvent("mouseup", {
bubbles: true,
cancelable: true,
}),
{
offsetX: dsl.rightColumn * 4,
offsetY: dsl.bottomRow * 4,
},
),
);
expect(spyWidgetSelection).toHaveBeenLastCalledWith(
SelectionRequestType.Multiple,
["tabsWidgetId", "switchWidgetId"],
);
});
});
|
391 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/navigation/FocusEntity.test.ts | import { identifyEntityFromPath, FocusEntity } from "navigation/FocusEntity";
import { AppState } from "../entities/IDE/constants";
describe("identifyEntityFromPath", () => {
const oldUrlCases = [
{
path: "/applications/myAppId/pages/myPageId/edit",
expected: {
entity: FocusEntity.CANVAS,
id: "",
pageId: "myPageId",
appState: AppState.PAGES,
},
},
{
path: "/applications/myAppId/pages/myPageId/edit/widgets/ryvc8i7oja",
expected: {
entity: FocusEntity.PROPERTY_PANE,
id: "ryvc8i7oja",
pageId: "myPageId",
appState: AppState.PAGES,
},
},
{
path: "/applications/myAppId/pages/myPageId/edit/api/myApiId",
expected: {
entity: FocusEntity.API,
id: "myApiId",
pageId: "myPageId",
appState: AppState.PAGES,
},
},
{
path: "/applications/myAppId/pages/myPageId/edit/queries/myQueryId",
expected: {
entity: FocusEntity.QUERY,
id: "myQueryId",
pageId: "myPageId",
appState: AppState.PAGES,
},
},
];
const pageSlugCases = [
{
path: "/app/eval/page1-myPageId/edit",
expected: {
entity: FocusEntity.CANVAS,
id: "",
pageId: "myPageId",
appState: AppState.PAGES,
},
},
{
path: "/app/myAppId/page1-myPageId/edit/widgets/ryvc8i7oja",
expected: {
entity: FocusEntity.PROPERTY_PANE,
id: "ryvc8i7oja",
pageId: "myPageId",
appState: AppState.PAGES,
},
},
{
path: "/app/eval/page1-myPageId/edit/api/myApiId",
expected: {
entity: FocusEntity.API,
id: "myApiId",
pageId: "myPageId",
appState: AppState.PAGES,
},
},
{
path: "/app/eval/page1-myPageId/edit/queries/myQueryId",
expected: {
entity: FocusEntity.QUERY,
id: "myQueryId",
pageId: "myPageId",
appState: AppState.PAGES,
},
},
];
const customSlugCases = [
{
path: "/app/myCustomSlug-myPageId/edit",
expected: {
entity: FocusEntity.CANVAS,
id: "",
pageId: "myPageId",
appState: AppState.PAGES,
},
},
{
path: "/app/myCustomSlug-myPageId/edit/widgets/ryvc8i7oja",
expected: {
entity: FocusEntity.PROPERTY_PANE,
id: "ryvc8i7oja",
pageId: "myPageId",
appState: AppState.PAGES,
},
},
{
path: "/app/myCustomSlug-myPageId/edit/api/myApiId",
expected: {
entity: FocusEntity.API,
id: "myApiId",
pageId: "myPageId",
appState: AppState.PAGES,
},
},
{
path: "/app/myCustomSlug-myPageId/edit/queries/myQueryId",
expected: {
entity: FocusEntity.QUERY,
id: "myQueryId",
pageId: "myPageId",
appState: AppState.PAGES,
},
},
];
const cases = oldUrlCases.concat(pageSlugCases.concat(customSlugCases));
it("works", () => {
for (const testCase of cases) {
const actual = identifyEntityFromPath(testCase.path);
expect(actual).toStrictEqual(testCase.expected);
}
});
});
|
399 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings/DisconnectService.test.tsx | import { render, screen } from "test/testUtils";
import React from "react";
import { DisconnectService } from "./DisconnectService";
import {
createMessage,
DISCONNECT_AUTH_METHOD,
DISCONNECT_CONFIRMATION,
} from "@appsmith/constants/messages";
let container: any = null;
const buttonClickHandler = jest.fn();
const useSelector = jest.fn();
const values = {
subHeader: "some subheader value",
warning: "some warning",
};
useSelector.mockReturnValue(values);
function renderComponent() {
render(
<DisconnectService
disconnect={() => buttonClickHandler()}
subHeader={values.subHeader}
warning={values.warning}
/>,
);
}
describe("Disconnect Service", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
it("is rendered", () => {
renderComponent();
const disconnectBtn = screen.queryAllByTestId("disconnect-service-button");
expect(disconnectBtn).toHaveLength(1);
expect(disconnectBtn[0].textContent).toEqual(
createMessage(DISCONNECT_AUTH_METHOD),
);
disconnectBtn[0].click();
expect(disconnectBtn[0].textContent).toEqual(
createMessage(DISCONNECT_CONFIRMATION),
);
});
});
|
423 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings/FormGroup/Accordion.test.tsx | import { render, screen } from "test/testUtils";
import React from "react";
import type { Setting } from "@appsmith/pages/AdminSettings/config/types";
import {
SettingTypes,
SettingSubtype,
} from "@appsmith/pages/AdminSettings/config/types";
import Accordion from "./Accordion";
import { SETTINGS_FORM_NAME } from "@appsmith/constants/forms";
import { reduxForm } from "redux-form";
let container: any = null;
const setting: Setting = {
id: "SETTING_TOGGLE_ID",
name: "SETTING_TOGGLE_ID",
category: "test category",
subCategory: "test sub category",
controlType: SettingTypes.ACCORDION,
label: "test accordion label",
advanced: [
{
id: "SETTING_TEXT_INPUT_ID",
name: "SETTING_TEXT_INPUT_ID",
category: "test input category",
subCategory: "test input sub category",
controlType: SettingTypes.TEXTINPUT,
controlSubType: SettingSubtype.TEXT,
label: "test input label",
},
],
};
function renderComponent() {
function ToggleComponent() {
return (
<Accordion
category={setting.category}
label={setting.label}
settings={setting.advanced}
subCategory={setting.subCategory}
/>
);
}
const Parent = reduxForm<any, any>({
validate: () => {
return {};
},
form: SETTINGS_FORM_NAME,
touchOnBlur: true,
})(ToggleComponent);
render(<Parent />, {
initialState: {
form: {
[SETTINGS_FORM_NAME]: {
values: {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
[setting.advanced![0].id]: false,
},
},
},
},
});
}
describe("Accordion", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
it("is rendered", () => {
renderComponent();
expect(screen.getAllByText(/test accordion label/)).toBeDefined();
expect(document.querySelector("hr")).toBeDefined();
expect(document.querySelector("[name='expand-more']")).toBeDefined();
expect(screen.queryByTestId("admin-settings-group-wrapper")).toBeFalsy();
});
it("is open", () => {
renderComponent();
expect(document.querySelector("hr")).toBeDefined();
expect(document.querySelector("[name='expand-more']")).toBeDefined();
document.querySelector("hr")?.click();
expect(document.querySelector("[name='expand-less']")).toBeDefined();
expect(screen.queryByTestId("admin-settings-group-wrapper")).toBeDefined();
});
});
|
425 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings/FormGroup/Button.test.tsx | import { render, screen } from "test/testUtils";
import React from "react";
import type { Setting } from "@appsmith/pages/AdminSettings/config/types";
import { SettingTypes } from "@appsmith/pages/AdminSettings/config/types";
import ButtonComponent from "./Button";
let container: any = null;
const buttonClickHandler = jest.fn();
const buttonIsDisabled = jest.fn();
const setting: Setting = {
id: "SETTING_ID",
text: "download",
action: buttonClickHandler,
category: "test",
controlType: SettingTypes.BUTTON,
isDisabled: buttonIsDisabled,
};
const dispatch = jest.fn();
const settings = {};
jest.mock("react-redux", () => {
const originalModule = jest.requireActual("react-redux");
return {
...originalModule,
useDispatch: () => dispatch,
useSelector: () => settings,
};
});
function renderComponent() {
render(<ButtonComponent setting={setting} />);
}
describe("Button", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
it("is rendered", () => {
renderComponent();
const button = screen.queryAllByTestId("admin-settings-button");
expect(button).toHaveLength(1);
});
it("is rendered with proper text", () => {
renderComponent();
const button = screen.queryAllByTestId("admin-settings-button");
expect(button).toHaveLength(1);
expect(button[0].textContent).toBe(setting.text);
});
it("is disabled when isDisabled is returning true", () => {
buttonIsDisabled.mockReturnValue(true);
renderComponent();
const button = screen.queryAllByTestId("admin-settings-button");
expect(buttonIsDisabled).toHaveBeenCalledWith(settings);
expect((button[0] as any).disabled).toBeTruthy();
});
it("is not disabled when isDisabled is returning false", () => {
buttonIsDisabled.mockReturnValue(false);
renderComponent();
const button = screen.queryAllByTestId("admin-settings-button");
expect(buttonIsDisabled).toHaveBeenCalledWith(settings);
expect((button[0] as any).disabled).toBeFalsy();
});
it("is executing action of setting on click", () => {
renderComponent();
const button = screen.queryAllByTestId("admin-settings-button");
expect(buttonClickHandler).not.toHaveBeenCalled();
button[0].click();
expect(buttonClickHandler).toHaveBeenCalledWith(dispatch, settings);
});
});
|
430 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings/FormGroup/CopyUrlForm.test.tsx | import { render, screen } from "test/testUtils";
import React from "react";
import CopyUrlForm from "./CopyUrlForm";
import copy from "copy-to-clipboard";
let container: any = null;
jest.mock("copy-to-clipboard");
const values = {
helpText: "some helper text",
title: "Redirect URL",
value: "/link-to-be-copied",
fieldName: "redirectUrl",
};
function renderComponent() {
render(
<CopyUrlForm
fieldName={values.fieldName}
helpText={values.helpText}
title={values.title}
value={values.value}
/>,
);
}
describe("Redirect URL Form", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
it("is rendered", () => {
renderComponent();
window.prompt = jest.fn();
const fieldTitle = screen.getAllByText(/Redirect URL/);
expect(fieldTitle).toBeDefined();
const inputEl = screen.getByTestId(
`${values.fieldName}-input`,
) as HTMLInputElement;
const value = `${window.location.origin}/link-to-be-copied`;
expect(inputEl?.value).toBeDefined();
expect(inputEl?.value).toEqual(value);
expect(inputEl?.hasAttribute("disabled"));
const copyIcon = screen.getByTestId("redirectUrl-copy-icon");
expect(copyIcon).toBeDefined();
copyIcon?.click();
expect(copy).toHaveBeenCalledWith(value);
inputEl?.click();
expect(copy).toHaveBeenCalledWith(value);
});
});
|
433 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings/FormGroup/Group.test.tsx | import { render, screen } from "test/testUtils";
import React from "react";
import type { Setting } from "@appsmith/pages/AdminSettings/config/types";
import { SettingTypes } from "@appsmith/pages/AdminSettings/config/types";
import Group from "./group";
import { SETTINGS_FORM_NAME } from "@appsmith/constants/forms";
import { reduxForm } from "redux-form";
let container: any = null;
const settings: Setting[] = [
{
id: "test",
name: "test",
label: "formGroup",
helpText: "",
subText: "",
category: "test",
controlType: SettingTypes.BUTTON,
fieldName: "uneditable-field",
formName: "UneditableField",
value: "http://localhost",
},
];
function renderComponent() {
function GroupComponent() {
return <Group category="test" name="test" settings={settings} />;
}
const Parent = reduxForm<any, any>({
validate: () => {
return {};
},
form: SETTINGS_FORM_NAME,
touchOnBlur: true,
})(GroupComponent);
render(<Parent />);
}
function getElements() {
const textInput = screen.queryAllByTestId("admin-settings-group-text-input");
const toggle = screen.queryAllByTestId("admin-settings-group-toggle");
const link = screen.queryAllByTestId("admin-settings-group-link");
const text = screen.queryAllByTestId("admin-settings-group-text");
const button = screen.queryAllByTestId("admin-settings-group-button");
const group = screen.queryAllByTestId("admin-settings-group");
const tagInput = screen.queryAllByTestId("admin-settings-tag-input");
const accordion = screen.queryAllByTestId("admin-settings-accordion");
const uneditableField = screen.queryAllByTestId(
"admin-settings-uneditable-field",
);
return {
textInput,
toggle,
link,
text,
button,
group,
tagInput,
accordion,
uneditableField,
};
}
describe("Group", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
it("is rendered", () => {
renderComponent();
const group = screen.queryAllByTestId("admin-settings-group-wrapper");
expect(group).toHaveLength(1);
});
it("is rendered for text input", () => {
settings[0].controlType = SettingTypes.TEXTINPUT;
renderComponent();
const {
accordion,
button,
group,
link,
tagInput,
text,
textInput,
toggle,
uneditableField,
} = getElements();
expect(textInput).toHaveLength(1);
expect(toggle).toHaveLength(0);
expect(link).toHaveLength(0);
expect(text).toHaveLength(0);
expect(button).toHaveLength(0);
expect(group).toHaveLength(0);
expect(uneditableField).toHaveLength(0);
expect(tagInput).toHaveLength(0);
expect(accordion).toHaveLength(0);
});
it("is rendered for toggle", () => {
settings[0].controlType = SettingTypes.TOGGLE;
renderComponent();
const {
accordion,
button,
group,
link,
tagInput,
text,
textInput,
toggle,
uneditableField,
} = getElements();
expect(textInput).toHaveLength(0);
expect(toggle).toHaveLength(1);
expect(link).toHaveLength(0);
expect(text).toHaveLength(0);
expect(button).toHaveLength(0);
expect(group).toHaveLength(0);
expect(uneditableField).toHaveLength(0);
expect(tagInput).toHaveLength(0);
expect(accordion).toHaveLength(0);
});
it("is rendered for link", () => {
settings[0].controlType = SettingTypes.CALLOUT;
renderComponent();
const {
accordion,
button,
group,
link,
tagInput,
text,
textInput,
toggle,
uneditableField,
} = getElements();
expect(textInput).toHaveLength(0);
expect(toggle).toHaveLength(0);
expect(link).toHaveLength(1);
expect(text).toHaveLength(0);
expect(button).toHaveLength(0);
expect(group).toHaveLength(0);
expect(uneditableField).toHaveLength(0);
expect(tagInput).toHaveLength(0);
expect(accordion).toHaveLength(0);
});
it("is rendered for text", () => {
settings[0].controlType = SettingTypes.TEXT;
renderComponent();
const {
accordion,
button,
group,
link,
tagInput,
text,
textInput,
toggle,
uneditableField,
} = getElements();
expect(textInput).toHaveLength(0);
expect(toggle).toHaveLength(0);
expect(link).toHaveLength(0);
expect(text).toHaveLength(1);
expect(button).toHaveLength(0);
expect(group).toHaveLength(0);
expect(uneditableField).toHaveLength(0);
expect(tagInput).toHaveLength(0);
expect(accordion).toHaveLength(0);
});
it("is rendered for button", () => {
settings[0].controlType = SettingTypes.BUTTON;
renderComponent();
const {
accordion,
button,
group,
link,
tagInput,
text,
textInput,
toggle,
uneditableField,
} = getElements();
expect(textInput).toHaveLength(0);
expect(toggle).toHaveLength(0);
expect(link).toHaveLength(0);
expect(text).toHaveLength(0);
expect(button).toHaveLength(1);
expect(group).toHaveLength(0);
expect(uneditableField).toHaveLength(0);
expect(tagInput).toHaveLength(0);
expect(accordion).toHaveLength(0);
});
it("is rendered for group", () => {
settings[0].controlType = SettingTypes.GROUP;
renderComponent();
const {
accordion,
button,
group,
link,
tagInput,
text,
textInput,
toggle,
uneditableField,
} = getElements();
expect(textInput).toHaveLength(0);
expect(toggle).toHaveLength(0);
expect(link).toHaveLength(0);
expect(text).toHaveLength(0);
expect(button).toHaveLength(0);
expect(group).toHaveLength(1);
expect(uneditableField).toHaveLength(0);
expect(tagInput).toHaveLength(0);
expect(accordion).toHaveLength(0);
});
it("is rendered for uneditable field", () => {
settings[0].controlType = SettingTypes.UNEDITABLEFIELD;
renderComponent();
const {
accordion,
button,
group,
link,
tagInput,
text,
textInput,
toggle,
uneditableField,
} = getElements();
expect(textInput).toHaveLength(0);
expect(toggle).toHaveLength(0);
expect(link).toHaveLength(0);
expect(text).toHaveLength(0);
expect(button).toHaveLength(0);
expect(group).toHaveLength(0);
expect(uneditableField).toHaveLength(1);
expect(tagInput).toHaveLength(0);
expect(accordion).toHaveLength(0);
});
it("is rendered for tag input", () => {
settings[0].controlType = SettingTypes.TAGINPUT;
renderComponent();
const {
accordion,
button,
group,
link,
tagInput,
text,
textInput,
toggle,
uneditableField,
} = getElements();
expect(textInput).toHaveLength(0);
expect(toggle).toHaveLength(0);
expect(link).toHaveLength(0);
expect(text).toHaveLength(0);
expect(button).toHaveLength(0);
expect(group).toHaveLength(0);
expect(uneditableField).toHaveLength(0);
expect(tagInput).toHaveLength(1);
expect(accordion).toHaveLength(0);
});
it("is rendered for accordion", () => {
settings[0].controlType = SettingTypes.ACCORDION;
renderComponent();
const {
accordion,
button,
group,
link,
tagInput,
text,
textInput,
toggle,
uneditableField,
} = getElements();
expect(textInput).toHaveLength(0);
expect(toggle).toHaveLength(0);
expect(link).toHaveLength(0);
expect(text).toHaveLength(0);
expect(button).toHaveLength(0);
expect(group).toHaveLength(0);
expect(uneditableField).toHaveLength(0);
expect(tagInput).toHaveLength(0);
expect(accordion).toHaveLength(1);
});
});
|
435 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings/FormGroup/Link.test.tsx | import { render, screen } from "test/testUtils";
import React from "react";
import type { Setting } from "@appsmith/pages/AdminSettings/config/types";
import { SettingTypes } from "@appsmith/pages/AdminSettings/config/types";
import Link from "./Link";
let container: any = null;
const linkClickHandler = jest.fn();
const setting: Setting = {
id: "SETTING_ID",
isHidden: false,
label: "setting label",
action: linkClickHandler,
category: "test",
controlType: SettingTypes.LINK,
url: "",
};
const dispatch = jest.fn();
jest.mock("react-redux", () => {
const originalModule = jest.requireActual("react-redux");
return {
...originalModule,
useDispatch: () => dispatch,
};
});
function renderComponent() {
render(<Link setting={setting} />);
}
describe("Link", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
it("is rendered", () => {
renderComponent();
const link = screen.queryAllByTestId("admin-settings-link");
expect(link).toHaveLength(1);
});
it("is rendered with label", () => {
renderComponent();
const linkLabel = screen.queryAllByTestId("admin-settings-link-label");
expect(linkLabel).toHaveLength(1);
expect(linkLabel[0].textContent).toBe(setting.label);
});
it("is rendered with click handler", () => {
renderComponent();
const linkAnchor = screen.queryAllByTestId("admin-settings-link-anchor");
expect(linkAnchor).toHaveLength(1);
expect(linkClickHandler).not.toHaveBeenCalled();
linkAnchor[0].click();
expect(linkClickHandler).toHaveBeenCalledWith(dispatch);
});
it("is rendered with href", () => {
const url = "http://test.appsmith.com";
setting.url = url;
renderComponent();
const linkAnchor = screen.queryAllByTestId("admin-settings-link-anchor");
expect(linkAnchor).toHaveLength(1);
expect(linkAnchor[0].getAttribute("href")).toBe(url);
expect(linkAnchor[0].getAttribute("target")).toBe("_blank");
});
});
|
437 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings/FormGroup/Radio.test.tsx | import { render } from "test/testUtils";
import React from "react";
import type { Setting } from "@appsmith/pages/AdminSettings/config/types";
import { SettingTypes } from "@appsmith/pages/AdminSettings/config/types";
import Radio from "./Radio";
import { SETTINGS_FORM_NAME } from "@appsmith/constants/forms";
import { reduxForm } from "redux-form";
let container: any = null;
const setting: Setting = {
id: "SETTING_RADIO",
name: "SETTING_RADIO",
category: "test category",
controlType: SettingTypes.RADIO,
label: "test label",
controlTypeProps: {
options: [
{
label: "Label one",
value: "ONE",
},
{
label: "Label two",
value: "TWO",
},
],
},
format: (value) => {
return { value };
},
parse: (value) => {
return value.value;
},
};
function renderComponent() {
function RadioFieldComponent() {
return <Radio data-testid="t--radio" setting={setting} />;
}
const Parent = reduxForm<any, any>({
validate: () => {
return {};
},
form: SETTINGS_FORM_NAME,
touchOnBlur: true,
})(RadioFieldComponent);
render(<Parent />, {
initialState: {
form: {
[SETTINGS_FORM_NAME]: {
values: {
[setting.id]: "TWO",
},
},
},
},
});
}
describe("Radio", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
it("is rendered", () => {
renderComponent();
const radioOptions: NodeListOf<HTMLInputElement> =
document.querySelectorAll("input[type=radio]");
const numberOfCheckboxes = radioOptions.length;
expect(numberOfCheckboxes).toEqual(
setting.controlTypeProps?.options.length,
);
expect(radioOptions[1].checked).toBeTruthy();
});
});
|
439 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings/FormGroup/TagInputField.test.tsx | import { render, screen } from "test/testUtils";
import React from "react";
import type { Setting } from "@appsmith/pages/AdminSettings/config/types";
import { SettingTypes } from "@appsmith/pages/AdminSettings/config/types";
import TagInputField from "./TagInputField";
import { SETTINGS_FORM_NAME } from "@appsmith/constants/forms";
import { reduxForm } from "redux-form";
let container: any = null;
const setting: Setting = {
id: "SETTING_TAG_INPUT_ID",
name: "SETTING_TAG_INPUT_ID",
category: "test category",
controlType: SettingTypes.TAGINPUT,
label: "test label",
};
function renderComponent() {
function TagInputFieldComponent() {
return (
<TagInputField
data-testid="t--tag-input"
intent="success"
label={setting.label}
name={setting.name || setting.id}
placeholder=""
setting={setting}
type="text"
/>
);
}
const Parent = reduxForm<any, any>({
validate: () => {
return {};
},
form: SETTINGS_FORM_NAME,
touchOnBlur: true,
})(TagInputFieldComponent);
render(<Parent />, {
initialState: {
form: {
[SETTINGS_FORM_NAME]: {
values: {
[setting.id]: "comma,separated,values",
},
},
},
},
});
}
describe("Tag Input", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
it("is rendered", () => {
renderComponent();
const allTags = document.getElementsByClassName(
"bp3-text-overflow-ellipsis",
);
const allCrossBtns = document.getElementsByClassName("bp3-tag-remove");
const numberOfTags = allTags.length;
const numberOfCrossBtns = allCrossBtns.length;
expect(numberOfTags).toEqual(numberOfCrossBtns);
expect(screen.getByText(/comma/)).toBeDefined();
expect(screen.getByText(/separated/)).toBeDefined();
expect(screen.getByText(/values/)).toBeDefined();
});
});
|
441 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings/FormGroup/Text.test.tsx | import { render, screen } from "test/testUtils";
import React from "react";
import type { Setting } from "@appsmith/pages/AdminSettings/config/types";
import { SettingTypes } from "@appsmith/pages/AdminSettings/config/types";
import TextComponent from "./Text";
let container: any = null;
const buttonClickHandler = jest.fn();
const setting: Setting = {
id: "SETTING_ID",
name: "textType",
text: "download",
action: buttonClickHandler,
category: "test",
controlType: SettingTypes.TEXT,
};
const useSelector = jest.fn();
const settingsConfig = {
textType: "some text value",
};
useSelector.mockReturnValue(settingsConfig);
function renderComponent() {
render(<TextComponent setting={setting} />, {
initialState: {
settings: {
isLoading: false,
isSaving: false,
isRestarting: false,
showReleaseNotes: false,
isRestartFailed: false,
config: settingsConfig,
},
},
});
}
describe("Text", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
it("is rendered", () => {
renderComponent();
const text = screen.queryAllByTestId("admin-settings-text");
expect(text).toHaveLength(1);
expect(text[0].textContent).toBe(settingsConfig.textType);
});
});
|
444 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings/FormGroup/TextInput.test.tsx | import { render } from "test/testUtils";
import React from "react";
import type { Setting } from "@appsmith/pages/AdminSettings/config/types";
import {
SettingTypes,
SettingSubtype,
} from "@appsmith/pages/AdminSettings/config/types";
import TextInput from "./TextInput";
import { SETTINGS_FORM_NAME } from "@appsmith/constants/forms";
import { reduxForm } from "redux-form";
let container: any = null;
const setting: Setting = {
id: "SETTING_TEXT_INPUT_ID",
name: "SETTING_TEXT_INPUT_ID",
category: "test category",
controlType: SettingTypes.TEXTINPUT,
controlSubType: SettingSubtype.TEXT,
label: "test label",
};
function renderComponent() {
function TextInputFieldComponent() {
return <TextInput setting={setting} />;
}
const Parent = reduxForm<any, any>({
validate: () => {
return {};
},
form: SETTINGS_FORM_NAME,
touchOnBlur: true,
})(TextInputFieldComponent);
render(<Parent />, {
initialState: {
form: {
[SETTINGS_FORM_NAME]: {
values: {
[setting.id]: "test value",
},
},
},
},
});
}
describe("Text Input", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
it("is rendered", () => {
renderComponent();
const inputEl = document.querySelector("input");
expect(inputEl?.value).toBeDefined();
expect(inputEl?.value).toEqual("test value");
});
});
|
446 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings/FormGroup/Toggle.test.tsx | import { render } from "test/testUtils";
import React from "react";
import type { Setting } from "@appsmith/pages/AdminSettings/config/types";
import { SettingTypes } from "@appsmith/pages/AdminSettings/config/types";
import Toggle from "./Toggle";
import { SETTINGS_FORM_NAME } from "@appsmith/constants/forms";
import { reduxForm } from "redux-form";
let container: any = null;
const setting: Setting = {
id: "SETTING_TOGGLE_ID",
name: "SETTING_TOGGLE_ID",
category: "test category",
controlType: SettingTypes.TOGGLE,
label: "test label",
};
function renderComponent() {
function ToggleComponent() {
return <Toggle setting={setting} />;
}
const Parent = reduxForm<any, any>({
validate: () => {
return {};
},
form: SETTINGS_FORM_NAME,
touchOnBlur: true,
})(ToggleComponent);
render(<Parent />, {
initialState: {
form: {
[SETTINGS_FORM_NAME]: {
values: {
[setting.id]: false,
},
},
},
},
});
}
describe("Toggle", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
it("is rendered", () => {
renderComponent();
const inputEl = document.querySelector("input");
expect(inputEl?.checked).toBeDefined();
expect(inputEl?.checked).toEqual(true); // value = ![setting.id]
expect(inputEl?.hasAttribute("checked"));
});
it("when clicked flips the flag", () => {
renderComponent();
const inputEl = document.querySelector("input");
inputEl?.click();
expect(inputEl?.checked).toEqual(false);
});
});
|
448 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AdminSettings/FormGroup/common.test.tsx | import { render, screen } from "test/testUtils";
import React from "react";
import type { Setting } from "@appsmith/pages/AdminSettings/config/types";
import { SettingTypes } from "@appsmith/pages/AdminSettings/config/types";
import { FormGroup } from "./Common";
let container: any = null;
const setting: Setting = {
id: "SETTING_ID",
label: "formGroup",
helpText: "",
subText: "",
category: "test",
controlType: SettingTypes.BUTTON,
};
const CLASSNAME = "form-group";
function renderComponent() {
render(
<FormGroup className={CLASSNAME} setting={setting}>
<div data-testid="admin-settings-form-group-child" />
</FormGroup>,
container,
);
}
describe("FormGroup", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
it("is rendered", () => {
renderComponent();
const formGroup = screen.queryAllByTestId("admin-settings-form-group");
expect(formGroup).toHaveLength(1);
expect(formGroup[0].className).toContain(CLASSNAME);
const formGroupLabel = screen.queryAllByTestId(
"admin-settings-form-group-label",
);
expect(formGroupLabel).toHaveLength(1);
expect(formGroupLabel[0].textContent).toBe(setting.label);
const formGroupHelpText = screen.queryAllByTestId(
"admin-settings-form-group-helptext",
);
expect(formGroupHelpText).toHaveLength(0);
const formGroupSubtext = screen.queryAllByTestId(
"admin-settings-form-group-subtext",
);
expect(formGroupSubtext).toHaveLength(0);
});
it("is rendered with helpText", () => {
setting.helpText = "some help text";
renderComponent();
const formGroupHelpText = screen.queryAllByTestId(
"admin-settings-form-group-helptext",
);
expect(formGroupHelpText).toHaveLength(1);
});
it("is rendered with subText", () => {
setting.subText = "some sub text";
renderComponent();
const formGroupSubtext = screen.queryAllByTestId(
"admin-settings-form-group-subtext",
);
expect(formGroupSubtext).toHaveLength(1);
expect(formGroupSubtext[0].textContent).toBe(`${setting.subText}`);
});
it("is rendered with children", () => {
renderComponent();
const formGroupChild = screen.queryAllByTestId(
"admin-settings-form-group-child",
);
expect(formGroupChild).toHaveLength(1);
});
});
|
465 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages | petrpan-code/appsmithorg/appsmith/app/client/src/pages/AppViewer/PrimaryCTA.test.tsx | import React from "react";
import { render, screen, cleanup } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import { Provider } from "react-redux";
import { ThemeProvider } from "styled-components";
import { lightTheme } from "selectors/themeSelectors";
import PrimaryCTA from "./PrimaryCTA";
import configureStore from "redux-mock-store";
jest.mock("react-router", () => ({
...jest.requireActual("react-router"),
useHistory: () => ({ push: jest.fn() }),
useLocation: () => ({
pathname: "/app/test-3/page1-63cccd44463c535b9fbc297c",
search: "?fork=true",
}),
}));
const mockDispatch = jest.fn();
jest.mock("react-redux", () => ({
...jest.requireActual("react-redux"),
useDispatch: () => mockDispatch,
}));
export const initialState: any = {
entities: {
pageList: {
applicationId: 1,
currentPageId: 1,
pages: [
{
pageId: 1,
slug: "pageSlug",
},
],
},
datasources: {
list: [],
},
actions: [],
canvasWidgets: {
main_component: {},
},
},
ui: {
gitSync: {
protectedBranches: [],
},
editor: {
isPreviewMode: false,
},
appSettingsPane: {
isOpen: false,
},
appTheming: {
selectedTheme: {
properties: {
colors: {
primaryColor: "",
},
borderRadius: {
appBorderRadius: "",
},
},
},
},
applications: {
currentApplication: {
id: "605c435a91dea93f0eaf91b8",
name: "My Application",
slug: "my-application",
workspaceId: "",
evaluationVersion: 1,
appIsExample: false,
gitApplicationMetadata: undefined,
applicationVersion: 2,
forkingEnabled: true,
isPublic: true,
},
userWorkspaces: [],
},
theme: {
theme: {
colors: {
applications: {
iconColor: "#f2f2f2",
},
success: {
main: "#e2e2e2",
},
},
},
},
users: {
currentUser: undefined,
},
},
};
const state = JSON.parse(JSON.stringify(initialState));
const mockStore = configureStore();
export function getStore(action?: string) {
switch (action) {
case "SET_CURRENT_USER_DETAILS":
state.ui.users.currentUser = {
username: "test",
};
break;
}
return mockStore(state);
}
export const fetchApplicationMockResponse = {
responseMeta: {
status: 200,
success: true,
},
data: {
application: {
id: "605c435a91dea93f0eaf91b8",
name: "My Application",
slug: "my-application",
workspaceId: "",
evaluationVersion: 1,
appIsExample: false,
gitApplicationMetadata: undefined,
applicationVersion: 2,
forkingEnabled: true,
isPublic: true,
},
pages: [
{
id: "605c435a91dea93f0eaf91ba",
name: "Page1",
isDefault: true,
slug: "page-1",
},
{
id: "605c435a91dea93f0eaf91bc",
name: "Page2",
isDefault: false,
slug: "page-2",
},
],
workspaceId: "",
},
};
describe("App viewer fork button", () => {
afterEach(cleanup);
it("Fork modal trigger should not be displayed until user details are fetched", () => {
render(
<Provider store={getStore()}>
<ThemeProvider theme={lightTheme}>
<PrimaryCTA
navColorStyle="solid"
primaryColor="red"
url={"/app/test-3/page1-63cccd44463c535b9fbc297c/edit"}
/>
</ThemeProvider>
</Provider>,
);
expect(screen.queryAllByTestId("fork-modal-trigger").length).toEqual(0);
expect(mockDispatch).toHaveBeenCalledTimes(0);
mockDispatch.mockClear();
});
it("Fork modal trigger should be displayed when user details are defined and user is not anonymous", () => {
render(
<Provider store={getStore("SET_CURRENT_USER_DETAILS")}>
<ThemeProvider theme={lightTheme}>
<PrimaryCTA
navColorStyle="solid"
primaryColor="red"
url={"/app/test-3/page1-63cccd44463c535b9fbc297c/edit"}
/>
</ThemeProvider>
</Provider>,
);
expect(screen.queryAllByTestId("fork-modal-trigger").length).toEqual(1);
expect(mockDispatch).toHaveBeenCalledTimes(1);
mockDispatch.mockClear();
});
});
|
530 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/MainContainerWidthToggles.test.tsx | import React from "react";
import "@testing-library/jest-dom";
import { ThemeProvider } from "styled-components";
import { render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Provider } from "react-redux";
import { lightTheme } from "selectors/themeSelectors";
import store from "store";
import { MainContainerWidthToggles } from "./MainContainerWidthToggles";
function navigateWithArrowKeys(key: string, noOfPresses: number) {
for (let i = 0; i < noOfPresses; i++) {
userEvent.keyboard(key);
}
}
describe("<MainContainerWidthToggles />", () => {
const getTestComponent = () => (
<ThemeProvider theme={lightTheme}>
<Provider store={store}>
<MainContainerWidthToggles />
</Provider>
</ThemeProvider>
);
it("Pressing tab should focus on the first component", () => {
const { container } = render(getTestComponent());
userEvent.tab();
// Should focus on the first component
const tab = container.getElementsByClassName(
"ads-v2-segmented-control__segments-container",
)[0];
expect(tab).toHaveFocus();
});
it("{ArrowRight} should focus the next item", () => {
const { container } = render(getTestComponent());
const tabs = container.getElementsByClassName(
"ads-v2-segmented-control__segments-container",
);
userEvent.tab();
navigateWithArrowKeys("{ArrowRight}", 1);
expect(tabs[1]).toHaveFocus();
// Focus back on the first element
userEvent.keyboard("{ArrowLeft}");
// Arrow Right after the last item should focus the first item again
navigateWithArrowKeys("{ArrowRight}", tabs.length);
expect(tabs[0]).toHaveFocus();
});
it("{ArrowLeft} should focus the next item", async () => {
const { container } = render(getTestComponent());
const tabs = container.getElementsByClassName(
"ads-v2-segmented-control__segments-container",
);
userEvent.tab();
// Arrow Left on the First item should focus on the last item
navigateWithArrowKeys("{ArrowLeft}", 1);
expect(tabs[tabs.length - 1]).toHaveFocus();
navigateWithArrowKeys("{ArrowLeft}", tabs.length - 1);
expect(tabs[0]).toHaveFocus();
});
});
|
656 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/Explorer/EntityExplorer.test.tsx | import { act, fireEvent, render } from "test/testUtils";
import {
buildChildren,
widgetCanvasFactory,
} from "test/factories/WidgetFactoryUtils";
import React from "react";
import { MockPageDSL } from "test/testCommon";
import { DEFAULT_ENTITY_EXPLORER_WIDTH } from "constants/AppConstants";
import store, { runSagaMiddleware } from "store";
import Datasources from "./Datasources";
import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
import { mockDatasources } from "./mockTestData";
import { updateCurrentPage } from "actions/pageActions";
import urlBuilder from "@appsmith/entities/URLRedirect/URLAssembly";
import * as helpers from "@appsmith/pages/Editor/Explorer/helpers";
import * as explorerSelector from "selectors/explorerSelector";
import * as permissionPageHelpers from "@appsmith/utils/BusinessFeatures/permissionPageHelpers";
import userEvent from "@testing-library/user-event";
import { MAIN_CONTAINER_WIDGET_ID } from "constants/WidgetConstants";
import * as widgetSelectionsActions from "actions/widgetSelectionActions";
import { SelectionRequestType } from "sagas/WidgetSelectUtils";
import { NavigationMethod } from "utils/history";
import WidgetsEditorEntityExplorer from "../WidgetsEditorEntityExplorer";
jest.useFakeTimers();
const pushState = jest.spyOn(window.history, "pushState");
pushState.mockImplementation((state: any, title: any, url: any) => {
window.document.title = title;
window.location.pathname = url;
});
jest.mock("@appsmith/utils/permissionHelpers", () => {
return {
__esModule: true,
...jest.requireActual("@appsmith/utils/permissionHelpers"),
};
});
jest.mock("@appsmith/pages/Editor/Explorer/helpers", () => ({
__esModule: true,
...jest.requireActual("@appsmith/pages/Editor/Explorer/helpers"),
}));
jest.mock("@appsmith/utils/BusinessFeatures/permissionPageHelpers", () => ({
__esModule: true,
...jest.requireActual(
"@appsmith/utils/BusinessFeatures/permissionPageHelpers",
),
}));
jest.mock("selectors/explorerSelector", () => ({
__esModule: true,
...jest.requireActual("selectors/explorerSelector"),
}));
jest
.spyOn(explorerSelector, "getExplorerWidth")
.mockImplementation(() => DEFAULT_ENTITY_EXPLORER_WIDTH);
const addDatasource = jest.fn();
const listDatasource = jest.fn();
const onDatasourcesToggle = jest.fn();
const isDatasourcesOpen = true;
const entityId = "pageId";
describe("Entity Explorer tests", () => {
beforeAll(() => {
runSagaMiddleware();
});
beforeEach(() => {
urlBuilder.updateURLParams(
{
applicationId: "appId",
applicationSlug: "appSlug",
applicationVersion: 2,
},
[
{
pageId: "pageId",
pageSlug: "pageSlug",
},
],
);
});
it("checks datasources section in explorer", () => {
const mockExplorerState = jest.spyOn(helpers, "getExplorerStatus");
mockExplorerState.mockImplementationOnce(() => true);
store.dispatch({
type: ReduxActionTypes.FETCH_DATASOURCES_SUCCESS,
payload: mockDatasources,
});
jest
.spyOn(permissionPageHelpers, "getHasCreateDatasourcePermission")
.mockReturnValue(true);
store.dispatch(updateCurrentPage("pageId"));
const component = render(
<Datasources
addDatasource={addDatasource}
entityId={entityId}
isDatasourcesOpen={isDatasourcesOpen}
listDatasource={listDatasource}
onDatasourcesToggle={onDatasourcesToggle}
/>,
);
expect(component.container.getElementsByClassName("t--entity").length).toBe(
5,
);
});
it("should hide create datasources section in explorer if the user don't have valid permissions", () => {
store.dispatch({
type: ReduxActionTypes.FETCH_DATASOURCES_SUCCESS,
payload: mockDatasources,
});
jest
.spyOn(permissionPageHelpers, "getHasCreateDatasourcePermission")
.mockReturnValue(false);
const mockExplorerState = jest.spyOn(helpers, "getExplorerStatus");
mockExplorerState.mockImplementationOnce(() => true);
store.dispatch(updateCurrentPage("pageId"));
const component = render(
<Datasources
addDatasource={addDatasource}
entityId={entityId}
isDatasourcesOpen={isDatasourcesOpen}
listDatasource={listDatasource}
onDatasourcesToggle={onDatasourcesToggle}
/>,
);
expect(component.container.getElementsByClassName("t--entity").length).toBe(
4,
);
const addDatasourceEntity = document.getElementById(
"entity-add_new_datasource",
);
expect(addDatasourceEntity).toBeNull();
});
it("Should render Widgets tree in entity explorer", () => {
const children: any = buildChildren([{ type: "TABS_WIDGET" }]);
const dsl: any = widgetCanvasFactory.build({
children,
});
const component = render(
<MockPageDSL dsl={dsl}>
<WidgetsEditorEntityExplorer />
</MockPageDSL>,
);
const widgetsTree: any = component.queryByText("Widgets", {
selector: "div.t--entity-name",
});
act(() => {
fireEvent.click(widgetsTree);
jest.runAllTimers();
});
const tabsWidget = component.queryByText(children[0].widgetName);
expect(tabsWidget).toBeTruthy();
});
describe("Widget Selection in entity explorer", () => {
const spyWidgetSelection = jest.spyOn(
widgetSelectionsActions,
"selectWidgetInitAction",
);
beforeEach(() => {
spyWidgetSelection.mockClear();
});
it("Select widget on entity explorer", () => {
const children: any = buildChildren([
{ type: "TABS_WIDGET", widgetId: "tabsWidgetId" },
]);
const dsl: any = widgetCanvasFactory.build({
children,
});
const component = render(
<MockPageDSL dsl={dsl}>
<WidgetsEditorEntityExplorer />
</MockPageDSL>,
);
const tabsWidget: any = component.queryByText(children[0].widgetName);
act(() => {
fireEvent.click(tabsWidget);
jest.runAllTimers();
});
expect(spyWidgetSelection).toHaveBeenCalledWith(
SelectionRequestType.One,
["tabsWidgetId"],
NavigationMethod.EntityExplorer,
undefined,
);
});
it("CMD + click Multi Select widget on entity explorer", () => {
const children: any = buildChildren([
{
type: "CHECKBOX_WIDGET",
parentId: "0",
widgetId: "checkboxWidgetId",
},
{ type: "SWITCH_WIDGET", parentId: "0", widgetId: "switchWidgetId" },
]);
const dsl: any = widgetCanvasFactory.build({
children,
});
const component = render(
<MockPageDSL dsl={dsl}>
<WidgetsEditorEntityExplorer />
</MockPageDSL>,
);
const checkBox: any = component.queryByText(children[0].widgetName);
act(() => {
fireEvent.click(checkBox);
jest.runAllTimers();
});
const switchWidget: any = component.queryByText(children[1].widgetName);
expect(spyWidgetSelection).toHaveBeenCalledWith(
SelectionRequestType.One,
["checkboxWidgetId"],
NavigationMethod.EntityExplorer,
undefined,
);
act(() => {
fireEvent.click(switchWidget, {
ctrlKey: true,
});
jest.runAllTimers();
});
expect(spyWidgetSelection).toHaveBeenCalledWith(
SelectionRequestType.PushPop,
["switchWidgetId"],
undefined,
undefined,
);
});
it("Shift + Click Multi Select widget on entity explorer", () => {
const children: any = buildChildren([
{
type: "CHECKBOX_WIDGET",
parentId: "0",
widgetId: "checkboxWidgetId",
},
{ type: "SWITCH_WIDGET", parentId: "0", widgetId: "switchWidgetId" },
{ type: "BUTTON_WIDGET", parentId: "0", widgetId: "buttonWidgetId" },
]);
const dsl: any = widgetCanvasFactory.build({
children,
});
const component = render(
<MockPageDSL dsl={dsl}>
<WidgetsEditorEntityExplorer />
</MockPageDSL>,
);
const checkboxWidget: any = component.queryByText(children[0].widgetName);
const buttonWidget: any = component.queryByText(children[2].widgetName);
act(() => {
fireEvent.click(checkboxWidget);
jest.runAllTimers();
});
expect(spyWidgetSelection).toHaveBeenCalledWith(
SelectionRequestType.One,
["checkboxWidgetId"],
NavigationMethod.EntityExplorer,
undefined,
);
act(() => {
fireEvent.click(buttonWidget, {
shiftKey: true,
});
jest.runAllTimers();
});
expect(spyWidgetSelection).toHaveBeenCalledWith(
SelectionRequestType.ShiftSelect,
["buttonWidgetId"],
undefined,
undefined,
);
});
it("Shift + Click Deselect Non Siblings", () => {
const containerId = "containerWidgetId";
const canvasId = "canvasWidgetId";
const children: any = buildChildren([
{
type: "CHECKBOX_WIDGET",
parentId: canvasId,
widgetId: "checkboxWidgetId",
},
{
type: "SWITCH_WIDGET",
parentId: canvasId,
widgetId: "switchWidgetId",
},
{
type: "BUTTON_WIDGET",
parentId: canvasId,
widgetId: "buttonWidgetId",
},
]);
const canvasWidget = buildChildren([
{
type: "CANVAS_WIDGET",
parentId: containerId,
children,
widgetId: canvasId,
},
]);
const containerChildren: any = buildChildren([
{
type: "CONTAINER_WIDGET",
children: canvasWidget,
widgetId: containerId,
parentId: MAIN_CONTAINER_WIDGET_ID,
},
{
type: "CHART_WIDGET",
parentId: MAIN_CONTAINER_WIDGET_ID,
widgetId: "chartWidgetId",
},
]);
const dsl: any = widgetCanvasFactory.build({
children: containerChildren,
});
const component = render(
<MockPageDSL dsl={dsl}>
<WidgetsEditorEntityExplorer />
</MockPageDSL>,
);
const containerWidget: any = component.queryByText(
containerChildren[0].widgetName,
);
act(() => {
fireEvent.click(containerWidget);
jest.runAllTimers();
});
expect(spyWidgetSelection).toHaveBeenCalledWith(
SelectionRequestType.One,
[containerId],
NavigationMethod.EntityExplorer,
undefined,
);
const collapsible: any = component.container.querySelector(
`.t--entity-collapse-toggle[id="arrow-right-s-line"]`,
);
fireEvent.click(collapsible);
const buttonWidget: any = component.queryByText(children[2].widgetName);
act(() => {
fireEvent.click(buttonWidget, {
shiftKey: true,
});
jest.runAllTimers();
});
expect(spyWidgetSelection).toHaveBeenCalledWith(
SelectionRequestType.ShiftSelect,
["buttonWidgetId"],
undefined,
undefined,
);
const checkBoxWidget: any = component.queryByText(children[0].widgetName);
act(() => {
fireEvent.click(checkBoxWidget, {
shiftKey: true,
});
jest.runAllTimers();
});
expect(spyWidgetSelection).toHaveBeenCalledWith(
SelectionRequestType.ShiftSelect,
["checkboxWidgetId"],
undefined,
undefined,
);
const chartWidget: any = component.queryByText(
containerChildren[1].widgetName,
);
act(() => {
fireEvent.click(chartWidget, {
shiftKey: true,
});
jest.runAllTimers();
});
expect(spyWidgetSelection).toHaveBeenCalledWith(
SelectionRequestType.ShiftSelect,
["chartWidgetId"],
undefined,
undefined,
);
});
});
it("should hide delete & edit of datasource if the user don't have valid permissions", async () => {
store.dispatch({
type: ReduxActionTypes.FETCH_DATASOURCES_SUCCESS,
payload: mockDatasources,
});
jest
.spyOn(permissionPageHelpers, "getHasCreateDatasourcePermission")
.mockReturnValue(true);
jest
.spyOn(permissionPageHelpers, "getHasManageDatasourcePermission")
.mockReturnValue(false);
jest
.spyOn(permissionPageHelpers, "getHasDeleteDatasourcePermission")
.mockReturnValue(false);
const mockExplorerState = jest.spyOn(helpers, "getExplorerStatus");
mockExplorerState.mockImplementationOnce(() => true);
store.dispatch(updateCurrentPage("pageId"));
const { container } = render(
<Datasources
addDatasource={addDatasource}
entityId={entityId}
isDatasourcesOpen={isDatasourcesOpen}
listDatasource={listDatasource}
onDatasourcesToggle={onDatasourcesToggle}
/>,
);
const target = container.getElementsByClassName("t--context-menu");
await userEvent.click(target[2]);
const deleteOption = document.getElementsByClassName(
"t--datasource-delete",
);
const editOption = document.getElementsByClassName("t--datasource-rename");
const refreshOption = document.getElementsByClassName(
"t--datasource-refresh",
);
expect(deleteOption.length).toBe(0);
expect(editOption.length).toBe(0);
expect(refreshOption.length).toBe(1);
});
});
|
693 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/Explorer/Libraries | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/Explorer/Libraries/__tests__/Installer.test.tsx | import React from "react";
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import { Provider } from "react-redux";
import store from "store";
import { ThemeProvider } from "styled-components";
import { lightTheme } from "selectors/themeSelectors";
import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
import { Installer } from "pages/Editor/Explorer/Libraries/Installer";
import { BrowserRouter } from "react-router-dom";
export const fetchApplicationMockResponse = {
responseMeta: {
status: 200,
success: true,
},
data: {
application: {
id: "605c435a91dea93f0eaf91b8",
name: "My Application",
slug: "my-application",
workspaceId: "",
evaluationVersion: 1,
appIsExample: false,
gitApplicationMetadata: undefined,
applicationVersion: 2,
},
pages: [
{
id: "605c435a91dea93f0eaf91ba",
name: "Page1",
isDefault: true,
slug: "page-1",
},
{
id: "605c435a91dea93f0eaf91bc",
name: "Page2",
isDefault: false,
slug: "page-2",
},
],
workspaceId: "",
},
};
describe("Contains all UI tests for JS libraries", () => {
store.dispatch({
type: ReduxActionTypes.TOGGLE_INSTALLER,
payload: true,
});
afterEach(cleanup);
it("Headers should exist", () => {
render(
<BrowserRouter>
<Provider store={store}>
<ThemeProvider theme={lightTheme}>
<Installer />
</ThemeProvider>
</Provider>
</BrowserRouter>,
);
expect(screen.getByText("Recommended libraries")).toBeDefined();
expect(screen.getByTestId("library-url")).toBeDefined();
expect(screen.getByTestId("install-library-btn")).toBeDisabled();
});
it("Validates URL", () => {
render(
<BrowserRouter>
<Provider store={store}>
<ThemeProvider theme={lightTheme}>
<Installer />
</ThemeProvider>
</Provider>
</BrowserRouter>,
);
const input = screen.getByTestId("library-url");
fireEvent.change(input, { target: { value: "https://valid.com/file.js" } });
expect(screen.getByTestId("install-library-btn")).toBeEnabled();
expect(screen.queryByText("Please enter a valid URL")).toBeNull();
fireEvent.change(input, { target: { value: "23" } });
expect(screen.queryByText("Please enter a valid URL")).toBeDefined();
expect(screen.getByTestId("install-library-btn")).toBeDisabled();
});
it("Renders progress bar", () => {
render(
<BrowserRouter>
<Provider store={store}>
<ThemeProvider theme={lightTheme}>
<Installer />
</ThemeProvider>
</Provider>
</BrowserRouter>,
);
store.dispatch({
type: ReduxActionTypes.FETCH_APPLICATION_SUCCESS,
payload: {
...fetchApplicationMockResponse.data.application,
pages: fetchApplicationMockResponse.data.pages,
},
});
const input = screen.getByTestId("library-url");
fireEvent.change(input, {
target: {
value:
"https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.6/dayjs.min.js",
},
});
const installButton = screen.getByTestId("install-library-btn");
expect(installButton).toBeDefined();
fireEvent.click(installButton);
expect(
screen.queryByText(
`Installing library for ${fetchApplicationMockResponse.data.application.name}`,
),
).toBeDefined();
});
it("Progress bar should disappear once the installation succeeds or fails", () => {
render(
<BrowserRouter>
<Provider store={store}>
<ThemeProvider theme={lightTheme}>
<Installer />
</ThemeProvider>
</Provider>
</BrowserRouter>,
);
store.dispatch({
type: ReduxActionTypes.INSTALL_LIBRARY_INIT,
payload:
"https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.6/dayjs.min.js",
});
expect(
screen.queryByText(
`Installing library for ${fetchApplicationMockResponse.data.application.name}`,
),
).toBeDefined();
store.dispatch({
type: ReduxActionTypes.INSTALL_LIBRARY_SUCCESS,
payload: {
name: "dayjs",
version: "1.11.6",
accessor: ["dayjs"],
url: "https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.6/dayjs.min.js",
},
});
expect(
screen.queryByText(
`Installing library for ${fetchApplicationMockResponse.data.application.name}`,
),
).toBeNull();
});
});
|
705 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.test.tsx | const history = jest.fn();
const dispatch = jest.fn();
import { bindDataOnCanvas } from "actions/pluginActionActions";
import { builderURL, integrationEditorURL } from "@appsmith/RouteBuilder";
import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
import { INTEGRATION_TABS } from "constants/routes";
import React from "react";
import { Provider } from "react-redux";
import { fireEvent, render, screen } from "test/testUtils";
import OnboardingChecklist from "./Checklist";
import { getStore, initialState } from "./testUtils";
import urlBuilder from "@appsmith/entities/URLRedirect/URLAssembly";
import "@testing-library/jest-dom";
import * as onboardingSelectors from "selectors/onboardingSelectors";
let container: any = null;
jest.mock("react-redux", () => {
const originalModule = jest.requireActual("react-redux");
return {
...originalModule,
useDispatch: () => dispatch,
};
});
jest.mock("utils/history", () => ({
push: history,
listen: jest.fn(),
}));
jest.mock("utils/lazyLottie", () => ({
loadAnimation: () => {
return {
play: jest.fn(),
destroy: jest.fn(),
goToAndStop: jest.fn(),
};
},
}));
function renderComponent(store: any) {
render(
<Provider store={store}>
<OnboardingChecklist />
</Provider>,
container,
);
}
describe("Checklist", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
urlBuilder.updateURLParams(
{
applicationSlug: initialState.ui.applications.currentApplication.slug,
applicationId: initialState.entities.pageList.applicationId,
applicationVersion: 2,
},
[
{
pageSlug: initialState.entities.pageList.pages[0].slug,
pageId: initialState.entities.pageList.currentPageId,
},
],
);
});
afterEach(() => {
jest.clearAllMocks();
});
it("is rendered", () => {
renderComponent(getStore(0));
const wrapper = screen.getAllByTestId("checklist-wrapper");
expect(wrapper.length).toBe(1);
const completionInfo = screen.getAllByTestId("checklist-completion-info");
expect(completionInfo[0].innerHTML).toBe("0 of 5 ");
const datasourceButton = screen.getAllByTestId("checklist-datasource");
expect(datasourceButton.length).toBe(1);
const actionButton = screen.getAllByTestId("checklist-action");
expect(actionButton.length).toBe(1);
const widgetButton = screen.getAllByTestId("checklist-widget");
expect(widgetButton.length).toBe(1);
const connectionButton = screen.getAllByTestId("checklist-connection");
expect(connectionButton.length).toBe(1);
const deployButton = screen.getAllByTestId("checklist-deploy");
expect(deployButton.length).toBe(1);
const banner = screen.queryAllByTestId("checklist-completion-banner");
expect(banner.length).toBe(0);
fireEvent.click(datasourceButton[0]);
expect(history).toHaveBeenCalledWith(
integrationEditorURL({
pageId: initialState.entities.pageList.currentPageId,
selectedTab: INTEGRATION_TABS.NEW,
}),
);
});
it("disabled items should not be clickable", () => {
renderComponent(getStore(0));
const wrapper = screen.getAllByTestId("checklist-wrapper");
expect(wrapper.length).toBe(1);
const actionButton = screen.queryAllByTestId("checklist-action");
dispatch.mockClear();
fireEvent.click(actionButton[0]);
expect(dispatch).toHaveBeenCalledTimes(0);
const connectionButton = screen.queryAllByTestId("checklist-connection");
dispatch.mockClear();
fireEvent.click(connectionButton[0]);
expect(dispatch).toHaveBeenCalledTimes(0);
});
it("with `add a datasource` task checked off", () => {
renderComponent(getStore(1));
const datasourceButton = screen.queryAllByTestId("checklist-datasource");
expect(datasourceButton[0]).toHaveStyle("cursor: auto");
const actionButton = screen.queryAllByTestId("checklist-action");
fireEvent.click(actionButton[0]);
expect(history).toHaveBeenCalledWith(
integrationEditorURL({
pageId: initialState.entities.pageList.currentPageId,
selectedTab: INTEGRATION_TABS.ACTIVE,
}),
);
});
it("with `add a query` task checked off", () => {
renderComponent(getStore(2));
const actionButton = screen.queryAllByTestId("checklist-action");
expect(actionButton[0]).toHaveStyle("cursor: auto");
const widgetButton = screen.queryAllByTestId("checklist-widget");
fireEvent.click(widgetButton[0]);
expect(history).toHaveBeenCalledWith(
builderURL({ pageId: initialState.entities.pageList.currentPageId }),
);
expect(dispatch).toHaveBeenCalledWith({
type: ReduxActionTypes.TOGGLE_ONBOARDING_WIDGET_SELECTION,
payload: true,
});
expect(dispatch).toHaveBeenCalledWith({
type: ReduxActionTypes.SET_FORCE_WIDGET_PANEL_OPEN,
payload: true,
});
});
it("with `add a widget` task checked off", () => {
const store: any = getStore(3);
renderComponent(store);
const widgetButton = screen.queryAllByTestId("checklist-widget");
expect(widgetButton[0]).toHaveStyle("cursor: auto");
const connectionButton = screen.queryAllByTestId("checklist-connection");
fireEvent.click(connectionButton[0]);
expect(dispatch).toHaveBeenCalledWith(
bindDataOnCanvas({
queryId: store.getState().entities.actions[0].config.id,
applicationId: store.getState().entities.pageList.applicationId,
pageId: store.getState().entities.pageList.currentPageId,
}),
);
});
it("with `connect your data` task checked off", () => {
const isWidgetActionConnectionPresentSelector = jest.spyOn(
onboardingSelectors,
"isWidgetActionConnectionPresent",
);
isWidgetActionConnectionPresentSelector.mockImplementation(() => {
return true;
});
renderComponent(getStore(4));
const connectionButton = screen.queryAllByTestId("checklist-connection");
expect(connectionButton[0]).toHaveStyle("cursor: auto");
const deployButton = screen.queryAllByTestId("checklist-deploy");
fireEvent.click(deployButton[0]);
expect(dispatch).toHaveBeenCalledWith({
type: ReduxActionTypes.PUBLISH_APPLICATION_INIT,
payload: {
applicationId: initialState.entities.pageList.applicationId,
},
});
});
it("with `Deploy your application` task checked off", () => {
renderComponent(getStore(5));
const deployButton = screen.queryAllByTestId("checklist-deploy-button");
expect(deployButton.length).toBe(0);
const banner = screen.queryAllByTestId("checklist-completion-banner");
expect(banner.length).toBe(1);
});
});
|
710 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/FirstTimeUserOnboarding/Statusbar.test.tsx | const dispatch = jest.fn();
import React from "react";
import { Provider } from "react-redux";
import { render } from "test/testUtils";
import OnboardingStatusbar from "./Statusbar";
import { getStore } from "./testUtils";
import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
import { SIGNPOSTING_STEP } from "./Utils";
import { signpostingStepUpdateInit } from "actions/onboardingActions";
import * as onboardingSelectors from "selectors/onboardingSelectors";
let container: any = null;
jest.mock("react-redux", () => {
const originalModule = jest.requireActual("react-redux");
return {
...originalModule,
useDispatch: () => dispatch,
};
});
jest.mock("../../../selectors/onboardingSelectors", () => {
const originalModule = jest.requireActual(
"../../../selectors/onboardingSelectors",
);
return {
...originalModule,
isWidgetActionConnectionPresent: jest.fn(),
};
});
const originalOnboardingSelectors = jest.requireActual(
"../../../selectors/onboardingSelectors",
);
function renderComponent(store: any) {
render(
<Provider store={store}>
<OnboardingStatusbar />
</Provider>,
container,
);
}
describe("Statusbar", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
afterEach(() => {
jest.clearAllMocks();
});
it("is rendered", async () => {
renderComponent(getStore(0));
expect(dispatch).toHaveBeenCalledTimes(5);
expect(dispatch).toHaveBeenCalledWith(
expect.objectContaining({
payload: {
completed: false,
step: expect.any(String),
},
type: ReduxActionTypes.SIGNPOSTING_STEP_UPDATE_INIT,
}),
);
});
it("on completing first step", async () => {
renderComponent(getStore(1));
expect(dispatch).toHaveBeenNthCalledWith(
1,
signpostingStepUpdateInit({
step: SIGNPOSTING_STEP.CONNECT_A_DATASOURCE,
completed: true,
}),
);
});
it("on completing second step", async () => {
renderComponent(getStore(2));
expect(dispatch).toHaveBeenNthCalledWith(
2,
signpostingStepUpdateInit({
step: SIGNPOSTING_STEP.CREATE_A_QUERY,
completed: true,
}),
);
});
it("on completing third step", async () => {
renderComponent(getStore(3));
expect(dispatch).toHaveBeenNthCalledWith(
3,
signpostingStepUpdateInit({
step: SIGNPOSTING_STEP.ADD_WIDGETS,
completed: true,
}),
);
});
it("on completing fourth step", async () => {
const isWidgetActionConnectionPresentSelector = jest.spyOn(
onboardingSelectors,
"isWidgetActionConnectionPresent",
);
isWidgetActionConnectionPresentSelector.mockImplementation(() => {
return true;
});
renderComponent(getStore(4));
expect(dispatch).toHaveBeenNthCalledWith(
4,
signpostingStepUpdateInit({
step: SIGNPOSTING_STEP.CONNECT_DATA_TO_WIDGET,
completed: true,
}),
);
});
it("on completing fifth step", async () => {
renderComponent(getStore(5));
expect(dispatch).toHaveBeenNthCalledWith(
5,
signpostingStepUpdateInit({
step: SIGNPOSTING_STEP.DEPLOY_APPLICATIONS,
completed: true,
}),
);
});
it("should test useIsWidgetActionConnectionPresent function", () => {
const store = getStore(4).getState() as any;
const isWidgetActionConnectionPresentHelper = () => {
return originalOnboardingSelectors.isWidgetActionConnectionPresent.resultFunc(
store.entities.canvasWidgets,
store.entities.actions,
store.evaluations.dependencies.inverseDependencyMap,
);
};
//Both property and trigger dependency present
expect(isWidgetActionConnectionPresentHelper()).toBe(true);
//only trigger dependency present
store.evaluations.dependencies.inverseDependencyMap = {};
expect(isWidgetActionConnectionPresentHelper()).toBe(true);
//no dependency present
store.entities.canvasWidgets = {};
store.entities.actions = [];
expect(isWidgetActionConnectionPresentHelper()).toBe(false);
//only trigger dependency present
store.entities.canvasWidgets = {
[Math.random()]: {
widgetName: "widget",
onClick: "{{Query.run()}}",
dynamicTriggerPathList: [
{
key: "onClick",
},
],
text: "{{Query.data}}",
},
};
store.entities.actions = [
{
config: {
id: Math.random(),
pageId: 1,
name: "Query",
},
},
];
expect(isWidgetActionConnectionPresentHelper()).toBe(true);
//no dependency present
store.entities.canvasWidgets = {};
store.entities.actions = [];
expect(isWidgetActionConnectionPresentHelper()).toBe(false);
//only nested trigger dependency present
store.entities.canvasWidgets = {
[Math.random()]: {
widgetName: "widget",
column: {
onClick: "{{Query.run()}}",
},
dynamicTriggerPathList: [
{
key: "column.onClick",
},
],
text: "label",
},
};
store.entities.actions = [
{
config: {
id: Math.random(),
pageId: 1,
name: "Query",
},
},
];
expect(isWidgetActionConnectionPresentHelper()).toBe(true);
//no dependency present
store.entities.canvasWidgets = {};
store.entities.actions = [];
expect(isWidgetActionConnectionPresentHelper()).toBe(false);
//only property dependency present
store.entities.canvasWidgets = {
[Math.random()]: {
widgetName: "widget",
dynamicTriggerPathList: [],
text: "{{Query.data}}",
},
};
store.entities.actions = [
{
config: {
id: Math.random(),
pageId: 1,
name: "Query",
},
},
];
store.evaluations.dependencies.inverseDependencyMap = {
"Query.data": ["Query", "widget.text"],
};
expect(isWidgetActionConnectionPresentHelper()).toBe(true);
});
});
|
726 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.test.tsx | import React from "react";
import {
createMessage,
SAVE_HOTKEY_TOASTER_MESSAGE,
} from "@appsmith/constants/messages";
import { all } from "@redux-saga/core/effects";
import { redoAction, undoAction } from "actions/pageActions";
import { Toast } from "design-system";
import { MAIN_CONTAINER_WIDGET_ID } from "constants/WidgetConstants";
import { MemoryRouter } from "react-router-dom";
import * as utilities from "selectors/editorSelectors";
import * as dataTreeSelectors from "selectors/dataTreeSelectors";
import store, { runSagaMiddleware } from "store";
import {
buildChildren,
widgetCanvasFactory,
} from "test/factories/WidgetFactoryUtils";
import { sagasToRunForTests } from "test/sagas";
import {
dispatchTestKeyboardEventWithCode,
MockApplication,
mockCreateCanvasWidget,
mockGetCanvasWidgetDsl,
mockGetWidgetEvalValues,
MockPageDSL,
useMockDsl,
} from "test/testCommon";
import { MockCanvas } from "test/testMockedWidgets";
import { act, fireEvent, render, waitFor } from "test/testUtils";
import * as widgetRenderUtils from "utils/widgetRenderUtils";
import IDE from "../IDE";
import GlobalHotKeys from "./GlobalHotKeys";
import * as widgetSelectionsActions from "actions/widgetSelectionActions";
import { SelectionRequestType } from "sagas/WidgetSelectUtils";
import * as widgetActions from "actions/widgetActions";
import * as uiSelectors from "selectors/ui";
import { NavigationMethod } from "../../../utils/history";
import { setExplorerPinnedAction } from "actions/explorerActions";
jest.mock("constants/routes", () => {
return {
...jest.requireActual("constants/routes"),
matchBuilderPath: () => true,
};
});
describe("Canvas Hot Keys", () => {
beforeAll(() => {
runSagaMiddleware();
});
const mockGetIsFetchingPage = jest.spyOn(utilities, "getIsFetchingPage");
const spyGetCanvasWidgetDsl = jest.spyOn(utilities, "getCanvasWidgetDsl");
function UpdatedEditor({ dsl }: any) {
useMockDsl(dsl);
return <IDE />;
}
// These need to be at the top to avoid imports not being mocked. ideally should be in setup.ts but will override for all other tests
beforeAll(() => {
const mockGenerator = function* () {
yield all([]);
};
// top avoid the first middleware run which wud initiate all sagas.
jest.mock("sagas", () => ({
rootSaga: mockGenerator,
}));
// only the default exports are mocked to avoid overriding utilities exported out of them. defaults are marked to avoid worker initiation and page api calls in tests.
jest.mock("sagas/EvaluationsSaga", () => ({
...jest.requireActual("sagas/EvaluationsSaga"),
default: mockGenerator,
}));
jest.mock("@appsmith/sagas/PageSagas", () => ({
...jest.requireActual("@appsmith/sagas/PageSagas"),
default: mockGenerator,
}));
});
describe("Select all hotkey", () => {
jest
.spyOn(widgetRenderUtils, "createCanvasWidget")
.mockImplementation(mockCreateCanvasWidget);
jest
.spyOn(dataTreeSelectors, "getWidgetEvalValues")
.mockImplementation(mockGetWidgetEvalValues);
jest
.spyOn(utilities, "computeMainContainerWidget")
.mockImplementation((widget) => widget as any);
it("Cmd + A - select all widgets on canvas", async () => {
const children: any = buildChildren([
{
type: "TABS_WIDGET",
parentId: MAIN_CONTAINER_WIDGET_ID,
widgetId: "tabsWidgetId",
},
{
type: "SWITCH_WIDGET",
parentId: MAIN_CONTAINER_WIDGET_ID,
widgetId: "switchWidgetId",
},
]);
const dsl: any = widgetCanvasFactory.build({
children,
});
spyGetCanvasWidgetDsl.mockImplementation(mockGetCanvasWidgetDsl);
mockGetIsFetchingPage.mockImplementation(() => false);
const spyWidgetSelection = jest.spyOn(
widgetSelectionsActions,
"selectWidgetInitAction",
);
const spyPaste = jest.spyOn(widgetActions, "pasteWidget");
const component = render(
<MemoryRouter
initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]}
>
<MockApplication>
<GlobalHotKeys
getMousePosition={() => {
return { x: 0, y: 0 };
}}
>
<UpdatedEditor dsl={dsl} />
</GlobalHotKeys>
</MockApplication>
</MemoryRouter>,
{ initialState: store.getState(), sagasToRun: sagasToRunForTests },
);
const canvasWidgets = component.queryAllByTestId("test-widget");
expect(canvasWidgets.length).toBe(2);
act(() => {
if (canvasWidgets[0].firstChild) {
fireEvent.mouseOver(canvasWidgets[0].firstChild);
fireEvent.click(canvasWidgets[0].firstChild);
}
});
const tabsWidgetName: any =
component.container.querySelector(`span.t--widget-name`);
fireEvent.click(tabsWidgetName);
expect(spyWidgetSelection).toHaveBeenCalledWith(
SelectionRequestType.One,
["tabsWidgetId"],
NavigationMethod.CanvasClick,
undefined,
);
spyWidgetSelection.mockClear();
const artBoard: any = component.queryByTestId("t--canvas-artboard");
// deselect all other widgets
fireEvent.click(artBoard);
expect(spyWidgetSelection).toHaveBeenCalledWith(
SelectionRequestType.Empty,
[],
NavigationMethod.CanvasClick,
);
spyWidgetSelection.mockClear();
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"A",
65,
false,
true,
);
expect(spyWidgetSelection).toHaveBeenCalledWith(SelectionRequestType.All);
spyWidgetSelection.mockClear();
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"escape",
27,
false,
false,
);
expect(spyWidgetSelection).toHaveBeenCalledWith(
SelectionRequestType.Empty,
);
spyWidgetSelection.mockClear();
act(() => {
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"A",
65,
false,
true,
);
});
expect(spyWidgetSelection).toHaveBeenCalledWith(SelectionRequestType.All);
spyWidgetSelection.mockClear();
act(() => {
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"C",
67,
false,
true,
);
});
act(() => {
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"V",
86,
false,
true,
);
});
expect(spyPaste).toHaveBeenCalled();
});
});
afterAll(() => jest.resetModules());
});
describe("Cut/Copy/Paste hotkey", () => {
const spyWidgetSelection = jest.spyOn(
widgetSelectionsActions,
"selectWidgetInitAction",
);
const spyCut = jest.spyOn(widgetActions, "cutWidget");
const spyCopy = jest.spyOn(widgetActions, "copyWidget");
const spyPaste = jest.spyOn(widgetActions, "pasteWidget");
jest.spyOn(uiSelectors, "getSelectedWidgets").mockReturnValue(["testWidget"]);
beforeEach(() => {
spyWidgetSelection.mockClear();
spyCut.mockClear();
spyCopy.mockClear();
spyPaste.mockClear();
});
it("Should copy and paste all selected widgets with hotkey cmd + c and cmd + v ", async () => {
const children: any = buildChildren([
{
type: "TABS_WIDGET",
topRow: 5,
bottomRow: 30,
leftColumn: 5,
rightColumn: 30,
parentId: MAIN_CONTAINER_WIDGET_ID,
},
{
type: "SWITCH_WIDGET",
topRow: 5,
bottomRow: 10,
leftColumn: 40,
rightColumn: 48,
parentId: MAIN_CONTAINER_WIDGET_ID,
},
]);
const dsl: any = widgetCanvasFactory.build({
children,
});
const component = render(
<MockPageDSL dsl={dsl}>
<GlobalHotKeys
getMousePosition={() => {
return { x: 0, y: 0 };
}}
>
<MockCanvas />
</GlobalHotKeys>
</MockPageDSL>,
{ initialState: store.getState(), sagasToRun: sagasToRunForTests },
);
const artBoard: any = await component.queryByTestId("t--canvas-artboard");
// deselect all other widgets
fireEvent.click(artBoard);
act(() => {
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"A",
65,
false,
true,
);
});
expect(spyWidgetSelection).toBeCalledWith(SelectionRequestType.All);
// jest.spyOn(sagaSelectors, "getWidgetMetaProps").mockReturnValue({});
//
// let selectedWidgets = await component.queryAllByTestId("t--selected");
// expect(selectedWidgets.length).toBe(2);
// jest.spyOn(sagaSelectors, "getWidgetMetaProps").mockReturnValue({});
act(() => {
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"C",
67,
false,
true,
);
});
expect(spyCopy).toBeCalled();
act(() => {
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"V",
86,
false,
true,
);
});
expect(spyPaste).toBeCalled();
act(() => {
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"A",
65,
false,
true,
);
});
expect(spyWidgetSelection).toBeCalledWith(SelectionRequestType.All);
});
it("Should cut and paste all selected widgets with hotkey cmd + x and cmd + v ", async () => {
const children: any = buildChildren([
{
type: "TABS_WIDGET",
topRow: 5,
bottomRow: 30,
leftColumn: 5,
rightColumn: 30,
parentId: MAIN_CONTAINER_WIDGET_ID,
},
{
type: "SWITCH_WIDGET",
topRow: 5,
bottomRow: 10,
leftColumn: 40,
rightColumn: 48,
parentId: MAIN_CONTAINER_WIDGET_ID,
},
]);
const dsl: any = widgetCanvasFactory.build({
children,
});
const component = render(
<MockPageDSL dsl={dsl}>
<GlobalHotKeys
getMousePosition={() => {
return { x: 0, y: 0 };
}}
>
<MockCanvas />
</GlobalHotKeys>
</MockPageDSL>,
);
const artBoard: any = await component.queryByTestId("t--canvas-artboard");
// deselect all other widgets
fireEvent.click(artBoard);
act(() => {
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"A",
65,
false,
true,
);
});
expect(spyWidgetSelection).toBeCalledWith(SelectionRequestType.All);
act(() => {
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"X",
88,
false,
true,
);
});
expect(spyCut).toBeCalled();
act(() => {
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"V",
86,
false,
true,
);
});
expect(spyPaste).toBeCalled();
});
});
describe("Undo/Redo hotkey", () => {
it("should dispatch undo Action on cmd + z", () => {
const dispatchSpy = jest.spyOn(store, "dispatch");
const component = render(
<MockPageDSL>
<GlobalHotKeys
getMousePosition={() => {
return { x: 0, y: 0 };
}}
>
<MockCanvas />
</GlobalHotKeys>
</MockPageDSL>,
);
dispatchSpy.mockClear();
act(() => {
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"Z",
90,
false,
true,
);
});
expect(dispatchSpy).toBeCalledTimes(1);
expect(dispatchSpy).toBeCalledWith(undoAction());
});
it("should dispatch redo Action on cmd + shift + z", () => {
const dispatchSpy = jest.spyOn(store, "dispatch");
const component = render(
<MockPageDSL>
<GlobalHotKeys
getMousePosition={() => {
return { x: 0, y: 0 };
}}
>
<MockCanvas />
</GlobalHotKeys>
</MockPageDSL>,
);
dispatchSpy.mockClear();
act(() => {
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"Z",
90,
true,
true,
);
});
expect(dispatchSpy).toBeCalledTimes(1);
expect(dispatchSpy).toBeCalledWith(redoAction());
});
it("should dispatch redo Action on ctrl + y", () => {
const dispatchSpy = jest.spyOn(store, "dispatch");
const component = render(
<MockPageDSL>
<GlobalHotKeys
getMousePosition={() => {
return { x: 0, y: 0 };
}}
>
<MockCanvas />
</GlobalHotKeys>
</MockPageDSL>,
);
dispatchSpy.mockClear();
act(() => {
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"Y",
89,
false,
true,
);
});
expect(dispatchSpy).toBeCalledTimes(1);
expect(dispatchSpy).toBeCalledWith(redoAction());
});
});
describe("cmd + s hotkey", () => {
it("Should render toast message", async () => {
const component = render(
<>
<Toast />
<GlobalHotKeys
getMousePosition={() => {
return { x: 0, y: 0 };
}}
>
<div />
</GlobalHotKeys>
</>,
);
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"s",
83,
false,
true,
);
await waitFor(() => {
expect(
component.getByText(createMessage(SAVE_HOTKEY_TOASTER_MESSAGE)),
).toBeDefined();
});
});
});
describe("mod + / hotkey", () => {
it("Should dispatch pin/unpin explorer on mod + /", async () => {
const dispatchSpy = jest.spyOn(store, "dispatch");
const component = render(
<GlobalHotKeys
getMousePosition={() => {
return { x: 0, y: 0 };
}}
>
<div />
</GlobalHotKeys>,
);
dispatchSpy.mockClear();
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"/",
191,
false,
true,
);
expect(dispatchSpy).toBeCalledTimes(2);
expect(dispatchSpy).toHaveBeenNthCalledWith(
1,
setExplorerPinnedAction(false),
);
});
it("Shouldn't dispatch pin/unpin explorer on mod + / when signposting is enabled", async () => {
const dispatchSpy = jest.spyOn(store, "dispatch");
const state: any = {
entities: {
pageList: {
applicationId: "1",
},
},
ui: {
onBoarding: {
firstTimeUserOnboardingApplicationIds: ["1"],
},
},
};
const component = render(
<GlobalHotKeys
getMousePosition={() => {
return { x: 0, y: 0 };
}}
>
<div />
</GlobalHotKeys>,
{
initialState: state,
},
);
dispatchSpy.mockClear();
dispatchTestKeyboardEventWithCode(
component.container,
"keydown",
"/",
191,
false,
true,
);
expect(dispatchSpy).toBeCalledTimes(0);
});
});
|
739 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/IDE/AppsmithIDE.test.tsx | import type { AppState } from "@appsmith/reducers";
import { all } from "@redux-saga/core/effects";
import lodash from "lodash";
import React from "react";
import { MemoryRouter } from "react-router-dom";
import * as dataTreeSelectors from "selectors/dataTreeSelectors";
import * as utilities from "selectors/editorSelectors";
import store from "store";
import {
buildChildren,
widgetCanvasFactory,
} from "test/factories/WidgetFactoryUtils";
import { sagasToRunForTests } from "test/sagas";
import {
MockApplication,
mockCreateCanvasWidget,
mockGetCanvasWidgetDsl,
mockGetPagePermissions,
mockGetWidgetEvalValues,
syntheticTestMouseEvent,
} from "test/testCommon";
import { UpdatedEditor } from "test/testMockedWidgets";
import { act, fireEvent, render } from "test/testUtils";
import { generateReactKey } from "utils/generators";
import { getAbsolutePixels } from "utils/helpers";
import * as useDynamicAppLayoutHook from "utils/hooks/useDynamicAppLayout";
import * as widgetRenderUtils from "utils/widgetRenderUtils";
import GlobalHotKeys from "../GlobalHotKeys";
import * as uiSelectors from "selectors/ui";
const renderNestedComponent = () => {
const initialState = store.getState() as unknown as Partial<AppState>;
const canvasId = "canvas-id";
const containerId = "container-id";
const children: any = buildChildren([
{
type: "INPUT_WIDGET_V2",
dragDisabled: true,
leftColumn: 0,
topRow: 1,
parentId: canvasId,
rightColumn: 5,
bottomRow: 2,
text: "DRAG DISABLED INPUT",
},
{
type: "TEXT_WIDGET",
leftColumn: 0,
parentId: canvasId,
rightColumn: 5,
bottomRow: 3,
topRow: 2,
text: "LABEL",
widgetId: "text-widget",
},
]);
const canvasWidgetChildren: any = buildChildren([
{
type: "CANVAS_WIDGET",
parentId: containerId,
widgetId: canvasId,
children,
},
]);
const containerWidgetChildren: any = buildChildren([
{
type: "CONTAINER_WIDGET",
children: canvasWidgetChildren,
parentId: "0",
widgetId: containerId,
},
]);
const dsl: any = widgetCanvasFactory.build({
children: containerWidgetChildren,
});
return render(
<MemoryRouter
initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]}
>
<MockApplication>
<GlobalHotKeys>
<UpdatedEditor dsl={dsl} />
</GlobalHotKeys>
</MockApplication>
</MemoryRouter>,
{ initialState, sagasToRun: sagasToRunForTests },
);
};
describe("Drag and Drop widgets into Main container", () => {
const mockGetIsFetchingPage = jest.spyOn(utilities, "getIsFetchingPage");
const spyGetCanvasWidgetDsl = jest.spyOn(utilities, "getCanvasWidgetDsl");
jest
.spyOn(widgetRenderUtils, "createCanvasWidget")
.mockImplementation(mockCreateCanvasWidget);
jest
.spyOn(dataTreeSelectors, "getWidgetEvalValues")
.mockImplementation(mockGetWidgetEvalValues);
jest
.spyOn(utilities, "computeMainContainerWidget")
.mockImplementation((widget) => widget as any);
jest
.spyOn(useDynamicAppLayoutHook, "useDynamicAppLayout")
.mockImplementation(() => true);
const pushState = jest.spyOn(window.history, "pushState");
pushState.mockImplementation((state: any, title: any, url: any) => {
window.document.title = title;
window.location.pathname = url;
});
// These need to be at the top to avoid imports not being mocked. ideally should be in setup.ts but will override for all other tests
beforeAll(() => {
const mockGenerator = function* () {
yield all([]);
};
const debounceMocked = jest.spyOn(lodash, "debounce");
debounceMocked.mockImplementation((fn: any) => fn);
// top avoid the first middleware run which wud initiate all sagas.
jest.mock("sagas", () => ({
rootSaga: mockGenerator,
}));
// only the deafault exports are mocked to avoid overriding utilities exported out of them. defaults are marked to avoid worker initiation and page api calls in tests.
jest.mock("sagas/EvaluationsSaga", () => ({
...jest.requireActual("sagas/EvaluationsSaga"),
default: mockGenerator,
}));
jest.mock("@appsmith/sagas/PageSagas", () => ({
...jest.requireActual("@appsmith/sagas/PageSagas"),
default: mockGenerator,
}));
});
it("Drag to move widgets", () => {
const children: any = buildChildren([
{
type: "TABS_WIDGET",
topRow: 5,
bottomRow: 5,
leftColumn: 5,
rightColumn: 5,
widgetId: "tabsWidgetId",
},
]);
const dsl: any = widgetCanvasFactory.build({
children,
});
spyGetCanvasWidgetDsl.mockImplementation(mockGetCanvasWidgetDsl);
mockGetIsFetchingPage.mockImplementation(() => false);
const component = render(
<MemoryRouter
initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]}
>
<MockApplication>
<GlobalHotKeys>
<UpdatedEditor dsl={dsl} />
</GlobalHotKeys>
</MockApplication>
</MemoryRouter>,
{ initialState: store.getState(), sagasToRun: sagasToRunForTests },
);
const propPane = component.queryByTestId("t--propertypane");
expect(propPane).toBeNull();
const canvasWidgets = component.queryAllByTestId("test-widget");
expect(canvasWidgets.length).toBe(1);
const tabsWidget: any = component.container.querySelector(
".t--draggable-tabswidget",
);
const tab: any = component.container.querySelector(".t--widget-tabswidget");
const initPositions = {
left: tab.style.left,
top: tab.style.top,
};
act(() => {
fireEvent.mouseOver(tabsWidget);
});
jest
.spyOn(uiSelectors, "getSelectedWidgets")
.mockReturnValue(["tabsWidgetId"]);
act(() => {
fireEvent.dragStart(tabsWidget);
});
const mainCanvas: any = component.queryByTestId("div-dragarena-0");
act(() => {
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mousemove", {
bubbles: true,
cancelable: true,
}),
{
offsetX: 0,
offsetY: 0,
},
),
);
});
act(() => {
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mousemove", {
bubbles: true,
cancelable: true,
}),
{
offsetX: -50,
offsetY: -50,
},
),
);
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mouseup", {
bubbles: true,
cancelable: true,
}),
),
);
});
const movedTab: any = component.container.querySelector(
".t--widget-tabswidget",
);
const finalPositions = {
left: movedTab.style.left,
top: movedTab.style.top,
};
expect(finalPositions.left).not.toEqual(initPositions.left);
expect(finalPositions.top).not.toEqual(initPositions.top);
});
it("When widgets are moved out of main container bounds move them back to previous position", () => {
const children: any = buildChildren([
{
type: "TABS_WIDGET",
topRow: 5,
bottomRow: 5,
leftColumn: 5,
rightColumn: 5,
},
]);
const dsl: any = widgetCanvasFactory.build({
children,
});
spyGetCanvasWidgetDsl.mockImplementation(mockGetCanvasWidgetDsl);
mockGetIsFetchingPage.mockImplementation(() => false);
const component = render(
<MemoryRouter
initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]}
>
<MockApplication>
<GlobalHotKeys>
<UpdatedEditor dsl={dsl} />
</GlobalHotKeys>
</MockApplication>
</MemoryRouter>,
{ initialState: store.getState(), sagasToRun: sagasToRunForTests },
);
const propPane = component.queryByTestId("t--propertypane");
expect(propPane).toBeNull();
const canvasWidgets = component.queryAllByTestId("test-widget");
expect(canvasWidgets.length).toBe(1);
const tabsWidget: any = component.container.querySelector(
".t--draggable-tabswidget",
);
const tab: any = component.container.querySelector(".t--widget-tabswidget");
const initPositions = {
left: tab.style.left,
top: tab.style.top,
};
act(() => {
fireEvent.mouseOver(tabsWidget);
});
act(() => {
fireEvent.dragStart(tabsWidget);
});
const mainCanvas: any = component.queryByTestId("div-dragarena-0");
act(() => {
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mousemove", {
bubbles: true,
cancelable: true,
}),
{
offsetX: 0,
offsetY: 0,
},
),
);
});
act(() => {
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mousemove", {
bubbles: true,
cancelable: true,
}),
{
offsetX: -500,
offsetY: -500,
},
),
);
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mouseup", {
bubbles: true,
cancelable: true,
}),
),
);
});
const movedTab: any = component.container.querySelector(
".t--widget-tabswidget",
);
const finalPositions = {
left: movedTab.style.left,
top: movedTab.style.top,
};
expect(finalPositions.left).toEqual(initPositions.left);
expect(finalPositions.top).toEqual(initPositions.top);
});
// ToDO(Ashok): Check with Rahul if this test case is still relevant post reflow.
// it("When widgets are colliding with other widgets move them back to previous position", () => {
// const children: any = buildChildren([
// {
// type: "TABS_WIDGET",
// topRow: 5,
// bottomRow: 15,
// leftColumn: 5,
// rightColumn: 15,
// },
// {
// type: "TABLE_WIDGET",
// topRow: 15,
// bottomRow: 25,
// leftColumn: 5,
// rightColumn: 15,
// },
// ]);
// const dsl: any = widgetCanvasFactory.build({
// children,
// });
// spyGetCanvasWidgetDsl.mockImplementation(mockGetCanvasWidgetDsl);
// mockGetIsFetchingPage.mockImplementation(() => false);
// const component = render(
// <MemoryRouter
// initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]}
// >
// <MockApplication>
// <GlobalHotKeys>
// <UpdatedEditor dsl={dsl} />
// </GlobalHotKeys>
// </MockApplication>
// </MemoryRouter>,
// { initialState: store.getState(), sagasToRun: sagasToRunForTests },
// );
// const propPane = component.queryByTestId("t--propertypane");
// expect(propPane).toBeNull();
// const canvasWidgets = component.queryAllByTestId("test-widget");
// expect(canvasWidgets.length).toBe(2);
// const tabsWidget: any = component.container.querySelector(
// ".t--draggable-tabswidget",
// );
// const tab: any = component.container.querySelector(".t--widget-tabswidget");
// const initPositions = {
// left: tab.style.left,
// top: tab.style.top,
// };
// act(() => {
// fireEvent.mouseOver(tabsWidget);
// });
// act(() => {
// fireEvent.dragStart(tabsWidget);
// });
// const mainCanvas: any = component.queryByTestId("div-dragarena-0");
// act(() => {
// fireEvent(
// mainCanvas,
// syntheticTestMouseEvent(
// new MouseEvent("mousemove", {
// bubbles: true,
// cancelable: true,
// }),
// {
// offsetX: 0,
// offsetY: 0,
// },
// ),
// );
// });
// act(() => {
// fireEvent(
// mainCanvas,
// syntheticTestMouseEvent(
// new MouseEvent("mousemove", {
// bubbles: true,
// cancelable: true,
// }),
// {
// offsetX: 0,
// offsetY: 50,
// },
// ),
// );
// fireEvent(
// mainCanvas,
// syntheticTestMouseEvent(
// new MouseEvent("mouseup", {
// bubbles: true,
// cancelable: true,
// }),
// ),
// );
// });
// const movedTab: any = component.container.querySelector(
// ".t--widget-tabswidget",
// );
// const finalPositions = {
// left: movedTab.style.left,
// top: movedTab.style.top,
// };
// expect(finalPositions.left).toEqual(initPositions.left);
// expect(finalPositions.top).toEqual(initPositions.top);
// });
it("When widgets are out of bottom most bounds of parent canvas, canvas has to expand", () => {
const children: any = buildChildren([
{
type: "TABS_WIDGET",
topRow: 5,
bottomRow: 15,
leftColumn: 5,
rightColumn: 15,
},
{
type: "TABLE_WIDGET",
topRow: 15,
bottomRow: 25,
leftColumn: 5,
rightColumn: 15,
widgetId: "tableWidgetId",
},
]);
const dsl: any = widgetCanvasFactory.build({
children,
});
dsl.bottomRow = 250;
spyGetCanvasWidgetDsl.mockImplementation(mockGetCanvasWidgetDsl);
mockGetIsFetchingPage.mockImplementation(() => false);
const component = render(
<MemoryRouter
initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]}
>
<MockApplication>
<GlobalHotKeys>
<UpdatedEditor dsl={dsl} />
</GlobalHotKeys>
</MockApplication>
</MemoryRouter>,
{ initialState: store.getState(), sagasToRun: sagasToRunForTests },
);
const propPane = component.queryByTestId("t--propertypane");
expect(propPane).toBeNull();
const canvasWidgets = component.queryAllByTestId("test-widget");
expect(canvasWidgets.length).toBe(2);
const tabsWidget: any = component.container.querySelector(
".t--draggable-tablewidget",
);
act(() => {
fireEvent.mouseOver(tabsWidget);
});
jest
.spyOn(uiSelectors, "getSelectedWidgets")
.mockReturnValue(["tableWidgetId"]);
act(() => {
fireEvent.dragStart(tabsWidget);
});
const mainCanvas: any = component.queryByTestId("div-dragarena-0");
const dropTarget: any =
component.container.getElementsByClassName("t--drop-target")[0];
let initialLength = dropTarget.style.height;
act(() => {
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mousemove", {
bubbles: true,
cancelable: true,
}),
{
offsetX: 0,
offsetY: 0,
},
),
);
});
act(() => {
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mousemove", {
bubbles: true,
cancelable: true,
}),
{
offsetX: 0,
offsetY: 300,
// min height - (component height + bottom row)
},
),
);
});
let updatedDropTarget: any =
component.container.getElementsByClassName("t--drop-target")[0];
let updatedLength = updatedDropTarget.style.height;
expect(initialLength).not.toEqual(updatedLength);
initialLength = updatedLength;
const amountMovedY = 300;
act(() => {
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mousemove", {
bubbles: true,
cancelable: true,
}),
{
offsetX: 0,
offsetY: 300 + amountMovedY,
},
),
);
});
updatedDropTarget =
component.container.getElementsByClassName("t--drop-target")[0];
updatedLength = updatedDropTarget.style.height;
expect(getAbsolutePixels(initialLength) + amountMovedY).toEqual(
getAbsolutePixels(updatedLength),
);
});
it("Drag and Drop widget into an empty canvas", () => {
const children: any = buildChildren([]);
const dsl: any = widgetCanvasFactory.build({
children,
});
spyGetCanvasWidgetDsl.mockImplementation(mockGetCanvasWidgetDsl);
mockGetIsFetchingPage.mockImplementation(() => false);
jest
.spyOn(utilities, "getPagePermissions")
.mockImplementation(mockGetPagePermissions);
const component = render(
<MemoryRouter
initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]}
>
<MockApplication>
<GlobalHotKeys>
<UpdatedEditor dsl={dsl} />
</GlobalHotKeys>
</MockApplication>
</MemoryRouter>,
{ initialState: store.getState(), sagasToRun: sagasToRunForTests },
);
const propPane = component.queryByTestId("t--propertypane");
expect(propPane).toBeNull();
const canvasWidgets = component.queryAllByTestId("test-widget");
// empty canvas
expect(canvasWidgets.length).toBe(0);
const allAddEntityButtons: any =
component.container.querySelectorAll(".t--entity-add-btn");
const widgetAddButton = allAddEntityButtons[1];
act(() => {
fireEvent.click(widgetAddButton);
});
const containerButton: any = component.queryAllByText("Container");
act(() => {
fireEvent.dragStart(containerButton[0]);
});
const mainCanvas: any = component.queryByTestId("div-dragarena-0");
act(() => {
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mousemove", {
bubbles: true,
cancelable: true,
}),
{
offsetX: 200,
offsetY: 200,
},
),
);
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mousemove", {
bubbles: true,
cancelable: true,
}),
{
offsetX: 200,
offsetY: 200,
},
),
);
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mouseup", {
bubbles: true,
cancelable: true,
}),
{
offsetX: 200,
offsetY: 200,
},
),
);
});
const newlyAddedCanvas = component.container.querySelectorAll(
"div[type='CONTAINER_WIDGET']",
);
expect(newlyAddedCanvas.length).toBe(1);
});
it("Disallow drag if widget not focused", () => {
const initialState = store.getState() as unknown as Partial<AppState>;
const containerId = generateReactKey();
const canvasId = generateReactKey();
const canvasWidget = buildChildren([
{
type: "CANVAS_WIDGET",
parentId: containerId,
children: [],
widgetId: canvasId,
dropDisabled: true,
},
]);
const containerChildren: any = buildChildren([
{
type: "CONTAINER_WIDGET",
children: canvasWidget,
widgetId: containerId,
parentId: "0",
},
]);
const dsl: any = widgetCanvasFactory.build({
children: containerChildren,
});
spyGetCanvasWidgetDsl.mockImplementation(mockGetCanvasWidgetDsl);
mockGetIsFetchingPage.mockImplementation(() => false);
const component = render(
<MemoryRouter
initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]}
>
<MockApplication>
<GlobalHotKeys>
<UpdatedEditor dsl={dsl} />
</GlobalHotKeys>
</MockApplication>
</MemoryRouter>,
{ initialState, sagasToRun: sagasToRunForTests },
);
const widget: any = component.container.querySelector(
".t--widget-containerwidget",
);
const draggableWidget: any = component.container.querySelector(
".t--draggable-containerwidget",
);
const canvasWidgets = component.queryAllByTestId("test-widget");
expect(canvasWidgets.length).toBe(1);
const initWidgetPosition = {
left: widget.style.left,
top: widget.style.top,
};
jest
.spyOn(uiSelectors, "getSelectedWidgets")
.mockReturnValue([containerId]);
act(() => {
fireEvent.dragStart(draggableWidget);
});
let mainCanvas: any = component.queryByTestId("div-dragarena-0");
expect(mainCanvas).toBeNull();
// Focus on widget and drag
act(() => {
fireEvent.mouseOver(draggableWidget);
});
act(() => {
fireEvent.dragStart(draggableWidget);
});
mainCanvas = component.queryByTestId("div-dragarena-0");
act(() => {
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mousemove", {
bubbles: true,
cancelable: true,
}),
{
offsetX: 100,
offsetY: 100,
},
),
);
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mouseup", {
bubbles: true,
cancelable: true,
}),
),
);
});
const movedWidget: any = component.container.querySelector(
".t--widget-containerwidget",
);
const finalWidgetPosition = {
left: movedWidget.style.left,
top: movedWidget.style.top,
};
expect(finalWidgetPosition).not.toStrictEqual(initWidgetPosition);
});
afterAll(() => jest.resetModules());
});
describe("Drag in a nested container", () => {
const mockGetIsFetchingPage = jest.spyOn(utilities, "getIsFetchingPage");
const spyGetCanvasWidgetDsl = jest.spyOn(utilities, "getCanvasWidgetDsl");
// These need to be at the top to avoid imports not being mocked. ideally should be in setup.ts but will override for all other tests
beforeAll(() => {
const mockGenerator = function* () {
yield all([]);
};
const debounceMocked = jest.spyOn(lodash, "debounce");
debounceMocked.mockImplementation((fn: any) => fn);
// top avoid the first middleware run which wud initiate all sagas.
jest.mock("sagas", () => ({
rootSaga: mockGenerator,
}));
// only the deafault exports are mocked to avoid overriding utilities exported out of them. defaults are marked to avoid worker initiation and page api calls in tests.
jest.mock("sagas/EvaluationsSaga", () => ({
...jest.requireActual("sagas/EvaluationsSaga"),
default: mockGenerator,
}));
jest.mock("@appsmith/sagas/PageSagas", () => ({
...jest.requireActual("@appsmith/sagas/PageSagas"),
default: mockGenerator,
}));
});
it("container drags when focused on", () => {
spyGetCanvasWidgetDsl.mockImplementation(mockGetCanvasWidgetDsl);
mockGetIsFetchingPage.mockImplementation(() => false);
const component = renderNestedComponent();
jest
.spyOn(uiSelectors, "getSelectedWidgets")
.mockReturnValue(["container-id"]);
const containerWidget: any = component.container.querySelector(
".t--widget-containerwidget",
);
const draggableContainerWidget: any = component.container.querySelector(
".t--draggable-containerwidget",
);
const canvasWidgets = component.queryAllByTestId("test-widget");
expect(canvasWidgets.length).toBe(3);
const initContainerWidgetPosition = {
left: containerWidget.style.left,
top: containerWidget.style.top,
};
act(() => {
fireEvent.mouseOver(draggableContainerWidget);
});
act(() => {
fireEvent.dragStart(draggableContainerWidget);
});
const mainCanvas: any = component.queryByTestId("div-dragarena-0");
act(() => {
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mousemove", {
bubbles: true,
cancelable: true,
}),
{
offsetX: 100,
offsetY: 100,
},
),
);
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mouseup", {
bubbles: true,
cancelable: true,
}),
),
);
});
const movedContainerWidget: any = component.container.querySelector(
".t--widget-containerwidget",
);
const finalContainerWidgetPositions = {
left: movedContainerWidget.style.left,
top: movedContainerWidget.style.top,
};
expect(finalContainerWidgetPositions).not.toStrictEqual(
initContainerWidgetPosition,
);
});
it("nested widget drags when focused on", () => {
spyGetCanvasWidgetDsl.mockImplementation(mockGetCanvasWidgetDsl);
mockGetIsFetchingPage.mockImplementation(() => false);
const component = renderNestedComponent();
jest
.spyOn(uiSelectors, "getSelectedWidgets")
.mockReturnValue(["text-widget"]);
const textWidget: any = component.container.querySelector(
".t--widget-textwidget",
);
const draggableTextWidget: any = component.container.querySelector(
".t--draggable-textwidget",
);
const canvasWidgets = component.queryAllByTestId("test-widget");
expect(canvasWidgets.length).toBe(3);
const initTextWidgetPosition = {
left: textWidget.style.left,
top: textWidget.style.top,
};
act(() => {
fireEvent.mouseOver(draggableTextWidget);
});
act(() => {
fireEvent.dragStart(draggableTextWidget);
});
const mainCanvas: any = component.queryByTestId("div-dragarena-0");
act(() => {
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mousemove", {
bubbles: true,
cancelable: true,
}),
{
offsetX: 500,
offsetY: 500,
},
),
);
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mouseup", {
bubbles: true,
cancelable: true,
}),
),
);
});
const movedTextWidget: any = component.container.querySelector(
".t--widget-textwidget",
);
const finalTextWidgetPositions = {
left: movedTextWidget.style.left,
top: movedTextWidget.style.top,
};
expect(finalTextWidgetPositions).not.toStrictEqual(initTextWidgetPosition);
});
it("does not let disabledWidget drag and parent widget position stays same", () => {
spyGetCanvasWidgetDsl.mockImplementation(mockGetCanvasWidgetDsl);
mockGetIsFetchingPage.mockImplementation(() => false);
const component = renderNestedComponent();
const inputWidget: any = component.container.querySelector(
".t--widget-inputwidgetv2",
);
const draggableInputWidget: any = component.container.querySelector(
".t--draggable-inputwidgetv2",
);
const draggableContainerWidget: any = component.container.querySelector(
".t--draggable-containerwidget",
);
const containerWidget: any = component.container.querySelector(
".t--widget-containerwidget",
);
const initContainerWidgetPosition = {
left: containerWidget.style.left,
top: containerWidget.style.top,
};
const initInputWidgetPosition = {
left: inputWidget.style.left,
top: inputWidget.style.top,
};
const canvasWidgets = component.queryAllByTestId("test-widget");
expect(canvasWidgets.length).toBe(3);
act(() => {
fireEvent.mouseOver(draggableContainerWidget);
});
act(() => {
fireEvent.mouseOver(draggableInputWidget);
});
act(() => {
fireEvent.dragStart(draggableInputWidget);
});
const mainCanvas: any = component.queryByTestId("div-dragarena-0");
if (mainCanvas) {
act(() => {
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mousemove", {
bubbles: true,
cancelable: true,
}),
{
offsetX: 500,
offsetY: 500,
},
),
);
fireEvent(
mainCanvas,
syntheticTestMouseEvent(
new MouseEvent("mouseup", {
bubbles: true,
cancelable: true,
}),
),
);
});
}
const movedInputWidget: any = component.container.querySelector(
".t--widget-inputwidgetv2",
);
const finalInputWidgetPositions = {
left: movedInputWidget.style.left,
top: movedInputWidget.style.top,
};
const movedContainerWidget: any = component.container.querySelector(
".t--widget-containerwidget",
);
const finalContainerWidgetPositions = {
left: movedContainerWidget.style.left,
top: movedContainerWidget.style.top,
};
expect(finalInputWidgetPositions).toStrictEqual(initInputWidgetPosition);
expect(initContainerWidgetPosition).toStrictEqual(
finalContainerWidgetPositions,
);
});
afterAll(() => jest.resetModules());
});
|
766 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/IntegrationEditor | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/IntegrationEditor/__tests__/datasourceCard.test.tsx | import React from "react";
import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
import store from "store";
import { render } from "test/testUtils";
import DatasourceCard from "../DatasourceCard";
import { mockDatasources, mockPlugins } from "../mockData";
describe("Tasks", () => {
it("Checks to see if generate page button is hidden for unsupported plugins", () => {
store.dispatch({
type: ReduxActionTypes.FETCH_PLUGINS_SUCCESS,
payload: mockPlugins,
});
const generatePageComponent = render(
<DatasourceCard
// @ts-expect-error: Type mismatch
datasource={mockDatasources[0]}
// @ts-expect-error: Type mismatch
plugin={mockPlugins[0]}
/>,
);
expect(
generatePageComponent.container.querySelector(".t--generate-template"),
).toBeDefined();
const NoGeneratePageComponent = render(
<DatasourceCard
// @ts-expect-error: Type mismatch
datasource={mockDatasources[1]}
// @ts-expect-error: Type mismatch
plugin={mockPlugins[1]}
/>,
);
expect(
NoGeneratePageComponent.container.querySelector(".t--generate-template"),
).toBeNull();
});
});
|
777 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/JSEditor/utils.test.ts | import type { JSAction } from "entities/JSCollection";
import { uniqueId } from "lodash";
import { NO_FUNCTION_DROPDOWN_OPTION } from "./constants";
import {
convertJSActionToDropdownOption,
getJSActionOption,
getJSFunctionStartLineFromCode,
isCursorWithinNode,
} from "./utils";
const BASE_JS_OBJECT_BODY = `export default {
myVar1: [],
myVar2: {},
myFun1: () => {
//write code here
return FilePicker1
},
myFun2: async () => {
//use async-await or promises
await Api3.run()
await Api3.run()
return Api3.data
}
}`;
const BASE_JS_OBJECT_BODY_WITH_LITERALS = `export default {
myVar1: [],
myVar2: {},
["myFun1"]: () => {
//write code here
return FilePicker1
},
["myFun2"]: async () => {
//use async-await or promises
await Api3.run()
await Api3.run()
return Api3.data
}
}`;
const BASE_JS_ACTION = (useLiterals = false) => {
return {
workspaceId: "workspace-id",
pageId: "page-id",
collectionId: "collection-id",
pluginId: "plugin-id",
executeOnLoad: false,
dynamicBindingPathList: [],
isValid: false,
invalids: [],
jsonPathKeys: [],
cacheResponse: "",
confirmBeforeExecute: false,
messages: [],
clientSideExecution: false,
actionConfiguration: {
body: useLiterals
? BASE_JS_OBJECT_BODY_WITH_LITERALS
: BASE_JS_OBJECT_BODY,
isAsync: true,
timeoutInMillisecond: 1000,
jsArguments: [],
},
};
};
const createJSAction = (name: string, useLiterals = false): JSAction => {
return {
...BASE_JS_ACTION(useLiterals),
id: uniqueId(name),
name,
};
};
describe("getJSFunctionStartLineFromCode", () => {
it("returns null when cursor isn't within any function", () => {
const actualResponse = getJSFunctionStartLineFromCode(
BASE_JS_OBJECT_BODY,
100,
);
const expectedResponse = null;
expect(actualResponse).toStrictEqual(expectedResponse);
});
it("returns correct start line of function", () => {
const actualResponse1 = getJSFunctionStartLineFromCode(
BASE_JS_OBJECT_BODY,
4,
);
const actualResponse2 = getJSFunctionStartLineFromCode(
BASE_JS_OBJECT_BODY,
9,
);
const expectedStartLine1 = 3; // startLine of myFun1
const expectedStartLine2 = 7; // startLine of myFun2
expect(actualResponse1?.line).toStrictEqual(expectedStartLine1);
expect(actualResponse2?.line).toStrictEqual(expectedStartLine2);
});
it("returns correct start line of function when object keys are literals", () => {
const actualResponse1 = getJSFunctionStartLineFromCode(
BASE_JS_OBJECT_BODY_WITH_LITERALS,
4,
);
const actualResponse2 = getJSFunctionStartLineFromCode(
BASE_JS_OBJECT_BODY_WITH_LITERALS,
9,
);
const expectedStartLine1 = 3; // startLine of myFun1
const expectedStartLine2 = 7; // startLine of myFun2
expect(actualResponse1?.line).toStrictEqual(expectedStartLine1);
expect(actualResponse2?.line).toStrictEqual(expectedStartLine2);
});
it("isCursorWithinNode returns correct value", () => {
const cursorLineNumber = 2;
const testNodeLocation1 = {
start: { line: 1, column: 1, offset: 0 },
end: { line: 6, column: 1, offset: 0 },
};
const testNodeLocation2 = {
start: { line: 4, column: 1, offset: 0 },
end: { line: 6, column: 1, offset: 0 },
};
const actualResponse1 = isCursorWithinNode(
testNodeLocation1,
cursorLineNumber,
);
const actualResponse2 = isCursorWithinNode(
testNodeLocation2,
cursorLineNumber,
);
expect(actualResponse1).toBeTruthy();
expect(actualResponse2).toBeFalsy();
});
});
describe("jsAction dropdown", () => {
const jsActions = [
createJSAction("myFun1"),
createJSAction("myFun2"),
createJSAction("myFun3"),
];
it("getJSActionOption returns active JS Action on priority", () => {
const activeJSAction = jsActions[0];
const actualResponse = getJSActionOption(activeJSAction, jsActions);
const expectedResponse = convertJSActionToDropdownOption(activeJSAction);
expect(actualResponse).toEqual(expectedResponse);
});
it("getJSActionOption returns default option when there is no jsAction present", () => {
const activeJSAction = null;
const actualResponse = getJSActionOption(activeJSAction, []);
const expectedResponse = NO_FUNCTION_DROPDOWN_OPTION;
expect(actualResponse).toEqual(expectedResponse);
});
});
|
792 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/PropertyPane/PropertyPaneTitle.test.tsx | import React from "react";
import "@testing-library/jest-dom";
import { ThemeProvider } from "styled-components";
import { render } from "@testing-library/react";
import PropertyPaneTitle from "./PropertyPaneTitle";
import userEvent from "@testing-library/user-event";
import { lightTheme } from "selectors/themeSelectors";
import { Provider } from "react-redux";
import store from "store";
describe("<PropertyPaneTitle />", () => {
it("should focus when f2 is pressed", async () => {
const getTestComponent = () => (
<Provider store={store}>
<ThemeProvider theme={lightTheme}>
<PropertyPaneTitle actions={[]} isPanelTitle title="" widgetId="1" />
</ThemeProvider>
</Provider>
);
const component = getTestComponent();
const renderResult = render(component);
await userEvent.keyboard("{F2}");
expect(renderResult.container.querySelector("input")).toBeVisible();
});
});
|
798 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/PropertyPane/propertyPaneSearch.test.ts | import type { PropertyPaneSectionConfig } from "constants/PropertyControlConstants";
import { searchPropertyPaneConfig } from "./propertyPaneSearch";
describe("Property configuration search", () => {
const commonProperties = {
controlType: "CONTROL_TYPE",
isBindProperty: false,
isTriggerProperty: false,
};
const config: PropertyPaneSectionConfig[] = [
{
sectionName: "Section One",
children: [
{
label: "Disable Invalid Forms",
propertyName: "disabledWhenInvalid",
...commonProperties,
},
{
label: "Scroll contents",
propertyName: "scrollContents",
...commonProperties,
},
{
label: "Show reset",
propertyName: "showReset",
...commonProperties,
},
{
label: "Visible",
propertyName: "isVisible",
...commonProperties,
},
{
label: "Animate loading",
propertyName: "animateLoading",
...commonProperties,
},
{
label: "Submit button label",
propertyName: "submitButtonLabel",
...commonProperties,
},
{
label: "Reset button label",
invisible: true,
propertyName: "resetButtonLabel",
...commonProperties,
},
],
},
{
sectionName: "Section Two",
children: [
{
label: "Button color",
propertyName: "buttonColor",
...commonProperties,
},
{
label: "Button variant",
propertyName: "buttonVariant",
...commonProperties,
},
{
sectionName: "Icon",
children: [
{
label: "Icon",
propertyName: "icon",
...commonProperties,
},
{
label: "Placement",
propertyName: "placement",
...commonProperties,
},
{
label: "Icon Align",
propertyName: "iconAlign",
...commonProperties,
},
],
},
],
},
{
sectionName: "Another Button Section",
children: [
{
label: "Google reCAPTCHA key",
propertyName: "recaptchaKey",
...commonProperties,
},
],
},
{
sectionName: "Button Section",
children: [
{
label: "onClick",
propertyName: "onClick",
...commonProperties,
},
],
},
{
sectionName: "Special Char Section",
children: [
{
label: "Star *",
propertyName: "star",
...commonProperties,
},
{
label: "Plus +",
propertyName: "plus",
...commonProperties,
},
],
},
{
sectionName: "Special Char (/) Section 2",
children: [
{
label: "test",
propertyName: "test",
...commonProperties,
},
],
},
];
it("Should return configuration as it is for empty searchQuery", () => {
const result = searchPropertyPaneConfig(config, "");
expect(result).toEqual(config);
});
it("Should return empty array if the searchQuery didn't match any property or section", () => {
const result = searchPropertyPaneConfig(config, "blablabla");
expect(result).toEqual([]);
});
it("Validates search for a property", () => {
const result = searchPropertyPaneConfig(config, "animate");
expect(result).toEqual([
{
sectionName: "Section One",
children: [
{
label: "Animate loading",
propertyName: "animateLoading",
...commonProperties,
},
],
},
]);
});
it("Validates search for a section", () => {
const result = searchPropertyPaneConfig(config, "Section One");
expect(result).toEqual(config.slice(0, 1));
});
it("Validates search order for multiple matching items from multiple sections", () => {
const result = searchPropertyPaneConfig(config, "button");
expect(result).toEqual([
{
sectionName: "Button Section",
children: [
{
label: "onClick",
propertyName: "onClick",
...commonProperties,
},
],
},
{
sectionName: "Section Two",
children: [
{
label: "Button color",
propertyName: "buttonColor",
...commonProperties,
},
{
label: "Button variant",
propertyName: "buttonVariant",
...commonProperties,
},
],
},
{
sectionName: "Another Button Section",
children: [
{
label: "Google reCAPTCHA key",
propertyName: "recaptchaKey",
...commonProperties,
},
],
},
{
sectionName: "Section One",
children: [
{
label: "Submit button label",
propertyName: "submitButtonLabel",
...commonProperties,
},
],
},
]);
});
it("Validates search for a nested property", () => {
const result = searchPropertyPaneConfig(config, "placement");
expect(result).toEqual([
{
sectionName: "Section Two",
children: [
{
sectionName: "Icon",
children: [
{
label: "Placement",
propertyName: "placement",
...commonProperties,
},
],
},
],
},
]);
});
it("Validates search for a nested section", () => {
const result = searchPropertyPaneConfig(config, "Icon");
expect(result).toEqual([
{
sectionName: "Section Two",
children: [
{
sectionName: "Icon",
children: [
{
label: "Icon",
propertyName: "icon",
...commonProperties,
},
{
label: "Placement",
propertyName: "placement",
...commonProperties,
},
{
label: "Icon Align",
propertyName: "iconAlign",
...commonProperties,
},
],
},
],
},
]);
});
it("Validates search for camel Case property", () => {
const expectedResult = [
{
sectionName: "Button Section",
children: [
{
label: "onClick",
propertyName: "onClick",
...commonProperties,
},
],
},
];
let actualResult = searchPropertyPaneConfig(config, "click");
expect(actualResult).toEqual(expectedResult);
actualResult = searchPropertyPaneConfig(config, "onClick");
expect(actualResult).toEqual(expectedResult);
actualResult = searchPropertyPaneConfig(config, "on click");
expect(actualResult).toEqual(expectedResult);
});
it("Validates search for camel Case property - Test 2", () => {
const expectedResult = [
{
sectionName: "Another Button Section",
children: [
{
label: "Google reCAPTCHA key",
propertyName: "recaptchaKey",
...commonProperties,
},
],
},
];
let actualResult = searchPropertyPaneConfig(config, "captcha");
expect(actualResult).toEqual(expectedResult);
actualResult = searchPropertyPaneConfig(config, "reCaptcha");
expect(actualResult).toEqual(expectedResult);
});
it("Shouldn't search for properties with invisible flag set", () => {
const result = searchPropertyPaneConfig(config, "Reset button label");
expect(result).toEqual([]);
});
it("Validates token based match and not substring match", () => {
// If it was string match, "valid" should've matched "Disable Invalid Forms"
let result = searchPropertyPaneConfig(config, "valid");
expect(result).toEqual([]);
// If it was string match, "able" should've matched "Disable Invalid Forms"
result = searchPropertyPaneConfig(config, "able");
expect(result).toEqual([]);
result = searchPropertyPaneConfig(config, "Disable Forms");
expect(result).toEqual([]);
const disableInvalidFormsConfig = [
{
sectionName: "Section One",
children: [
{
label: "Disable Invalid Forms",
propertyName: "disabledWhenInvalid",
...commonProperties,
},
],
},
];
result = searchPropertyPaneConfig(config, "Disa");
expect(result).toEqual(disableInvalidFormsConfig);
result = searchPropertyPaneConfig(config, "Disable In");
expect(result).toEqual(disableInvalidFormsConfig);
result = searchPropertyPaneConfig(config, "Invalid For");
expect(result).toEqual(disableInvalidFormsConfig);
result = searchPropertyPaneConfig(config, "Invalid Forms");
expect(result).toEqual(disableInvalidFormsConfig);
});
it("Ensure special characters doesn't throw errors", () => {
expect(() => {
searchPropertyPaneConfig(config, "*");
}).not.toThrowError();
});
});
|
837 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/__tests__/AuthenticatedAPIErrorValidation.test.tsx | import React from "react";
import "@testing-library/jest-dom";
import { render, screen } from "test/testUtils";
import userEvent from "@testing-library/user-event";
import FormControl from "../FormControl";
import { createMessage, INVALID_URL } from "@appsmith/constants/messages";
import FormControlRegistry from "utils/formControl/FormControlRegistry";
import { reduxForm } from "redux-form";
let container: any = null;
const urlValidator = (value: string) => {
const validationRegex = "^(http|https)://";
if (value) {
const regex = new RegExp(validationRegex);
return regex.test(value)
? { isValid: true, message: "" }
: {
isValid: false,
message: createMessage(INVALID_URL),
};
}
return { isValid: true, message: "" };
};
function renderComponent() {
function formControlComponent() {
return (
<FormControl
config={{
id: "",
isValid: false,
isRequired: true,
controlType: "INPUT_TEXT",
dataType: "TEXT",
configProperty: "authentication.accessTokenUrl",
encrypted: false,
label: "Access token URL",
conditionals: {},
placeholderText: "https://example.com/login/oauth/access_token",
formName: "DatasourceRestAPIForm",
validator: urlValidator,
}}
formName="DatasourceRestAPIForm"
multipleConfig={[]}
/>
);
}
const Parent = reduxForm<any, any>({
validate: () => {
return {};
},
form: "DatasourceRestAPIForm",
touchOnBlur: true,
})(formControlComponent);
render(<Parent />);
}
describe("Authenticated API URL validations", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
FormControlRegistry.registerFormControlBuilders();
});
it("enter invalid token url and check for errors", async () => {
renderComponent();
const inputFormControl = document.querySelectorAll(
".t--form-control-INPUT_TEXT",
);
expect(inputFormControl.length).toBe(1);
const inputBox = inputFormControl[0].querySelectorAll("input");
expect(inputBox.length).toBe(1);
await userEvent.type(inputBox[0], "test value");
expect(inputBox[0]).toHaveValue("test value");
const errorText = screen.getAllByText(
"Please enter a valid URL, for example, https://example.com",
);
expect(errorText).toBeDefined();
});
it("enter valid token url and check for errors", async () => {
renderComponent();
const inputFormControl = document.querySelectorAll(
".t--form-control-INPUT_TEXT",
);
expect(inputFormControl.length).toBe(1);
const inputBox = inputFormControl[0].querySelectorAll("input");
expect(inputBox.length).toBe(1);
await userEvent.type(inputBox[0], "https://example.com");
expect(inputBox[0]).toHaveValue("https://example.com");
const errorText = screen.queryAllByText(
"Please enter a valid URL, for example, https://example.com",
);
expect(errorText.length).toBe(0);
});
});
|
838 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/__tests__/QueryEditorTable.test.tsx | import React from "react";
import { render, screen } from "test/testUtils";
import "@testing-library/jest-dom";
import Table from "../QueryEditor/Table";
import { getScrollBarWidth } from "../QueryEditor/Table";
function createEle() {
return {
scrollHeight: 0,
clientHeight: 0,
};
}
const scrollW = 6;
const reponsePaneHeight = 307;
const tableData = [
{ "": "Jan 1 1970 10:15AM" },
{ "": "Jan 2 1970 10:15AM" },
{ "": "Jan 3 1970 10:15AM" },
{ "": "Jan 4 1970 10:15AM" },
{ "": "Jan 5 1970 10:15AM" },
{ "": "Jan 1 1970 10:15AM" },
{ "": "Jan 2 1970 10:15AM" },
{ "": "Jan 3 1970 10:15AM" },
{ "": "Jan 4 1970 10:15AM" },
{ "": "Jan 5 1970 10:15AM" },
];
describe("Query Editor Table", () => {
it("it should render table with missing key", () => {
render(<Table data={[{ "": "Jan 1 1970 10:15AM" }]} />);
const date = screen.getByText(/Jan 1 1970 10:15AM/i);
expect(date).toBeInTheDocument();
});
it("13406: it should return scroll bar width 0 when table element is not defined", () => {
const ele = undefined;
const scrollWidth = getScrollBarWidth(ele, scrollW);
expect(scrollWidth).toBe(0);
});
it("13406: it should render table without scroll and scroll bar width would be 0", () => {
const ele = createEle();
ele.scrollHeight = 268;
ele.clientHeight = 268;
const scrollWidth = getScrollBarWidth(ele, scrollW);
expect(scrollWidth).toBe(0);
});
it("13406: it should render table with scroll and scroll bar width would be greater than 0", () => {
const ele = createEle();
ele.scrollHeight = 368;
ele.clientHeight = 268;
const scrollWidth = getScrollBarWidth(ele, scrollW);
expect(scrollWidth).toBeGreaterThan(0);
});
it("17653: Scroll bar in table doesnt appear", () => {
render(<Table data={tableData} tableBodyHeight={reponsePaneHeight} />);
const tbodyEle = document.querySelectorAll(".tbody > div");
expect(tbodyEle[0]).toHaveStyle("height: 171px");
});
});
|
850 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync/utils.test.ts | import {
changeInfoSinceLastCommit,
getIsStartingWithRemoteBranches,
isLocalBranch,
isRemoteBranch,
isValidGitRemoteUrl,
removeSpecialChars,
} from "./utils";
import { ApplicationVersion } from "@appsmith/actions/applicationActions";
const validUrls = [
"[email protected]:user/project.git",
"git://a@b:c/d.git",
"[email protected]:user/project.git",
"ssh://[email protected]:port/path/to/repo.git",
"ssh://[email protected]/path/to/repo.git",
"ssh://host.xz:port/path/to/repo.git",
"ssh://host.xz/path/to/repo.git",
"ssh://[email protected]/path/to/repo.git",
"ssh://host.xz/path/to/repo.git",
"ssh://[email protected]/~user/path/to/repo.git",
"ssh://host.xz/~user/path/to/repo.git",
"ssh://[email protected]/~/path/to/repo.git",
"ssh://host.xz/~/path/to/repo.git",
"[email protected]:v3/something/other/thing",
"[email protected]:v3/something/other/thing.git",
"[email protected]:v3/something/other/(thing).git",
"[email protected]:v3/(((something)/(other)/(thing).git",
"[email protected]:org__v3/(((something)/(other)/(thing).git",
"[email protected]:org__org/repoName.git",
"git@gitlab__abcd.test.org:org__org/repoName.git",
];
const invalidUrls = [
"[email protected].(com):v3/(((something)/(other)/(thing).git",
"[email protected]:v3/something/other/thing/",
"gitclonegit://a@b:c/d.git",
"https://github.com/user/project.git",
"http://github.com/user/project.git",
"https://192.168.101.127/user/project.git",
"http://192.168.101.127/user/project.git",
"ssh://[email protected]:port/path/to/repo.git/",
"ssh://[email protected]/path/to/repo.git/",
"ssh://host.xz:port/path/to/repo.git/",
"ssh://host.xz/path/to/repo.git/",
"ssh://[email protected]/path/to/repo.git/",
"ssh://host.xz/path/to/repo.git/",
"ssh://[email protected]/~user/path/to/repo.git/",
"ssh://host.xz/~user/path/to/repo.git/",
"git://host.xz/path/to/repo.git/",
"git://host.xz/~user/path/to/repo.git/",
"http://host.xz/path/to/repo.git/",
"https://host.xz/path/to/repo.git/",
"/path/to/repo.git/",
"path/to/repo.git/",
"~/path/to/repo.git",
"file:///path/to/repo.git/",
"file://~/path/to/repo.git/",
"[email protected]:/path/to/repo.git/",
"host.xz:/path/to/repo.git/",
"[email protected]:~user/path/to/repo.git/",
"host.xz:~user/path/to/repo.git/",
"[email protected]:path/to/repo.git",
"host.xz:path/to/repo.git",
"rsync://host.xz/path/to/repo.git/",
];
describe("gitSync utils", () => {
describe("getIsStartingWithRemoteBranches", function () {
it("returns true when only remote starts with origin/", () => {
const actual = getIsStartingWithRemoteBranches(
"whatever",
"origin/whateverelse",
);
const expected = true;
expect(actual).toEqual(expected);
});
it("returns false if param:local starts with origin/", () => {
const actual = getIsStartingWithRemoteBranches(
"origin/a",
"origin/whateverelse",
);
const expected = false;
expect(actual).toEqual(expected);
});
it("returns empty string if param:local is empty string", () => {
const actual = getIsStartingWithRemoteBranches("a", "");
const expected = "";
expect(actual).toEqual(expected);
});
it("returns empty string if param:remote is empty string", () => {
const actual = getIsStartingWithRemoteBranches("", "");
const expected = "";
expect(actual).toEqual(expected);
});
});
describe("isValidGitRemoteUrl returns true for valid urls", () => {
validUrls.forEach((validUrl: string) => {
it(`${validUrl} is a valid git remote URL`, () => {
const actual = isValidGitRemoteUrl(validUrl);
const expected = true;
expect(actual).toEqual(expected);
});
});
});
describe("isValidGitRemoteUrl returns false for invalid urls", () => {
invalidUrls.forEach((invalidUrl: string) => {
it(`${invalidUrl} is a valid git remote URL`, () => {
const actual = isValidGitRemoteUrl(invalidUrl);
const expected = false;
expect(actual).toEqual(expected);
});
});
});
describe("isRemoteBranch", () => {
it("returns true for branches that start with origin/", () => {
const branches = ["origin/", "origin/_", "origin/a", "origin/origin"];
const actual = branches.every(isRemoteBranch);
const expected = true;
expect(actual).toEqual(expected);
});
it("returns false for branches that don't start with origin/", () => {
const branches = [
"origin",
"original/",
"oriign/_",
"main/",
"upstream/origin",
"develop/",
"release/",
"master/",
];
const actual = branches.every(isRemoteBranch);
const expected = false;
expect(actual).toEqual(expected);
});
});
describe("isLocalBranch", () => {
it("returns false for branches that start with origin/", () => {
const branches = ["origin/", "origin/_", "origin/a", "origin/origin"];
const actual = branches.every(isLocalBranch);
const expected = false;
expect(actual).toEqual(expected);
});
it("returns true for branches that don't start with origin/", () => {
const branches = [
"origin",
"original/",
"oriign/_",
"main/",
"upstream/origin",
"develop/",
"release/",
"master/",
];
const actual = branches.every(isLocalBranch);
const expected = true;
expect(actual).toEqual(expected);
});
});
describe("removeSpecialCharacters", () => {
it("replaces special characters except / and - with _", () => {
const inputs = [
"abc_def",
"abc-def",
"abc*def",
"abc/def",
"abc&def",
"abc%def",
"abc#def",
"abc@def",
"abc!def",
"abc,def",
"abc<def",
"abc>def",
"abc?def",
"abc.def",
"abc;def",
"abc(def",
];
const expected = [
"abc_def",
"abc-def",
"abc_def",
"abc/def",
"abc_def",
"abc_def",
"abc_def",
"abc_def",
"abc_def",
"abc_def",
"abc_def",
"abc_def",
"abc_def",
"abc_def",
"abc_def",
"abc_def",
];
inputs.forEach((input, index) => {
const result = removeSpecialChars(input);
expect(result).toStrictEqual(expected[index]);
});
});
});
describe("changeInfoSinceLastCommit", () => {
it("returns default data", () => {
const applicationData = {
appIsExample: false,
applicationVersion: ApplicationVersion.DEFAULT,
defaultPageId: "",
slug: "",
id: "",
isAutoUpdate: false,
isManualUpdate: false,
name: "",
workspaceId: "",
pages: [],
};
const actual = changeInfoSinceLastCommit(applicationData);
const expected = {
changeReasonText: "Changes since last deployment",
isAutoUpdate: false,
isManualUpdate: false,
};
expect(actual).toEqual(expected);
});
it("returns migration change only data", () => {
const applicationData = {
appIsExample: false,
applicationVersion: ApplicationVersion.DEFAULT,
defaultPageId: "",
id: "",
slug: "",
isAutoUpdate: true,
isManualUpdate: false,
name: "",
workspaceId: "",
pages: [],
};
const actual = changeInfoSinceLastCommit(applicationData);
const expected = {
changeReasonText: "Changes since last deployment",
isAutoUpdate: true,
isManualUpdate: false,
};
expect(actual).toEqual(expected);
});
it("returns migration and user change data", () => {
const applicationData = {
appIsExample: false,
applicationVersion: ApplicationVersion.DEFAULT,
defaultPageId: "",
id: "",
slug: "",
isAutoUpdate: true,
isManualUpdate: true,
name: "",
workspaceId: "",
pages: [],
};
const actual = changeInfoSinceLastCommit(applicationData);
const expected = {
changeReasonText: "Changes since last deployment",
isAutoUpdate: true,
isManualUpdate: true,
};
expect(actual).toEqual(expected);
});
it("returns user changes only data", () => {
const applicationData = {
appIsExample: false,
applicationVersion: ApplicationVersion.DEFAULT,
defaultPageId: "",
id: "",
slug: "",
isAutoUpdate: false,
isManualUpdate: true,
name: "",
workspaceId: "",
pages: [],
};
const actual = changeInfoSinceLastCommit(applicationData);
const expected = {
changeReasonText: "Changes since last deployment",
isAutoUpdate: false,
isManualUpdate: true,
};
expect(actual).toEqual(expected);
});
});
});
|
855 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync/QuickGitActions/BranchButton.test.tsx | import { render, screen } from "test/testUtils";
import BranchButton from "./BranchButton";
import React from "react";
describe("BranchButton", () => {
it("renders properly", async () => {
render(<BranchButton />);
const currentBranch = await screen.queryByTestId(
"t--branch-button-currentBranch",
);
expect(currentBranch?.innerHTML).toContain("*");
});
});
|
874 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync/Tabs | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync/Tabs/GitSettings/index.test.tsx | /* eslint-disable jest/no-focused-tests */
import React from "react";
import { render, screen } from "test/testUtils";
import GitSettings from ".";
import type { AppState } from "@appsmith/reducers";
jest.mock("../../hooks/useIsGitAdmin", () => ({
useIsGitAdmin: () => false,
}));
describe("GitSettings test for git admin disabled", () => {
it("Branch protection, default branch and disconnect disabled when not ", () => {
const initialState: Partial<AppState> = {};
render(<GitSettings />, { initialState });
expect(screen.queryByTestId("t--git-protected-branches-select")).toBe(null);
expect(screen.queryByTestId("t--git-default-branch-select")).toBe(null);
expect(screen.queryByTestId("t--git-disconnect-btn")).toBe(null);
});
});
|
876 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync/Tabs | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync/Tabs/__tests__/Deploy.test.tsx | import React from "react";
import { Provider } from "react-redux";
import store from "store";
import { ThemeProvider } from "styled-components";
import { lightTheme } from "selectors/themeSelectors";
import { render } from "test/testUtils";
import Deploy from "../Deploy";
import {
commitToRepoInit,
fetchGitStatusSuccess,
} from "actions/gitSyncActions";
import { COMMITTING_AND_PUSHING_CHANGES } from "@appsmith/constants/messages";
describe("Tests for git deploy modal", () => {
it("Should show progress bar for JS Library diffs", () => {
const component = render(
<Provider store={store}>
<ThemeProvider theme={lightTheme}>
<Deploy />
</ThemeProvider>
</Provider>,
);
store.dispatch(
fetchGitStatusSuccess({
modified: [
"jslibs/UUID_https:[email protected]_src_uuid.min.js.json",
"application.json",
],
conflicting: [],
isClean: false,
modifiedJSLibs: 1,
modifiedPages: 0,
modifiedQueries: 0,
modifiedJSObjects: 0,
modifiedDatasources: 0,
aheadCount: 0,
behindCount: 0,
remoteBranch: "refs/remotes/origin/master",
discardDocUrl:
"https://docs.appsmith.com/core-concepts/version-control-with-git/pull-and-sync#discard-and-pull-changes",
}),
);
const diffText = component.getByText("1 library modified");
expect(diffText).toBeDefined();
store.dispatch(
commitToRepoInit({
commitMessage: "test",
doPush: false,
}),
);
const progressBar = component.getByText(COMMITTING_AND_PUSHING_CHANGES());
expect(progressBar).toBeDefined();
});
});
|
877 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync/components/BetaTag.test.tsx | import BetaTag from "./BetaTag";
import { render, screen } from "test/testUtils";
import React from "react";
import "jest-styled-components";
describe("BetaTag", () => {
it("renders properly", async () => {
render(<BetaTag />);
const actual = await screen.queryByTestId("t--beta-tag");
// renders
expect(actual).not.toBeNull();
// contains BETA text
expect(actual?.innerHTML.includes("BETA")).toBeTruthy();
// styles
expect(actual).toHaveStyleRule("height", "16px");
expect(actual).toHaveStyleRule("width", "48px");
expect(actual).toHaveStyleRule("display", "flex");
expect(actual).toHaveStyleRule("justify-content", "center");
expect(actual).toHaveStyleRule("align-items", "center");
expect(actual).toHaveStyleRule("color", "#191919");
expect(actual).toHaveStyleRule("border", "1px solid #191919");
});
});
|
884 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync/components/ConflictInfo.test.tsx | import ConflictInfo from "./ConflictInfo";
import { render, screen } from "test/testUtils";
import React from "react";
describe("ConflictInfo", () => {
it("renders properly", async () => {
render(
<ConflictInfo
browserSupportedRemoteUrl={"href"}
learnMoreLink={"link"}
/>,
);
// check for existence
[
await screen.queryByTestId("t--conflict-info-container"),
await screen.queryByTestId("t--conflict-info-error-warning"),
].every((query) => {
expect(query).not.toBeNull();
return true;
});
//check for text
const container = await screen.getByTestId("t--conflict-info-container");
const html = container.innerHTML.toString();
expect(html.includes("Learn more")).toBeTruthy();
expect(html.includes("Open repository")).toBeTruthy();
expect(
html.includes(
"Please resolve the merge conflicts manually on your repository.",
),
).toBeTruthy();
});
});
|
890 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync/components/DefaultTag.test.tsx | import DefaultTag from "./DefaultTag";
import { render, screen } from "test/testUtils";
import React from "react";
import "jest-styled-components";
describe("DefaultTag", () => {
it("renders properly", async () => {
render(<DefaultTag />);
const actual = await screen.queryByTestId("t--default-tag");
// renders
expect(actual).not.toBeNull();
// contains Default text
expect(actual?.innerHTML.includes("Default")).toBeTruthy();
});
});
|
895 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync/components/GitChangesList.test.tsx | import type { GitStatusData } from "reducers/uiReducers/gitSyncReducer";
import { gitChangeListData } from "./GitChangesList";
describe("GitChangesList", () => {
describe("gitChangesListData", () => {
it("returns proper data", () => {
const status: GitStatusData = {
conflicting: [],
aheadCount: 1,
behindCount: 1,
isClean: false,
modified: [],
modifiedPages: 1,
modifiedQueries: 1,
remoteBranch: "string",
modifiedJSObjects: 1,
modifiedDatasources: 1,
modifiedJSLibs: 1,
discardDocUrl: "string",
};
const actual = gitChangeListData(status);
expect(Array.isArray(actual)).toBeTruthy();
const actualJSON = JSON.stringify(actual);
expect(actualJSON.length).toBeGreaterThan(0);
const expectedJSON =
'[{"key":"change-status-widget","ref":null,"props":{"message":"1 page modified","iconName":"widget","hasValue":true},"_owner":null,"_store":{}},{"key":"change-status-query","ref":null,"props":{"message":"1 query modified","iconName":"query","hasValue":true},"_owner":null,"_store":{}},{"key":"change-status-js","ref":null,"props":{"message":"1 JS Object modified","iconName":"js","hasValue":true},"_owner":null,"_store":{}},{"key":"change-status-database-2-line","ref":null,"props":{"message":"1 datasource modified","iconName":"database-2-line","hasValue":true},"_owner":null,"_store":{}},{"key":"change-status-package","ref":null,"props":{"message":"1 library modified","iconName":"package","hasValue":true},"_owner":null,"_store":{}}]';
expect(actualJSON).toEqual(expectedJSON);
});
it("returns empty array", () => {
const actual = gitChangeListData();
const expected: JSX.Element[] = [];
expect(actual).toEqual(expected);
});
});
});
|
900 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync/components/LocalBranchList.test.tsx | import { render, screen } from "test/testUtils";
import "jest-styled-components";
import { LocalBranchList } from "./LocalBranchList";
describe("LocalBranchList", function () {
it("renders nothing when param:remoteBranches is an empty array", async () => {
render(LocalBranchList([], "", false, -1, "", () => undefined));
const renderedList = screen.queryByTestId(
"t--git-local-branch-list-container",
);
expect(renderedList?.innerHTML).toBeFalsy();
});
});
|
906 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync | petrpan-code/appsmithorg/appsmith/app/client/src/pages/Editor/gitSync/components/RemoteBranchList.test.tsx | import { render, screen } from "test/testUtils";
import "jest-styled-components";
import { RemoteBranchList } from "./RemoteBranchList";
describe("RemoteBranchList", function () {
it("renders nothing when param:remoteBranches is an empty array", async () => {
render(RemoteBranchList([], () => undefined));
const renderedList = await screen.queryByTestId(
"t--git-remote-branch-list-container",
);
expect(renderedList?.innerHTML).toBeFalsy();
});
it("renders one branch list item when param:remoteBranches contains only one string", async () => {
render(RemoteBranchList(["origin/one"], () => undefined));
const renderedList = screen.queryByTestId(
"t--git-remote-branch-list-container",
);
expect(renderedList).not.toBeNull();
expect(renderedList?.innerHTML.includes("Remote branches")).toBeTruthy();
expect(renderedList?.children.length).toEqual(2);
// contains styled segment header
const header = await screen.queryByTestId("t--branch-list-header-local");
expect(header).not.toBeNull();
expect(header?.innerHTML.includes("Remote branches")).toBeTruthy();
});
});
|
1,013 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages | petrpan-code/appsmithorg/appsmith/app/client/src/pages/setup/SetupForm.test.tsx | import { fireEvent, render, screen } from "test/testUtils";
import React from "react";
import "@testing-library/jest-dom";
import SetupForm from "./SetupForm";
import userEvent from "@testing-library/user-event";
function renderComponent() {
return render(<SetupForm />);
}
describe("SetupForm", () => {
it("If the form is in invalid state pressing enter should not submit the form", () => {
renderComponent();
const verifyPassword = screen.getByTestId("verifyPassword");
const formPage = screen.getByTestId("formPage");
expect(verifyPassword).toHaveAttribute("name");
userEvent.keyboard("{enter}");
// This attribute is removed in onsubmit
expect(verifyPassword).toHaveAttribute("name");
expect(formPage).toHaveClass("block");
});
it("If the form is in valid state pressing enter should nagivate to next page", () => {
renderComponent();
const formPage = screen.getByTestId("formPage");
expect(formPage).toHaveClass("block");
const firstName = screen.getByTestId("firstName");
fireEvent.change(firstName, { target: { value: "John" } });
const lastName = screen.getByTestId("lastName");
fireEvent.change(lastName, { target: { value: "Doe" } });
const email = screen.getByTestId("email");
fireEvent.change(email, { target: { value: "[email protected]" } });
const password = screen.getByTestId("password");
fireEvent.change(password, { target: { value: "Test@123" } });
const verifyPassword = screen.getByTestId("verifyPassword");
fireEvent.change(verifyPassword, { target: { value: "Test@123" } });
userEvent.keyboard("{enter}");
expect(formPage).toHaveClass("hidden");
});
});
|
1,015 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages | petrpan-code/appsmithorg/appsmith/app/client/src/pages/setup/SignupSuccess.test.tsx | import { render, screen } from "test/testUtils";
import React from "react";
import "@testing-library/jest-dom";
import { SignupSuccess } from "./SignupSuccess";
const useSelector = jest.fn();
const values = {
isSuperUser: true,
};
useSelector.mockReturnValue(values);
function renderComponent() {
return render(<SignupSuccess />);
}
describe("SignupSuccess", () => {
it("If we are intending to redirect do not show the signup form", () => {
renderComponent();
expect(screen.queryByTestId("welcome-page")).toBeNull();
});
});
|
1,023 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages | petrpan-code/appsmithorg/appsmith/app/client/src/pages/tests/slug.test.tsx | import React from "react";
import { ApplicationVersion } from "@appsmith/actions/applicationActions";
import { builderURL } from "@appsmith/RouteBuilder";
import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
import { selectURLSlugs } from "selectors/editorSelectors";
import store from "store";
import { render } from "test/testUtils";
import {
getUpdatedRoute,
isURLDeprecated,
matchPath_BuilderCustomSlug,
matchPath_ViewerSlug,
} from "utils/helpers";
import {
fetchApplicationMockResponse,
setMockApplication,
setMockPageList,
updatedApplicationPayload,
updatedPagePayload,
} from "./mockData";
import ManualUpgrades from "components/BottomBar/ManualUpgrades";
import { updateCurrentPage } from "actions/pageActions";
import urlBuilder from "@appsmith/entities/URLRedirect/URLAssembly";
import { Button } from "design-system";
describe("URL slug names", () => {
beforeEach(async () => {
setMockApplication();
setMockPageList();
store.dispatch({
type: ReduxActionTypes.SWITCH_CURRENT_PAGE_ID,
payload: { id: "605c435a91dea93f0eaf91ba", slug: "page-1" },
});
});
it("verifies right slug names from slugs selector", () => {
const state = store.getState();
const { applicationSlug, pageSlug } = selectURLSlugs(state);
expect(applicationSlug).toBe("my-application");
expect(pageSlug).toBe("page-1");
});
it("checks the update slug in URL method", () => {
const newAppSlug = "modified-app-slug";
const newPageSlug = "modified-page-slug";
const customSlug = "custom-slug";
const pathname = "/app/my-app/pages-605c435a91dea93f0eaf91ba";
const url1 = getUpdatedRoute(pathname, {
applicationSlug: newAppSlug,
pageSlug: newPageSlug,
});
expect(url1).toBe(
`/app/${newAppSlug}/${newPageSlug}-605c435a91dea93f0eaf91ba`,
);
const url2 = getUpdatedRoute(pathname, {
applicationSlug: newAppSlug,
pageSlug: newPageSlug,
customSlug,
});
expect(url2).toBe(`/app/${customSlug}-605c435a91dea93f0eaf91ba`);
});
it("checks the isDeprecatedURL method", () => {
const pathname1 =
"/applications/605c435a91dea93f0eaf91ba/pages/605c435a91dea93f0eaf91ba/edit";
const pathname2 =
"/applications/605c435a91dea93f0eaf91ba/pages/605c435a91dea93f0eaf91ba";
expect(isURLDeprecated(pathname1)).toBe(true);
expect(isURLDeprecated(pathname2)).toBe(true);
const pathname3 = "/app/apSlug/pages-605c435a91dea93f0eaf91ba";
expect(isURLDeprecated(pathname3)).toBe(false);
const pathname4 = "/app/customSlug-605c435a91dea93f0eaf91ba";
expect(isURLDeprecated(pathname4)).toBe(false);
});
it("verifies that the baseURLBuilder uses applicationVersion", () => {
const params = {
applicationId: "appId",
applicationSlug: "appSlug",
pageId: "pageId",
pageSlug: "pageSlug",
customSlug: "customSlug",
};
urlBuilder.updateURLParams(
{
applicationVersion: ApplicationVersion.DEFAULT,
applicationSlug: params.applicationSlug,
applicationId: params.applicationId,
},
[
{
pageId: params.pageId,
pageSlug: params.pageSlug,
},
],
);
const url1 = builderURL({ pageId: params.pageId });
urlBuilder.updateURLParams({
applicationVersion: ApplicationVersion.SLUG_URL,
});
const url2 = builderURL({ pageId: params.pageId });
store.dispatch({
type: ReduxActionTypes.UPDATE_APPLICATION_SUCCESS,
payload: { applicationVersion: ApplicationVersion.DEFAULT },
});
const url3 = builderURL({ pageId: params.pageId });
store.dispatch({
type: ReduxActionTypes.UPDATE_APPLICATION_SUCCESS,
payload: { applicationVersion: ApplicationVersion.SLUG_URL },
});
const url4 = builderURL({ pageId: params.pageId });
expect(url1).toBe("/applications/appId/pages/pageId/edit");
expect(url2).toBe("/app/appSlug/pageSlug-pageId/edit");
expect(url3).toBe("/applications/appId/pages/pageId/edit");
expect(url4).toBe("/app/appSlug/pageSlug-pageId/edit");
});
it("tests the manual upgrade option", () => {
store.dispatch({
type: ReduxActionTypes.FETCH_APPLICATION_SUCCESS,
payload: {
...fetchApplicationMockResponse.data.application,
pages: fetchApplicationMockResponse.data.pages,
applicationVersion: 1,
},
});
const component = render(
<ManualUpgrades showTooltip>
<Button
className="t--upgrade"
isIconButton
kind="tertiary"
size="md"
startIcon="upgrade"
/>
</ManualUpgrades>,
);
expect(component.getByTestId("update-indicator")).toBeDefined();
});
it("tests Route builder factory params", () => {
store.dispatch({
type: ReduxActionTypes.CURRENT_APPLICATION_NAME_UPDATE,
payload: updatedApplicationPayload,
});
store.dispatch({
type: ReduxActionTypes.UPDATE_PAGE_SUCCESS,
payload: updatedPagePayload,
});
const { applicationSlug, pageSlug: updatedPageSlug } =
urlBuilder.getURLParams(updatedPagePayload.id);
expect(applicationSlug).toBe(updatedApplicationPayload.slug);
expect(updatedPageSlug).toBe(updatedPagePayload.slug);
store.dispatch(updateCurrentPage("605c435a91dea93f0eaf91bc", "my-page-2"));
const { pageSlug } = urlBuilder.getURLParams("605c435a91dea93f0eaf91bc");
expect(pageSlug).toBe("my-page-2");
});
it("tests slug URLs utility methods", () => {
const legacyURL =
"/applications/605c435a91dea93f0eaf91ba/pages/605c435a91dea93f0eaf91ba/edit";
const slugURL = "/app/my-application/my-page-605c435a91dea93f0eaf91ba/edit";
expect(isURLDeprecated(legacyURL)).toBe(true);
expect(isURLDeprecated(slugURL)).toBe(false);
expect(
getUpdatedRoute(slugURL, {
applicationSlug: "my-app",
pageSlug: "page",
}),
).toBe("/app/my-app/page-605c435a91dea93f0eaf91ba/edit");
});
it("getUpdatedRoute - handles pattern match overlap with slug url and custom slug url", () => {
// this path will match with VIEWER_PATH and BUILDER_CUSTOM_PATH
const customSlug_pathname =
"/app/custom-63c63d944ae4345e31af12a7/edit/saas/google-sheets-plugin/api/63c63d984ae4345e31af12e5";
// verify path match overlap
const matchBuilderCustomPath =
matchPath_BuilderCustomSlug(customSlug_pathname);
const matchViewerSlugPath = matchPath_ViewerSlug(customSlug_pathname);
expect(matchViewerSlugPath).not.toBeNull();
expect(matchBuilderCustomPath).not.toBeNull();
// verify proper url is returned regarless of match overlap
expect(
getUpdatedRoute(customSlug_pathname, {
applicationSlug: "gsheetreleasetesting-copy",
customSlug: "custom",
pageId: "63c63d944ae4345e31af12a7",
pageSlug: "basicpagination",
}),
).toBe(customSlug_pathname);
});
});
|
1,040 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/workspace | petrpan-code/appsmithorg/appsmith/app/client/src/pages/workspace/__tests__/SettingsPageHeader.test.tsx | import React from "react";
import "@testing-library/jest-dom";
import { render, screen } from "test/testUtils";
import { SettingsPageHeader } from "../SettingsPageHeader";
import userEvent from "@testing-library/user-event";
let container: any = null;
const handleChange = jest.fn();
const mockOnSelect = jest.fn();
const pageMenuItems = [
{
icon: "book-line",
onSelect: mockOnSelect,
text: "Documentation",
},
];
function renderComponent() {
render(
<SettingsPageHeader
buttonText="Add"
onSearch={handleChange as any}
pageMenuItems={pageMenuItems}
searchPlaceholder="Search users"
showMoreOptions={false}
title={"Settings"}
/>,
);
}
describe("<PageHeader />", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
it("is rendered", () => {
renderComponent();
const searchInput = screen.queryAllByTestId("t--search-input");
expect(searchInput).toHaveLength(1);
});
it("should search and filter results for the given search query", async () => {
renderComponent();
const searchInput = screen.queryAllByTestId("t--search-input");
await userEvent.type(searchInput[0], "test value");
expect(searchInput[0]).toHaveValue("test value");
});
it("should have a button with text Add", () => {
renderComponent();
const button = screen.queryAllByTestId("t--page-header-input");
expect(button).toHaveLength(1);
expect(button[0]).toHaveTextContent("Add");
});
it("should show menu options on click of more", async () => {
const { queryAllByTestId, queryAllByText } = render(
<SettingsPageHeader
buttonText="Add"
onSearch={handleChange as any}
pageMenuItems={pageMenuItems}
searchPlaceholder="Search users"
showMoreOptions
title={"Settings"}
/>,
);
const moreMenu = queryAllByTestId("t--page-header-actions");
let menuOptions = queryAllByText(/Documentation/i);
expect(menuOptions).toHaveLength(0);
await userEvent.click(moreMenu[0]);
menuOptions = queryAllByText(/Documentation/i);
expect(menuOptions).toHaveLength(1);
await userEvent.click(menuOptions[0]);
expect(pageMenuItems[0].onSelect).toHaveBeenCalled();
});
});
|
1,041 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/workspace | petrpan-code/appsmithorg/appsmith/app/client/src/pages/workspace/__tests__/WorkspaceSettingsForm.test.tsx | import React from "react";
import { unmountComponentAtNode } from "react-dom";
import { render } from "test/testUtils";
import "@testing-library/jest-dom";
import { GeneralSettings } from "../General";
let container: any = null;
describe("Application Settings", () => {
beforeEach(async () => {
// setup a DOM element as a render target
container = document.createElement("div");
document.body.appendChild(container);
});
it("checks that workspace settings have correct styling", async () => {
const { findByText } = render(<GeneralSettings />);
const workspaceNameField = await findByText("Workspace name");
expect(workspaceNameField.closest("div")).toHaveStyle({ width: "100%" });
});
afterEach(() => {
// cleanup on exiting
unmountComponentAtNode(container);
container.remove();
container = null;
});
});
|
1,042 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/pages/workspace | petrpan-code/appsmithorg/appsmith/app/client/src/pages/workspace/__tests__/settings.test.tsx | import React from "react";
import "@testing-library/jest-dom";
import Router from "react-router-dom";
import { render, screen } from "test/testUtils";
import Settings from "../settings";
import * as reactRedux from "react-redux";
let container: any = null;
const mockWorkspaceData = {
id: "62a585995f76022609968dfa",
userPermissions: [
"inviteUsers:workspace",
"publish:workspaceApplications",
"read:workspaces",
"manage:workspaceApplications",
"export:workspaceApplications",
"read:workspaceApplications",
"manage:workspaces",
],
name: "Sangeeth's apps",
email: "[email protected]",
plugins: [
{
userPermissions: [],
pluginId: "62a57f3630ad39335c4dbf19",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a57f3830ad39335c4dbf69",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a57f3830ad39335c4dbf2b",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a57f3830ad39335c4dbf6e",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a57f3630ad39335c4dbf1a",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a583af5f76022609968df8",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a57f3830ad39335c4dbf70",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a57f3830ad39335c4dbf6b",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a57f3930ad39335c4dbf81",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a57f3a30ad39335c4dbfa7",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a57f3a30ad39335c4dbfb8",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a57f3630ad39335c4dbf17",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a57f3930ad39335c4dbf99",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a57f3930ad39335c4dbf7d",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a57f3930ad39335c4dbf8e",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a57f3930ad39335c4dbf9f",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a57f3630ad39335c4dbf18",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a57f3930ad39335c4dbf78",
status: "FREE",
new: true,
},
{
userPermissions: [],
pluginId: "62a583af5f76022609968df8",
status: "ACTIVATED",
new: true,
},
{
userPermissions: [],
pluginId: "62b9d071a43ddb5b61d2558c",
status: "ACTIVATED",
new: true,
},
],
slug: "sangeeth-s-apps",
isAutoGeneratedOrganization: true,
isAutoGeneratedWorkspace: true,
tenantId: "62a57f3c30ad39335c4dbffe",
logoUrl: "/api/v1/assets/null",
new: false,
};
jest.mock("react-router-dom", () => ({
...jest.requireActual("react-router-dom"),
useParams: jest.fn(),
}));
function renderComponent() {
render(<Settings />);
}
describe("<Settings />", () => {
const useSelectorMock = jest.spyOn(reactRedux, "useSelector");
const useDispatchMock = jest.spyOn(reactRedux, "useDispatch");
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
jest
.spyOn(Router, "useParams")
.mockReturnValue({ workspaceId: mockWorkspaceData.id });
useSelectorMock.mockReturnValue([mockWorkspaceData]);
useDispatchMock.mockClear();
});
it("is rendered", () => {
renderComponent();
const settings = screen.queryAllByTestId("t--settings-wrapper");
expect(settings).toHaveLength(1);
});
it("displays correct title", () => {
renderComponent();
const title = screen.getAllByTestId("t--page-title");
expect(title).toHaveLength(1);
expect(title[0].textContent).toBe(`${mockWorkspaceData.name}`);
});
it("displays tabs", () => {
renderComponent();
const tabList = screen.getAllByRole("tab");
expect(tabList.length).toBeGreaterThanOrEqual(2);
expect(tabList.length).toBeLessThanOrEqual(3);
});
});
|
1,080 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/reducers | petrpan-code/appsmithorg/appsmith/app/client/src/reducers/entityReducers/canvasWidgetsReducer.test.ts | import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
import reducer from "./canvasWidgetsReducer";
describe("Canvas Widgets Reducer", () => {
it("should return the initial state", () => {
expect(reducer(undefined, { type: "", payload: "" })).toEqual({});
});
it("should update the paths", () => {
const initialState = {
"0": { children: ["xyz123"] },
xyz123: {
bottomRow: 20,
topRow: 10,
someValue: {
apple: "orange",
},
},
};
const type = ReduxActionTypes.UPDATE_MULTIPLE_WIDGET_PROPERTIES;
const payload = {
widgetsToUpdate: {
xyz123: [
{
propertyPath: "someValue.apple",
propertyValue: "apple",
},
],
},
shouldEval: false,
};
const expected = {
"0": { children: ["xyz123"] },
xyz123: {
bottomRow: 20,
topRow: 10,
someValue: {
apple: "apple",
},
},
};
expect(reducer(initialState, { type, payload })).toEqual(expected);
});
it("should create paths if they donot exist", () => {
const initialState = {
"0": { children: ["xyz123"] },
xyz123: {
bottomRow: 20,
topRow: 10,
someValue: {
apple: "orange",
},
},
};
const type = ReduxActionTypes.UPDATE_MULTIPLE_WIDGET_PROPERTIES;
const payload = {
widgetsToUpdate: {
xyz123: [
{
propertyPath: "someValue.games.ball",
propertyValue: ["football"],
},
],
},
shouldEval: false,
};
const expected = {
"0": { children: ["xyz123"] },
xyz123: {
bottomRow: 20,
topRow: 10,
someValue: {
apple: "orange",
games: {
ball: ["football"],
},
},
},
};
expect(reducer(initialState, { type, payload })).toEqual(expected);
});
it("should not update the paths if the values are the same", () => {
const initialState = {
"0": { children: ["xyz123"] },
xyz123: {
bottomRow: 20,
topRow: 10,
someValue: {
apple: "orange",
},
},
};
const type = ReduxActionTypes.UPDATE_MULTIPLE_WIDGET_PROPERTIES;
const payload = {
widgetsToUpdate: {
xyz123: [
{
propertyPath: "someValue.apple",
propertyValue: "orange",
},
],
},
shouldEval: false,
};
// Reference equality check using toBe
expect(reducer(initialState, { type, payload })).toBe(initialState);
});
it("should have the same reference for paths not updated", () => {
const initialState = {
"0": { children: ["xyz123"] },
xyz123: {
bottomRow: 20,
topRow: 10,
someValue: {
apple: "orange",
games: {
ball: ["football"],
},
},
},
};
const type = ReduxActionTypes.UPDATE_MULTIPLE_WIDGET_PROPERTIES;
const payload = {
widgetsToUpdate: {
xyz123: [
{
propertyPath: "someValue.apple",
propertyValue: "orange",
},
],
},
shouldEval: true,
};
const result = reducer(initialState, { type, payload }).xyz123.someValue
.games;
// Reference equality check using toBe
expect(result).toBe(initialState.xyz123.someValue.games);
});
});
|
1,086 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/reducers | petrpan-code/appsmithorg/appsmith/app/client/src/reducers/entityReducers/metaWidgetsReducer.test.ts | import type { MetaWidgetsReduxState } from "./metaWidgetsReducer";
import reducer from "./metaWidgetsReducer";
import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
import { metaWidgetState } from "utils/metaWidgetState";
import { nestedMetaWidgetInitialState } from "./testData/metaWidgetReducer";
import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants";
import { getAssetUrl } from "@appsmith/utils/airgapHelpers";
const modifiedState: MetaWidgetsReduxState = {
baowuczcgg: {
parentColumnSpace: 1,
parentRowSpace: 1,
isVisible: true,
defaultImage: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`),
imageShape: "RECTANGLE",
maxZoomLevel: 1,
enableRotation: false,
enableDownload: false,
objectFit: "cover",
image: "{{((currentItem) => currentItem.img)(Image1.currentItem)}}",
widgetName: "Image1",
version: 1,
animateLoading: true,
type: "IMAGE_WIDGET",
hideCard: false,
isDeprecated: false,
displayName: "Image",
key: "zqar6ryg82",
iconSVG: "/static/media/icon.52d8fb963abcb95c79b10f1553389f22.svg",
boxShadow: "none",
dynamicBindingPathList: [
{
key: "image",
},
{
key: "borderRadius",
},
{
key: "currentItem",
},
{
key: "currentView",
},
],
dynamicTriggerPathList: [],
widgetId: "baowuczcgg",
renderMode: "CANVAS",
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
isLoading: false,
leftColumn: 0,
rightColumn: 16,
topRow: 0,
bottomRow: 8,
parentId: "xbbs7cls18",
currentItem: "{{List1.listData[Image1.currentIndex]}}",
currentView: "{{{}}}",
currentIndex: 0,
children: [],
referencedWidgetId: "baowuczcgg",
isMetaWidget: true,
creatorId: "hwgin979n4",
},
xy20z9gxsc: {
parentColumnSpace: 1,
parentRowSpace: 1,
isVisible: true,
text: "{{((currentItem) => currentItem.name)(Text1.currentItem)}}",
fontSize: "1rem",
fontStyle: "BOLD",
textAlign: "LEFT",
textColor: "#231F20",
truncateButtonColor: "#FFC13D",
widgetName: "Text1",
shouldTruncate: false,
overflow: "NONE",
version: 1,
animateLoading: true,
searchTags: ["typography", "paragraph", "label"],
type: "TEXT_WIDGET",
hideCard: false,
isDeprecated: false,
displayName: "Text",
key: "eezvtpz4sw",
iconSVG: "/static/media/icon.97c59b523e6f70ba6f40a10fc2c7c5b5.svg",
textStyle: "HEADING",
boxShadow: "none",
dynamicBindingPathList: [
{
key: "text",
},
{
key: "fontFamily",
},
{
key: "borderRadius",
},
{
key: "currentItem",
},
{
key: "currentView",
},
],
dynamicTriggerPathList: [],
widgetId: "xy20z9gxsc",
renderMode: "CANVAS",
fontFamily: "{{appsmith.theme.fontFamily.appFont}}",
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
isLoading: false,
leftColumn: 16,
rightColumn: 28,
topRow: 0,
bottomRow: 4,
parentId: "xbbs7cls18",
currentItem: "{{List1.listData[Text1.currentIndex]}}",
currentView: "{{{}}}",
currentIndex: 0,
children: [],
referencedWidgetId: "xy20z9gxsc",
isMetaWidget: true,
creatorId: "hwgin979n4",
},
tsdy8whhl1: {
parentColumnSpace: 1,
parentRowSpace: 1,
isVisible: true,
text: "{{((currentItem) => currentItem.id)(Text2.currentItem)}}",
fontSize: "1rem",
fontStyle: "BOLD",
textAlign: "LEFT",
textColor: "#231F20",
truncateButtonColor: "#FFC13D",
widgetName: "Text2",
shouldTruncate: false,
overflow: "NONE",
version: 1,
animateLoading: true,
searchTags: ["typography", "paragraph", "label"],
type: "TEXT_WIDGET",
hideCard: false,
isDeprecated: false,
displayName: "Text",
key: "eezvtpz4sw",
iconSVG: "/static/media/icon.97c59b523e6f70ba6f40a10fc2c7c5b5.svg",
textStyle: "BODY",
boxShadow: "none",
dynamicBindingPathList: [
{
key: "text",
},
{
key: "fontFamily",
},
{
key: "borderRadius",
},
{
key: "currentItem",
},
{
key: "currentView",
},
],
dynamicTriggerPathList: [],
widgetId: "tsdy8whhl1",
renderMode: "CANVAS",
fontFamily: "{{appsmith.theme.fontFamily.appFont}}",
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
isLoading: false,
leftColumn: 16,
rightColumn: 24,
topRow: 4,
bottomRow: 8,
parentId: "xbbs7cls18",
currentItem: "{{List1.listData[Text2.currentIndex]}}",
currentView: "{{{}}}",
currentIndex: 0,
children: [],
referencedWidgetId: "tsdy8whhl1",
isMetaWidget: true,
creatorId: "hwgin979n4",
},
xbbs7cls18: {
isVisible: true,
widgetName: "Canvas2",
version: 1,
detachFromLayout: true,
type: "CANVAS_WIDGET",
hideCard: true,
isDeprecated: false,
displayName: "Canvas",
key: "rhrv9ccmof",
containerStyle: "none",
canExtend: false,
children: ["baowuczcgg", "xy20z9gxsc", "tsdy8whhl1"],
minHeight: 1,
widgetId: "xbbs7cls18",
renderMode: "CANVAS",
boxShadow: "none",
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
accentColor: "{{appsmith.theme.colors.primaryColor}}",
isLoading: false,
parentColumnSpace: 1,
parentRowSpace: 1,
leftColumn: 0,
rightColumn: 1,
topRow: 0,
bottomRow: 1,
parentId: "e3bqqc9oid",
dynamicBindingPathList: [
{
key: "borderRadius",
},
{
key: "accentColor",
},
{
key: "currentView",
},
],
currentView: "{{{}}}",
currentIndex: 0,
referencedWidgetId: "xbbs7cls18",
isMetaWidget: true,
creatorId: "hwgin979n4",
},
e3bqqc9oid: {
isVisible: true,
parentColumnSpace: 1,
parentRowSpace: 1,
backgroundColor: "white",
widgetName: "Container1",
containerStyle: "card",
borderColor: "#E0DEDE",
borderWidth: "1",
boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}",
animateLoading: true,
children: ["xbbs7cls18"],
version: 1,
searchTags: ["div", "parent", "group"],
type: "CONTAINER_WIDGET",
hideCard: false,
isDeprecated: false,
displayName: "Container",
key: "b33ov8lfex",
iconSVG: "/static/media/icon.1977dca3370505e2db3a8e44cfd54907.svg",
isCanvas: true,
dragDisabled: true,
isDeletable: false,
disallowCopy: true,
disablePropertyPane: true,
openParentPropertyPane: true,
widgetId: "e3bqqc9oid",
renderMode: "CANVAS",
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
isLoading: false,
leftColumn: 0,
rightColumn: 64,
topRow: 0,
bottomRow: 12,
parentId: "8ari8fii6k",
dynamicBindingPathList: [
{
key: "borderRadius",
},
{
key: "boxShadow",
},
{
key: "data",
},
],
gap: 0,
data: "{{\n {\n \n Image1: { image: Image1.image,isVisible: Image1.isVisible }\n ,\n Text1: { isVisible: Text1.isVisible,text: Text1.text }\n ,\n Text2: { isVisible: Text2.isVisible,text: Text2.text }\n \n }\n }}",
currentIndex: 0,
referencedWidgetId: "e3bqqc9oid",
isMetaWidget: true,
creatorId: "hwgin979n4",
},
"8ari8fii6k": {
isVisible: true,
widgetName: "Canvas1",
version: 1,
detachFromLayout: true,
type: "CANVAS_WIDGET",
hideCard: true,
isDeprecated: false,
displayName: "Canvas",
key: "rhrv9ccmof",
containerStyle: "none",
dropDisabled: true,
openParentPropertyPane: true,
noPad: true,
children: ["e3bqqc9oid"],
minHeight: 190,
widgetId: "8ari8fii6k",
renderMode: "CANVAS",
boxShadow: "none",
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
accentColor: "{{appsmith.theme.colors.primaryColor}}",
isLoading: false,
parentColumnSpace: 1,
parentRowSpace: 1,
leftColumn: 0,
rightColumn: 314.25,
topRow: 0,
bottomRow: 154,
parentId: "hwgin979n4",
dynamicBindingPathList: [
{
key: "borderRadius",
},
{
key: "accentColor",
},
],
isMetaWidget: true,
creatorId: "hwgin979n4",
},
};
describe("meta widget reducer test", () => {
it("DELETE_META_WIDGETS", () => {
const creatorId = "u9ibqgimu2";
const expectedState: Record<string, unknown> = {};
Object.entries(nestedMetaWidgetInitialState).forEach(
([widgetId, widgetProps]) => {
if (widgetProps.creatorId !== creatorId) {
expectedState[widgetId] = widgetProps;
}
},
);
expect(
reducer(nestedMetaWidgetInitialState, {
type: ReduxActionTypes.DELETE_META_WIDGETS,
payload: {
creatorIds: [creatorId],
},
}),
).toEqual(expectedState);
});
it("INIT_CANVAS_LAYOUT", () => {
expect(
reducer(metaWidgetState, {
type: ReduxActionTypes.INIT_CANVAS_LAYOUT,
payload: {},
}),
).toEqual(metaWidgetState);
});
it("MODIFY_META_WIDGETS", () => {
expect(
reducer(metaWidgetState, {
type: ReduxActionTypes.MODIFY_META_WIDGETS,
payload: {
addOrUpdate: {
"8ari8fii6k": {
isVisible: true,
widgetName: "Canvas1",
version: 1,
detachFromLayout: true,
type: "CANVAS_WIDGET",
hideCard: true,
isDeprecated: false,
displayName: "Canvas",
key: "rhrv9ccmof",
containerStyle: "none",
dropDisabled: true,
openParentPropertyPane: true,
noPad: true,
children: ["e3bqqc9oid"],
minHeight: 190,
widgetId: "8ari8fii6k",
renderMode: "CANVAS",
boxShadow: "none",
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
accentColor: "{{appsmith.theme.colors.primaryColor}}",
isLoading: false,
parentColumnSpace: 1,
parentRowSpace: 1,
leftColumn: 0,
rightColumn: 314.25,
topRow: 0,
bottomRow: 154,
parentId: "hwgin979n4",
dynamicBindingPathList: [
{
key: "borderRadius",
},
{
key: "accentColor",
},
],
isMetaWidget: true,
creatorId: "hwgin979n4",
},
},
deleteIds: [
"u2jvh7h1f1",
"pawh54e2lk",
"o6yxt84kj5",
"ze1bnh8dpw",
"4b5r4c3kp7",
"3vmg2xwodp",
"squbljzvqv",
"zoq1nw5wke",
"gb0vgfvp68",
"3g3bxw6q2z",
],
propertyUpdates: [],
creatorId: "hwgin979n4",
},
}),
).toEqual(modifiedState);
});
});
|
1,090 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/reducers/entityReducers | petrpan-code/appsmithorg/appsmith/app/client/src/reducers/entityReducers/autoHeightReducers/autoHeightLayoutTreeReducer.test.ts | import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
import reducer from "./autoHeightLayoutTreeReducer";
describe("Canvas Levels Reducer", () => {
it("should return the initial state", () => {
expect(reducer(undefined, { type: "", payload: "" })).toEqual({});
});
it("should set the new auto height layout tree", () => {
const type = ReduxActionTypes.SET_AUTO_HEIGHT_LAYOUT_TREE;
const payload = {
tree: {
0: {
aboves: [],
belows: [],
topRow: 0,
bottomRow: 0,
originalTopRow: 0,
originalBottomRow: 0,
},
},
};
const expected = {
0: {
aboves: [],
belows: [],
topRow: 0,
bottomRow: 0,
originalTopRow: 0,
originalBottomRow: 0,
},
};
expect(reducer(undefined, { type, payload })).toEqual(expected);
});
it("should augment the auto height layout tree further in the state", () => {
const type = ReduxActionTypes.SET_AUTO_HEIGHT_LAYOUT_TREE;
const payload = {
tree: {
0: {
aboves: [],
belows: [],
topRow: 0,
bottomRow: 0,
originalTopRow: 0,
originalBottomRow: 0,
},
},
};
const state = reducer(undefined, { type, payload });
const payload2 = {
tree: {
0: {
aboves: [],
belows: [1],
topRow: 0,
bottomRow: 0,
originalTopRow: 0,
originalBottomRow: 0,
},
1: {
aboves: [0],
belows: [],
topRow: 10,
bottomRow: 10,
originalTopRow: 10,
originalBottomRow: 10,
},
},
};
const expected = {
0: {
aboves: [],
belows: [1],
topRow: 0,
bottomRow: 0,
originalTopRow: 0,
originalBottomRow: 0,
},
1: {
aboves: [0],
belows: [],
topRow: 10,
bottomRow: 10,
originalTopRow: 10,
originalBottomRow: 10,
},
};
const state2 = reducer(state, { type, payload: payload2 });
expect(state2).toEqual(expected);
});
});
|
1,092 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/reducers/entityReducers | petrpan-code/appsmithorg/appsmith/app/client/src/reducers/entityReducers/autoHeightReducers/canvasLevelsReducer.test.ts | import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
import reducer from "./canvasLevelsReducer";
describe("Canvas Levels Reducer", () => {
it("should return the initial state", () => {
expect(reducer(undefined, { type: "", payload: "" })).toEqual({});
});
it("should set the new canvas mappings to the state", () => {
const type = ReduxActionTypes.SET_AUTO_HEIGHT_LAYOUT_TREE;
const payload = {
canvasLevelMap: {
0: 0,
},
};
const expected = {
0: 0,
};
expect(reducer(undefined, { type, payload })).toEqual(expected);
});
it("should augment the further canvas mappings to the state", () => {
const type = ReduxActionTypes.SET_AUTO_HEIGHT_LAYOUT_TREE;
const payload = {
canvasLevelMap: {
0: 0,
},
};
const state = reducer(undefined, { type, payload });
const payload2 = {
canvasLevelMap: {
1: 1,
},
};
const expected = {
0: 0,
1: 1,
};
expect(reducer(state, { type, payload: payload2 })).toEqual(expected);
});
});
|
1,096 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/reducers/entityReducers | petrpan-code/appsmithorg/appsmith/app/client/src/reducers/entityReducers/metaReducer/test.ts | import metaReducer, { initialState } from "./index";
import { updateMetaState } from "actions/metaActions";
import type { ReduxAction } from "@appsmith/constants/ReduxActionConstants";
import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
let currentMetaState = initialState;
const inputWidget = {
widgetId: "incwlne",
propertyName: "selectedValues",
propertyValue: ["GREEN", "BLUE", "YELLOW"],
};
const noAction = (): ReduxAction<unknown> => {
return {
type: "NO_ACTION",
payload: {},
};
};
test("should return the initial state", () => {
expect(metaReducer(undefined, noAction())).toEqual(currentMetaState);
});
test("Add a widget meta values", () => {
currentMetaState = initialState;
expect(
metaReducer(currentMetaState, {
type: ReduxActionTypes.SET_META_PROP,
payload: {
widgetId: inputWidget.widgetId,
propertyName: inputWidget.propertyName,
propertyValue: inputWidget.propertyValue,
},
}),
).toEqual({
incwlne: {
selectedValues: ["GREEN", "BLUE", "YELLOW"],
},
});
});
test("Update widget meta state using evalMetaUpdates", () => {
const evalMetaUpdates = [
{ widgetId: "incwlne", metaPropertyPath: ["text"], value: "test123" },
{
widgetId: "incwlne",
metaPropertyPath: ["selectedValues"],
value: ["YELLOW"],
},
];
currentMetaState = metaReducer(
currentMetaState,
updateMetaState(evalMetaUpdates),
);
expect(currentMetaState).toEqual({
incwlne: {
text: "test123",
selectedValues: ["YELLOW"],
},
});
});
describe("Reset widget meta action", () => {
test("Reset widget with only widgetId", () => {
currentMetaState = metaReducer(currentMetaState, {
type: ReduxActionTypes.RESET_WIDGET_META,
payload: {
widgetId: inputWidget.widgetId,
},
});
expect(currentMetaState).toEqual({
incwlne: {},
});
});
currentMetaState = initialState;
expect(
metaReducer(currentMetaState, {
type: ReduxActionTypes.SET_META_PROP,
payload: {
widgetId: inputWidget.widgetId,
propertyName: inputWidget.propertyName,
propertyValue: inputWidget.propertyValue,
},
}),
).toEqual({
incwlne: {
selectedValues: ["GREEN", "BLUE", "YELLOW"],
},
});
test("Reset widget with evaluated values", () => {
expect(
metaReducer(currentMetaState, {
type: ReduxActionTypes.RESET_WIDGET_META,
payload: {
widgetId: inputWidget.widgetId,
evaluatedWidget: {
defaultSelectedValues: ["GREEN"],
selectedValues: ["GREEN", "BLUE", "YELLOW"],
widgetId: inputWidget.widgetId,
propertyOverrideDependency: {
selectedValues: {
DEFAULT: "defaultSelectedValues",
META: "meta.selectedValues",
},
},
},
evaluatedWidgetConfig: {
widgetId: inputWidget.widgetId,
propertyOverrideDependency: {
selectedValues: {
DEFAULT: "defaultSelectedValues",
META: "meta.selectedValues",
},
},
},
},
}),
).toEqual({
incwlne: {
selectedValues: ["GREEN"],
},
});
});
});
|
1,138 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/reducers | petrpan-code/appsmithorg/appsmith/app/client/src/reducers/uiReducers/pageWidgetsReducer.test.ts | import reducer from "./pageWidgetsReducer";
import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
import { getCurrentRowBinding } from "widgets/TableWidget/constants";
const pageWidgetUIInitialState = {
"60783f9204a08773573ed1d2": {
"0": {
widgetName: "MainContainer",
backgroundColor: "none",
rightColumn: 1118,
snapColumns: 16,
detachFromLayout: true,
widgetId: "0",
topRow: 0,
bottomRow: 1254,
containerStyle: "none",
snapRows: 33,
parentRowSpace: 1,
type: "CANVAS_WIDGET",
canExtend: true,
version: 16,
minHeight: 1292,
parentColumnSpace: 1,
dynamicBindingPathList: [],
leftColumn: 0,
children: ["i0zf1h4l5x", "qiyxmm887p"],
},
i0zf1h4l5x: {
isVisible: true,
label: "Data",
widgetName: "Standup_Table",
searchKey: "",
textSize: "PARAGRAPH",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
primaryColumns: {
avatar: {
index: 0,
width: 150,
id: "avatar",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "image",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "avatar",
computedValue: getCurrentRowBinding(
"Standup_Table",
"currentRow.avatar",
),
outputFormat: "",
},
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(
"Standup_Table",
"currentRow.name",
),
},
notes: {
index: 2,
width: 150,
id: "notes",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "notes",
computedValue: getCurrentRowBinding(
"Standup_Table",
"currentRow.notes",
),
},
},
derivedColumns: {},
tableData: "{{fetch_standup_updates.data}}",
version: 1,
type: "TABLE_WIDGET",
isLoading: false,
parentColumnSpace: 1,
parentRowSpace: 40,
leftColumn: 0,
rightColumn: 16,
topRow: 2,
bottomRow: 17,
parentId: "0",
widgetId: "i0zf1h4l5x",
columnSizeMap: {
avatar: 20,
name: 30,
},
migrated: true,
columns: 16,
rows: 15,
dynamicBindingPathList: [
{
key: "tableData",
},
{
key: "primaryColumns.avatar.computedValue",
},
{
key: "primaryColumns.name.computedValue",
},
{
key: "primaryColumns.notes.computedValue",
},
],
dynamicTriggerPathList: [],
columnTypeMap: {
avatar: {
type: "image",
format: "",
},
},
columnOrder: ["avatar", "name", "notes"],
},
qiyxmm887p: {
isVisible: true,
inputType: "TEXT",
label: "",
widgetName: "Standup_Input",
version: 1,
resetOnSubmit: true,
placeholderText: "Type your update and hit enter!",
type: "INPUT_WIDGET_V2",
isLoading: false,
leftColumn: 5,
rightColumn: 11,
topRow: 1,
bottomRow: 2,
parentId: "0",
widgetId: "qiyxmm887p",
onSubmit:
"{{add_standup_updates.run(() => fetch_standup_updates.run(), () => {})}}",
dynamicBindingPathList: [],
dynamicTriggerPathList: [
{
key: "onSubmit",
},
],
},
},
};
describe("page widget reducer test", () => {
it("should remove page widgets from state", () => {
expect(
reducer(pageWidgetUIInitialState, {
type: ReduxActionTypes.RESET_APPLICATION_WIDGET_STATE_REQUEST,
payload: {},
}),
).toEqual({});
});
});
|
1,201 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/sagas/WidgetBlueprintSagas.test.ts | import WidgetFactory from "WidgetProvider/factory";
import { BlueprintOperationTypes } from "WidgetProvider/constants";
import type { BlueprintOperation } from "./WidgetBlueprintSagas";
import { executeWidgetBlueprintChildOperations } from "./WidgetBlueprintSagas";
describe("WidgetBlueprintSagas", () => {
it("should returns widgets after executing the child operation", async () => {
const mockBlueprintChildOperation: BlueprintOperation = {
type: BlueprintOperationTypes.CHILD_OPERATIONS,
fn: () => {
return { widgets: {} };
},
};
jest
.spyOn(WidgetFactory, "getWidgetDefaultPropertiesMap")
.mockReturnValue({});
const generator = executeWidgetBlueprintChildOperations(
mockBlueprintChildOperation,
{
widgetId: {
image: "",
defaultImage: "",
widgetId: "Widget1",
type: "LIST_WIDGET",
widgetName: "List1",
parentId: "parentId",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
items: [],
version: 16,
disablePropertyPane: false,
},
},
["widgetId"],
"parentId",
);
generator.next();
expect(generator.next().value).toStrictEqual({});
});
});
|
1,206 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/sagas/WidgetOperationSaga.test.tsx | const updateAndSaveLayoutMock = jest.fn();
import {
setWidgetDynamicPropertySaga,
removeDynamicBindingProperties,
handleUpdateWidgetDynamicProperty,
batchUpdateWidgetDynamicPropertySaga,
} from "./WidgetOperationSagas";
const widget = {
isVisible: "true",
dynamicPropertyPathList: [],
dynamicBindingPathList: [],
};
const widget1 = {
isVisible: "{{true}}",
dynamicPropertyPathList: [
{
key: "isVisible",
},
],
dynamicBindingPathList: [
{
key: "isVisible",
},
],
};
jest.mock("redux-saga/effects", () => {
const originalModule = jest.requireActual("redux-saga/effects");
return {
__esModule: true,
...originalModule,
select: jest.fn(),
call: jest.fn(),
put: jest.fn(),
};
});
jest.mock("actions/pageActions", () => {
const originalModule = jest.requireActual("actions/pageActions");
return {
__esModule: true,
...originalModule,
updateAndSaveLayout: updateAndSaveLayoutMock,
};
});
describe("WidgetOperationSaga - ", () => {
describe("Should test setWidgetDynamicPropertySaga ", () => {
it("should update dynamicBindingPathList on js toggle", () => {
const value = setWidgetDynamicPropertySaga({
type: "test",
payload: {
isDynamic: true,
propertyPath: "isVisible",
widgetId: "test",
},
});
value.next(); // start
value.next(widget as any); // yield select
value.next({
...widget,
dynamicPropertyPathList: [
{
key: "isVisible",
},
],
} as any);
value.next({
test: widget,
} as any); // yield select
value.next(); //yield put
expect(updateAndSaveLayoutMock).toHaveBeenCalledWith({
test: {
...widget,
dynamicPropertyPathList: [
{
key: "isVisible",
},
],
},
});
});
it("should remove property from dynamicBindingList on js toggle off", () => {
const value = setWidgetDynamicPropertySaga({
type: "test",
payload: {
isDynamic: false,
propertyPath: "isVisible",
widgetId: "test",
},
});
value.next(); // start
value.next(widget1 as any); // yield select
value.next({
...widget1,
dynamicPropertyPathList: [],
dynamicBindingPathList: [],
isVisible: 1,
} as any);
value.next({
test: widget1,
} as any); // yield select
value.next(); //yield put
expect(updateAndSaveLayoutMock).toHaveBeenCalledWith({
test: {
dynamicPropertyPathList: [],
dynamicBindingPathList: [],
isVisible: 1,
},
});
});
});
});
describe("Should test handleUpdateWidgetDynamicProperty ", () => {
it("should update dynamicBindingPathList on js toggle and return the widget with dynamicBindingPath", () => {
const value = handleUpdateWidgetDynamicProperty(widget as any, {
isDynamic: true,
propertyPath: "isVisible",
});
value.next(); // start
value.next(widget as any); // yield select
value.next({
test: widget,
} as any); // yield select
value.return({
test: {
...widget,
dynamicPropertyPathList: [
{
key: "isVisible",
},
],
},
} as any);
expect(value.next().done).toEqual(true);
});
});
describe("Should test batchUpdateWidgetDynamicPropertySaga ", () => {
it("should update dynamicBindingPathList on js toggle and return the widget with dynamicBindingPath", () => {
const value = batchUpdateWidgetDynamicPropertySaga({
type: "test",
payload: {
updates: [
{
isDynamic: true,
propertyPath: "isVisible",
},
],
widgetId: "test",
},
});
value.next(); // start
value.next(widget as any); // yield select
value.next({
...widget,
dynamicPropertyPathList: [
{
key: "isVisible",
},
],
} as any);
value.next({
test: widget,
} as any); // yield select
value.next(); //yield put
expect(updateAndSaveLayoutMock).toHaveBeenCalledWith({
test: {
...widget,
dynamicPropertyPathList: [
{
key: "isVisible",
},
],
},
});
});
it("should remove property from dynamicBindingList on js toggle off when calling batchUpdateWidgetDynamicPropertySaga", () => {
const value = batchUpdateWidgetDynamicPropertySaga({
type: "test",
payload: {
updates: [
{
isDynamic: false,
propertyPath: "isVisible",
},
],
widgetId: "test",
},
});
value.next(); // start
value.next(widget1 as any); // yield select
value.next({
...widget1,
dynamicPropertyPathList: [],
dynamicBindingPathList: [],
isVisible: 1,
} as any);
value.next({
test: widget1,
} as any); // yield select
value.next(); //yield put
expect(updateAndSaveLayoutMock).toHaveBeenCalledWith({
test: {
dynamicPropertyPathList: [],
dynamicBindingPathList: [],
isVisible: 1,
},
});
});
});
describe("test removeDynamicBindingList", () => {
it("should remove table derived binding properties", () => {
// table bindings with derived properties
const dynamicBindingList = [
{ key: "primaryColumns.step.computedValue" },
{ key: "primaryColumns.task.computedValue" },
{ key: "primaryColumns.status.computedValue" },
{ key: "primaryColumns.action.computedValue" },
{ key: "derivedColumns.customColumn1.isCellVisible" },
{ key: "primaryColumns.customColumn1.isCellVisible" },
];
const propertyPath = "primaryColumns.customColumn1.isCellVisible";
const dynamicProperties = removeDynamicBindingProperties(
propertyPath,
dynamicBindingList,
);
// should remove custom and derived properties for customColumn1.isCellVisible
expect(dynamicProperties).not.toEqual(
expect.arrayContaining([
expect.objectContaining({
key: "derivedColumns.customColumn1.isCellVisible",
}),
expect.objectContaining({
key: "primaryColumns.customColumn1.isCellVisible",
}),
]),
);
});
it("should remove table binding properties", () => {
// table bindings
const dynamicBindingList = [
{ key: "primaryColumns.step.computedValue" },
{ key: "primaryColumns.task.computedValue" },
{ key: "primaryColumns.status.computedValue" },
{ key: "primaryColumns.action.computedValue" },
{ key: "primaryColumns.action.buttonLabel" },
];
const propertyPath = "primaryColumns.action.buttonLabel";
const dynamicProperties = removeDynamicBindingProperties(
propertyPath,
dynamicBindingList,
);
// should remove primaryColumns.action.buttonLabel property
expect(dynamicProperties).not.toEqual(
expect.arrayContaining([
expect.objectContaining({
key: "primaryColumns.action.buttonLabel",
}),
]),
);
});
it("should remove widget properties", () => {
// button widget binding
const dynamicBindingList = [{ key: "isVisible" }];
const propertyPath = "isVisible";
const dynamicProperties = removeDynamicBindingProperties(
propertyPath,
dynamicBindingList,
);
// should remove the isVisible property
expect(dynamicProperties).not.toEqual(
expect.arrayContaining([
expect.objectContaining({
key: "isVisible",
}),
]),
);
});
});
|
1,208 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/sagas/WidgetOperationUtils.test.ts | import type { OccupiedSpace } from "constants/CanvasEditorConstants";
import { klona } from "klona";
import { get } from "lodash";
import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsReducer";
import type { WidgetProps } from "widgets/BaseWidget";
import type { FlattenedWidgetProps } from "WidgetProvider/constants";
import type { CopiedWidgetGroup } from "./WidgetOperationUtils";
import {
handleIfParentIsListWidgetWhilePasting,
handleSpecificCasesWhilePasting,
doesTriggerPathsContainPropertyPath,
getSelectedWidgetIfPastingIntoListWidget,
checkForListWidgetInCopiedWidgets,
updateListWidgetPropertiesOnChildDelete,
purgeOrphanedDynamicPaths,
getBoundariesFromSelectedWidgets,
getSnappedGrid,
changeIdsOfPastePositions,
getVerticallyAdjustedPositions,
getNewPositionsForCopiedWidgets,
getPastePositionMapFromMousePointer,
getReflowedPositions,
getWidgetsFromIds,
getValueFromTree,
resizePublishedMainCanvasToLowestWidget,
} from "./WidgetOperationUtils";
describe("WidgetOperationSaga", () => {
it("should returns widgets after executing handleIfParentIsListWidgetWhilePasting", async () => {
expect(
doesTriggerPathsContainPropertyPath(false, "trigger-path-1", [
"trigger-path-1",
]),
).toBe(true);
expect(
doesTriggerPathsContainPropertyPath(false, "trigger-path-1", [
"trigger-path-2",
]),
).toBe(false);
expect(
doesTriggerPathsContainPropertyPath(true, "trigger-path-1", [
"trigger-path-2",
]),
).toBe(true);
});
it("should return widgets after executing handleIfParentIsListWidgetWhilePasting", async () => {
const result = handleIfParentIsListWidgetWhilePasting(
{
widgetId: "text1",
type: "TEXT_WIDGET",
widgetName: "Text1",
parentId: "list1",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
text: "{{currentItem.text}}",
version: 16,
disablePropertyPane: false,
},
{
list1: {
widgetId: "list1",
type: "LIST_WIDGET",
widgetName: "List1",
parentId: "0",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
version: 16,
disablePropertyPane: false,
template: {},
},
0: {
image: "",
defaultImage: "",
widgetId: "0",
type: "CANVAS_WIDGET",
widgetName: "MainContainer",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
version: 16,
disablePropertyPane: false,
template: {},
},
},
);
expect(result.list1.template["Text1"].text).toStrictEqual(
"{{List1.listData.map((currentItem) => (currentItem.text))}}",
);
expect(get(result, "list1.dynamicBindingPathList.0.key")).toStrictEqual(
"template.Text1.text",
);
});
it("should returns widgets after executing handleSpecificCasesWhilePasting", async () => {
const result = handleSpecificCasesWhilePasting(
{
widgetId: "text2",
type: "TEXT_WIDGET",
widgetName: "Text2",
parentId: "list2",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
text: "{{currentItem.text}}",
version: 16,
disablePropertyPane: false,
},
{
list1: {
widgetId: "list1",
type: "LIST_WIDGET",
widgetName: "List1",
parentId: "0",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
version: 16,
disablePropertyPane: false,
template: {},
},
0: {
image: "",
defaultImage: "",
widgetId: "0",
type: "CANVAS_WIDGET",
widgetName: "MainContainer",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
version: 16,
disablePropertyPane: false,
template: {},
},
list2: {
widgetId: "list2",
type: "LIST_WIDGET",
widgetName: "List2",
parentId: "0",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
version: 16,
disablePropertyPane: false,
template: {},
},
},
{
List1: "List2",
},
[
{
widgetId: "list2",
type: "LIST_WIDGET",
widgetName: "List2",
parentId: "0",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
version: 16,
disablePropertyPane: false,
template: {},
},
],
);
expect(result.list2.template["Text2"].text).toStrictEqual(
"{{List2.listData.map((currentItem) => (currentItem.text))}}",
);
expect(get(result, "list2.dynamicBindingPathList.0.key")).toStrictEqual(
"template.Text2.text",
);
});
it("handleSpecificCasesWhilePasting should rename dynamicTriggerPathList template keys for a copied list widget", async () => {
const result = handleSpecificCasesWhilePasting(
{
widgetId: "list2",
type: "LIST_WIDGET",
widgetName: "List2",
parentId: "0",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
version: 16,
disablePropertyPane: false,
template: {
Image1: {
widgetId: "image1",
type: "Image_WIDGET",
widgetName: "Image1",
parentId: "list2",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
version: 16,
disablePropertyPane: false,
dynamicTriggerPathList: [{ key: "onClick" }],
},
},
dynamicTriggerPathList: [{ key: "template.Image1.onClick" }],
},
{},
{
Image1: "Image1Copy",
},
[],
);
expect(get(result, "list2.dynamicTriggerPathList.0.key")).toStrictEqual(
"template.Image1Copy.onClick",
);
});
it("should return correct close modal reference name after executing handleSpecificCasesWhilePasting", async () => {
const result = handleSpecificCasesWhilePasting(
{
widgetName: "Modal1Copy",
rightColumn: 24,
detachFromLayout: true,
widgetId: "k441huwm77",
topRow: 34,
bottomRow: 58,
parentRowSpace: 10,
canOutsideClickClose: true,
type: "MODAL_WIDGET",
canEscapeKeyClose: true,
version: 1,
parentId: "0",
shouldScrollContents: true,
isLoading: false,
parentColumnSpace: 17.21875,
size: "MODAL_SMALL",
leftColumn: 0,
children: ["ihxw5r23hd"],
renderMode: "CANVAS",
},
{
k441huwm77: {
widgetName: "Modal1Copy",
rightColumn: 24,
detachFromLayout: true,
widgetId: "k441huwm77",
topRow: 34,
bottomRow: 58,
parentRowSpace: 10,
canOutsideClickClose: true,
type: "MODAL_WIDGET",
canEscapeKeyClose: true,
version: 1,
parentId: "0",
shouldScrollContents: true,
isLoading: false,
parentColumnSpace: 17.21875,
size: "MODAL_SMALL",
leftColumn: 0,
children: ["ihxw5r23hd"],
renderMode: "CANVAS",
},
suhkuyfpk3: {
widgetName: "Icon1Copy",
rightColumn: 64,
onClick: "{{closeModal('Modal1')}}",
color: "#040627",
iconName: "cross",
widgetId: "suhkuyfpk3",
topRow: 1,
bottomRow: 5,
isVisible: true,
type: "ICON_WIDGET",
version: 1,
parentId: "ihxw5r23hd",
isLoading: false,
leftColumn: 56,
iconSize: 24,
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
},
twnxjwy3r1: {
widgetName: "Button1Copy",
rightColumn: 48,
onClick: "{{closeModal('Modal1')}}",
isDefaultClickDisabled: true,
widgetId: "twnxjwy3r1",
buttonStyle: "SECONDARY_BUTTON",
topRow: 16,
bottomRow: 20,
isVisible: true,
type: "BUTTON_WIDGET",
version: 1,
parentId: "ihxw5r23hd",
isLoading: false,
dynamicTriggerPathList: [
{
key: "onClick",
},
],
leftColumn: 36,
dynamicBindingPathList: [],
text: "Cancel",
isDisabled: false,
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
},
},
{
Modal1: "Modal1Copy",
Canvas1: "Canvas1Copy",
Icon1: "Icon1Copy",
Text1: "Text1Copy",
Button1: "Button1Copy",
Button2: "Button2Copy",
},
[
{
widgetName: "Modal1Copy",
rightColumn: 24,
detachFromLayout: true,
widgetId: "k441huwm77",
topRow: 34,
bottomRow: 58,
parentRowSpace: 10,
canOutsideClickClose: true,
type: "MODAL_WIDGET",
canEscapeKeyClose: true,
version: 1,
parentId: "0",
shouldScrollContents: true,
isLoading: false,
parentColumnSpace: 17.21875,
size: "MODAL_SMALL",
leftColumn: 0,
children: ["ihxw5r23hd"],
renderMode: "CANVAS",
},
{
widgetName: "Icon1Copy",
rightColumn: 64,
onClick: "{{closeModal('Modal1')}}",
color: "#040627",
iconName: "cross",
widgetId: "suhkuyfpk3",
topRow: 1,
bottomRow: 5,
isVisible: true,
type: "ICON_WIDGET",
version: 1,
parentId: "ihxw5r23hd",
isLoading: false,
leftColumn: 56,
iconSize: 24,
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
},
{
widgetName: "Button1Copy",
rightColumn: 48,
onClick: "{{closeModal('Modal1')}}",
isDefaultClickDisabled: true,
widgetId: "twnxjwy3r1",
buttonStyle: "SECONDARY_BUTTON",
topRow: 16,
bottomRow: 20,
isVisible: true,
type: "BUTTON_WIDGET",
version: 1,
parentId: "ihxw5r23hd",
isLoading: false,
dynamicTriggerPathList: [
{
key: "onClick",
},
],
leftColumn: 36,
dynamicBindingPathList: [],
text: "Cancel",
isDisabled: false,
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
},
],
);
expect(result["suhkuyfpk3"].onClick).toStrictEqual(
"{{closeModal('Modal1Copy')}}",
);
expect(result["twnxjwy3r1"].onClick).toStrictEqual(
"{{closeModal('Modal1Copy')}}",
);
});
it("should returns widgets after executing getSelectedWidgetIfPastingIntoListWidget", async () => {
const result = getSelectedWidgetIfPastingIntoListWidget(
{
list2: {
widgetId: "list2",
type: "LIST_WIDGET",
widgetName: "List2",
parentId: "0",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
version: 16,
disablePropertyPane: false,
template: {},
},
},
{
widgetId: "list2",
type: "LIST_WIDGET",
widgetName: "List2",
parentId: "0",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
version: 16,
disablePropertyPane: false,
template: {},
},
[
{
widgetId: "list2",
parentId: "0",
list: [
{
widgetId: "list2",
type: "LIST_WIDGET",
widgetName: "List2",
parentId: "0",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
version: 16,
disablePropertyPane: false,
template: {},
},
],
},
],
);
expect(result?.type).toStrictEqual("LIST_WIDGET");
});
it("should return widgets after executing updateListWidgetPropertiesOnChildDelete", () => {
const result = updateListWidgetPropertiesOnChildDelete(
{
list1: {
widgetId: "list1",
type: "LIST_WIDGET",
widgetName: "List1",
parentId: "0",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
version: 16,
disablePropertyPane: false,
template: {},
enhancements: {},
dynamicBindingPathList: [{ key: "template.ButtonWidget1.text" }],
dynamicTriggerPathList: [
{
key: "template.ButtonWidget1.onClick",
},
],
},
buttonWidget1: {
type: "BUTTON_WIDGET",
widgetId: "buttonWidget1",
widgetName: "buttonWidget1",
version: 16,
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
renderMode: "CANVAS",
isLoading: false,
parentId: "list1",
},
0: {
type: "CANVAS_WIDGET",
widgetId: "0",
widgetName: "MainContainer",
version: 16,
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
renderMode: "CANVAS",
isLoading: false,
parentId: "list1",
},
},
"buttonWidget1",
"ButtonWidget1",
);
const expected = updateListWidgetPropertiesOnChildDelete(
{
list1: {
widgetId: "list1",
type: "LIST_WIDGET",
widgetName: "List1",
parentId: "0",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
version: 16,
disablePropertyPane: false,
template: {},
enhancements: {},
dynamicBindingPathList: [],
dynamicTriggerPathList: [],
},
buttonWidget1: {
type: "BUTTON_WIDGET",
widgetId: "buttonWidget1",
widgetName: "buttonWidget1",
version: 16,
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
renderMode: "CANVAS",
isLoading: false,
parentId: "list1",
},
0: {
type: "CANVAS_WIDGET",
widgetId: "0",
widgetName: "MainContainer",
version: 16,
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
renderMode: "CANVAS",
isLoading: false,
parentId: "list1",
},
},
"buttonWidget1",
"ButtonWidget1",
);
expect(result).toStrictEqual(expected);
});
it("should purge orphaned dynamicTriggerPaths and dynamicBindingPaths from widget", () => {
const input = {
dynamicBindingPathList: [
{ key: "primaryColumns.name.computedValue" },
{ key: "primaryColumns.name.fontStyle" },
{ key: "primaryColumns.name.nonExistentPath" },
{ key: "nonExistentKey" },
],
dynamicTriggerPathList: [
{ key: "primaryColumns.name.onClick" },
{ key: "primaryColumns.name.nonExistentPath" },
{ key: "nonExistentKey" },
],
primaryColumns: {
name: {
computedValue: "{{currentRow.something}}",
fontStyle: "bold",
onClick: "{{showAlert('message', 'error')}}",
},
},
};
const expected = {
dynamicBindingPathList: [
{ key: "primaryColumns.name.computedValue" },
{ key: "primaryColumns.name.fontStyle" },
],
dynamicTriggerPathList: [{ key: "primaryColumns.name.onClick" }],
primaryColumns: {
name: {
computedValue: "{{currentRow.something}}",
fontStyle: "bold",
onClick: "{{showAlert('message', 'error')}}",
},
},
};
const result = purgeOrphanedDynamicPaths(input as any as WidgetProps);
expect(result).toStrictEqual(expected);
});
it("should return boundaries of selected Widgets", () => {
const selectedWidgets = [
{
id: "1234",
topRow: 10,
leftColumn: 20,
rightColumn: 45,
bottomRow: 40,
},
{
id: "1233",
topRow: 45,
leftColumn: 30,
rightColumn: 60,
bottomRow: 70,
},
] as any as WidgetProps[];
expect(getBoundariesFromSelectedWidgets(selectedWidgets)).toEqual({
totalWidth: 40,
totalHeight: 60,
maxThickness: 30,
topMostRow: 10,
leftMostColumn: 20,
});
});
describe("test getSnappedGrid", () => {
it("should return snapGrids for a ContainerWidget", () => {
const canvasWidget = {
widgetId: "1234",
type: "CONTAINER_WIDGET",
noPad: true,
} as any as WidgetProps;
expect(getSnappedGrid(canvasWidget, 250)).toEqual({
padding: 4,
snapGrid: {
snapColumnSpace: 3.78125,
snapRowSpace: 10,
},
});
});
it("should return snapGrids for non ContainerWidget", () => {
const canvasWidget = {
widgetId: "1234",
type: "LIST_WIDGET",
noPad: false,
} as any as WidgetProps;
expect(getSnappedGrid(canvasWidget, 250)).toEqual({
padding: 10,
snapGrid: {
snapColumnSpace: 3.59375,
snapRowSpace: 10,
},
});
});
});
it("should test changeIdsOfPastePositions", () => {
const newPastingPositionMap = {
"1234": {
id: "1234",
left: 10,
right: 20,
top: 10,
bottom: 20,
},
"1235": {
id: "1235",
left: 11,
right: 22,
top: 11,
bottom: 22,
},
};
expect(changeIdsOfPastePositions(newPastingPositionMap)).toEqual([
{
id: "1",
left: 10,
right: 20,
top: 10,
bottom: 20,
},
{
id: "2",
left: 11,
right: 22,
top: 11,
bottom: 22,
},
]);
});
it("should offset widgets vertically so that it doesn't overlap with selected widgets", () => {
const selectedWidgets = [
{
id: "1234",
top: 10,
left: 20,
right: 45,
bottom: 40,
},
{
id: "1233",
top: 45,
left: 30,
right: 60,
bottom: 70,
},
{
id: "1235",
topRow: 80,
left: 10,
right: 50,
bottom: 100,
},
] as OccupiedSpace[];
const copiedWidgets = [
{
id: "1234",
top: 10,
left: 20,
right: 45,
bottom: 40,
},
{
id: "1233",
top: 45,
left: 30,
right: 60,
bottom: 70,
},
] as any as OccupiedSpace[];
expect(
getVerticallyAdjustedPositions(copiedWidgets, selectedWidgets, 30),
).toEqual({
"1234": {
id: "1234",
top: 71,
left: 20,
right: 45,
bottom: 101,
},
"1233": {
id: "1233",
top: 106,
left: 30,
right: 60,
bottom: 131,
},
});
});
it("should test getNewPositionsForCopiedWidgets", () => {
const copiedGroups = [
{
widgetId: "1234",
list: [
{
topRow: 10,
leftColumn: 20,
rightColumn: 45,
bottomRow: 40,
},
],
},
{
widgetId: "1235",
list: [
{
topRow: 45,
leftColumn: 25,
rightColumn: 40,
bottomRow: 80,
},
],
},
] as any as CopiedWidgetGroup[];
expect(
getNewPositionsForCopiedWidgets(copiedGroups, 10, 40, 20, 10),
).toEqual([
{
id: "1234",
top: 40,
left: 10,
right: 35,
bottom: 70,
},
{
id: "1235",
top: 75,
left: 15,
right: 30,
bottom: 110,
},
]);
});
it("should test getPastePositionMapFromMousePointer", () => {
const copiedGroups = [
{
widgetId: "1234",
list: [
{
topRow: 10,
leftColumn: 20,
rightColumn: 45,
bottomRow: 40,
},
],
},
{
widgetId: "1235",
list: [
{
topRow: 45,
leftColumn: 25,
rightColumn: 40,
bottomRow: 80,
},
],
},
] as any as CopiedWidgetGroup[];
expect(
getPastePositionMapFromMousePointer(copiedGroups, 10, 40, 20, 10),
).toEqual({
"1234": {
id: "1234",
top: 40,
left: 10,
right: 35,
bottom: 70,
},
"1235": {
id: "1235",
top: 75,
left: 15,
right: 30,
bottom: 110,
},
});
});
it("should test getReflowedPositions", () => {
const widgets = {
"1234": {
widgetId: "1234",
topRow: 40,
leftColumn: 10,
rightColumn: 35,
bottomRow: 70,
} as FlattenedWidgetProps,
"1233": {
widgetId: "1233",
topRow: 45,
leftColumn: 30,
rightColumn: 60,
bottomRow: 70,
} as FlattenedWidgetProps,
"1235": {
widgetId: "1235",
topRow: 75,
leftColumn: 15,
rightColumn: 30,
bottomRow: 110,
} as FlattenedWidgetProps,
};
const gridProps = {
parentRowSpace: 10,
parentColumnSpace: 10,
maxGridColumns: 64,
};
const reflowingWidgets = {
"1234": {
X: 30,
width: 200,
},
"1235": {
X: 40,
width: 250,
Y: 50,
height: 250,
},
};
expect(getReflowedPositions(widgets, gridProps, reflowingWidgets)).toEqual({
"1234": {
widgetId: "1234",
topRow: 40,
leftColumn: 13,
rightColumn: 33,
bottomRow: 70,
},
"1233": {
widgetId: "1233",
topRow: 45,
leftColumn: 30,
rightColumn: 60,
bottomRow: 70,
},
"1235": {
widgetId: "1235",
topRow: 80,
leftColumn: 19,
rightColumn: 44,
bottomRow: 105,
},
});
});
it("should test getWidgetsFromIds", () => {
const widgets = {
"1234": {
widgetId: "1234",
topRow: 40,
leftColumn: 10,
rightColumn: 35,
bottomRow: 70,
} as FlattenedWidgetProps,
"1233": {
widgetId: "1233",
topRow: 45,
leftColumn: 30,
rightColumn: 60,
bottomRow: 70,
} as FlattenedWidgetProps,
"1235": {
widgetId: "1235",
topRow: 75,
leftColumn: 15,
rightColumn: 30,
bottomRow: 110,
} as FlattenedWidgetProps,
};
expect(getWidgetsFromIds(["1235", "1234", "1237"], widgets)).toEqual([
{
widgetId: "1235",
topRow: 75,
leftColumn: 15,
rightColumn: 30,
bottomRow: 110,
},
{
widgetId: "1234",
topRow: 40,
leftColumn: 10,
rightColumn: 35,
bottomRow: 70,
},
]);
});
it("should test checkForListWidgetInCopiedWidgets", () => {
//if copying list widget onto list widget
expect(
checkForListWidgetInCopiedWidgets([
{
widgetId: "list2",
parentId: "0",
list: [
{
widgetId: "list2",
type: "LIST_WIDGET",
widgetName: "List2",
parentId: "0",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
version: 16,
disablePropertyPane: false,
template: {},
},
],
},
]),
).toBe(true);
//if copying container widget onto list widget
expect(
checkForListWidgetInCopiedWidgets([
{
widgetId: "container",
parentId: "0",
list: [
{
widgetId: "container",
type: "CONTAINER_WIDGET",
widgetName: "container",
parentId: "0",
renderMode: "CANVAS",
parentColumnSpace: 2,
parentRowSpace: 3,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 3,
isLoading: false,
listData: [],
version: 16,
disablePropertyPane: false,
template: {},
},
],
},
]),
).toBe(false);
});
});
describe("getValueFromTree - ", () => {
it("should test that value is correctly plucked from a valid path when object keys do not have dot", () => {
[
//Path that has a primitive value as leaf node
{
inputObj: {
path1: {
path2: "value",
},
someotherPath: "testValue",
},
path: "path1.path2",
output: "value",
defaultValue: "will not be returned",
},
//Path that has a non primitive value as leaf node
{
inputObj: {
path1: {
path2: {
path3: "value",
},
},
someotherPath: "testValue",
},
path: "path1.path2",
output: {
path3: "value",
},
defaultValue: "will not be returned",
},
//Path that traverse through an array with a primitive value as leaf node
{
inputObj: {
path1: [
{
path2: "value",
},
],
someotherPath: "testValue",
},
path: "path1.0.path2",
output: "value",
defaultValue: "will not be returned",
},
//Path that traverse through an array with a non primitive value as leaf node
{
inputObj: {
path1: [
{
path2: {
path3: "value",
},
},
],
someotherPath: "testValue",
},
path: "path1.0.path2",
output: {
path3: "value",
},
defaultValue: "will not be returned",
},
].forEach((testObj: any) => {
expect(
getValueFromTree(testObj.inputObj, testObj.path, testObj.defaultValue),
).toEqual(testObj.output);
});
});
it("should test that default value is returned for invalid path when object keys do not have dot", () => {
[
//Path that has a primitive value as leaf node
{
inputObj: {
path1: {
path2: "value",
},
someotherPath: "testValue",
},
path: "path1.path4",
output: "value",
defaultValue: "will be returned",
},
//Path that has a non primitive value as leaf node
{
inputObj: {
path1: {
path2: {
path3: "value",
},
},
someotherPath: "testValue",
},
path: "path4.path2",
output: {
path3: "value",
},
defaultValue: "will be returned",
},
//Path that traverse through an array with a primitive value as leaf node
{
inputObj: {
path1: [
{
path2: "value",
someotherPath: "testValue",
},
],
},
path: "path1.1.path2",
output: "value",
defaultValue: "will be returned",
},
//Path that traverse through an array with a non primitive value as leaf node
{
inputObj: {
path1: [
{
path2: {
path3: "value",
},
},
],
someotherPath: "testValue",
},
path: "path1.1.path2",
output: {
path3: "value",
},
defaultValue: "will be returned",
},
].forEach((testObj: any) => {
expect(
getValueFromTree(testObj.inputObj, testObj.path, testObj.defaultValue),
).toEqual(testObj.defaultValue);
});
});
it("should test that value is correctly plucked from a valid path when object keys have dot", () => {
[
//Path that has a primitive value as leaf node
{
inputObj: {
"path1.path2.path3": "value",
},
path: "path1.path2.path3",
output: "value",
defaultValue: "will not be returned",
},
//Path that has a primitive value as leaf node
{
inputObj: {
"path1.path2": {
path3: "value",
},
someotherPath: "testValue",
},
path: "path1.path2.path3",
output: "value",
defaultValue: "will not be returned",
},
//Path that has a primitive value as leaf node
{
inputObj: {
path1: {
"path2.path3": "value",
},
someotherPath: "testValue",
},
path: "path1.path2.path3",
output: "value",
defaultValue: "will not be returned",
},
//Path that has a primitive value as leaf node
{
inputObj: {
path1: {
path2: {
"path3.path4": "value",
},
},
someotherPath: "testValue",
},
path: "path1.path2.path3.path4",
output: "value",
defaultValue: "will not be returned",
},
//Path that has a primitive value as leaf node
{
inputObj: {
"path1.path2": {
"path3.path4": "value",
},
someotherPath: "testValue",
},
path: "path1.path2.path3.path4",
output: "value",
defaultValue: "will not be returned",
},
//Path that has a non primitive value as leaf node
{
inputObj: {
"path1.path2.path3": {
path4: "value",
},
someotherPath: "testValue",
},
path: "path1.path2.path3",
output: {
path4: "value",
},
defaultValue: "will not be returned",
},
//Path that has a non primitive value as leaf node
{
inputObj: {
path1: {
"path2.path3": {
path4: "value",
},
},
someotherPath: "testValue",
},
path: "path1.path2.path3",
output: {
path4: "value",
},
defaultValue: "will not be returned",
},
//Path that has a non primitive value as leaf node
{
inputObj: {
path1: {
path2: {
"path3.path4": {
path5: "value",
},
},
},
someotherPath: "testValue",
},
path: "path1.path2.path3.path4",
output: {
path5: "value",
},
defaultValue: "will not be returned",
},
//Path that traverse through an array with a primitive value as leaf node
{
inputObj: {
"path1.path2": [
{
path3: "value",
},
],
someotherPath: "testValue",
},
path: "path1.path2.0.path3",
output: "value",
defaultValue: "will not be returned",
},
//Path that traverse through an array with a primitive value as leaf node
{
inputObj: {
"path1.path2": [
{
path3: {
path4: "value",
},
},
],
someotherPath: "testValue",
},
path: "path1.path2.0.path3.path4",
output: "value",
defaultValue: "will not be returned",
},
//Path that traverse through an array with a primitive value as leaf node
{
inputObj: {
"path1.path2": [
{
"path3.path4": "value",
},
],
someotherPath: "testValue",
},
path: "path1.path2.0.path3.path4",
output: "value",
defaultValue: "will not be returned",
},
//Path that traverse through an array with a primitive value as leaf node
{
inputObj: {
"path1.path2": [
{
path3: [
{
path4: "value",
},
],
},
],
someotherPath: "testValue",
},
path: "path1.path2.0.path3.0.path4",
output: "value",
defaultValue: "will not be returned",
},
//Path that traverse through an array with a non primitive value as leaf node
{
inputObj: {
"path1.path2": [
{
path3: {
path4: "value",
},
},
],
someotherPath: "testValue",
},
path: "path1.path2.0.path3",
output: {
path4: "value",
},
defaultValue: "will not be returned",
},
//Path that traverse through an array with a non primitive value as leaf node
{
inputObj: {
"path1.path2.path3": [
{
path4: "value",
},
],
someotherPath: "testValue",
},
path: "path1.path2.path3.0",
output: {
path4: "value",
},
defaultValue: "will not be returned",
},
//Path that traverse through an array with a non primitive value as leaf node
{
inputObj: {
"path1.path2.path3": [
{
path4: [
{
path5: "value",
},
],
},
],
someotherPath: "testValue",
},
path: "path1.path2.path3.0.path4.0",
output: {
path5: "value",
},
defaultValue: "will not be returned",
},
//Path that traverse through an array with a non primitive value as leaf node
{
inputObj: {
"path1.path2.path3": [
{
"path4.path5": [
{
path6: "value",
},
],
},
],
},
path: "path1.path2.path3.0.path4.path5.0",
output: {
path6: "value",
},
defaultValue: "will not be returned",
},
{
inputObj: {
"path1.path2.path3": [
{
".path4.path5": [
{
path6: "value",
},
],
},
],
someotherPath: "testValue",
},
path: "path1.path2.path3.0..path4.path5.0",
output: {
path6: "value",
},
defaultValue: "will not be returned",
},
].forEach((testObj: any) => {
expect(
getValueFromTree(testObj.inputObj, testObj.path, testObj.defaultValue),
).toEqual(testObj.output);
});
});
it("should test that default value is returned for an invalid path when object keys have dot", () => {
[
//Path that has a primitive value as leaf node
{
inputObj: {
"path1.path2.path3": "value",
someotherPath: "testValue",
},
path: "path1.path2.path4",
output: "value",
defaultValue: "will be returned",
},
//Path that has a primitive value as leaf node
{
inputObj: {
"path1.path2": {
path3: "value",
},
someotherPath: "testValue",
},
path: "path1.path3.path4",
output: "value",
defaultValue: "will be returned",
},
//Path that has a primitive value as leaf node
{
inputObj: {
path1: {
"path2.path3": "value",
},
someotherPath: "testValue",
},
path: "path1.path2",
output: "value",
defaultValue: "will be returned",
},
//Path that has a primitive value as leaf node
{
inputObj: {
path1: {
path2: {
"path3.path4": "value",
},
},
someotherPath: "testValue",
},
path: "path1.path2.path3",
output: "value",
defaultValue: "will be returned",
},
//Path that has a primitive value as leaf node
{
inputObj: {
"path1.path2": {
"path3.path4": "value",
},
someotherPath: "testValue",
},
path: "path1.path3.path4",
output: "value",
defaultValue: "will be returned",
},
//Path that has a non primitive value as leaf node
{
inputObj: {
"path1.path2.path3": {
path4: "value",
},
someotherPath: "testValue",
},
path: "path1.path2",
output: {
path4: "value",
},
defaultValue: "will be returned",
},
//Path that has a non primitive value as leaf node
{
inputObj: {
path1: {
"path2.path3": {
path4: "value",
},
},
someotherPath: "testValue",
},
path: "path1.path2",
output: {
path4: "value",
},
defaultValue: "will be returned",
},
//Path that has a non primitive value as leaf node
{
inputObj: {
path1: {
path2: {
"path3.path4": {
path5: "value",
},
},
},
someotherPath: "testValue",
},
path: "path2.path3.path4",
output: {
path5: "value",
},
defaultValue: "will be returned",
},
//Path that traverse through an array with a primitive value as leaf node
{
inputObj: {
"path1.path2": [
{
path3: "value",
},
],
someotherPath: "testValue",
},
path: "path1.path2.1.path3",
output: "value",
defaultValue: "will be returned",
},
//Path that traverse through an array with a primitive value as leaf node
{
inputObj: {
"path1.path2": [
{
path3: {
path4: "value",
},
},
],
someotherPath: "testValue",
},
path: "path1.path2.1.path3.path4",
output: "value",
defaultValue: "will be returned",
},
//Path that traverse through an array with a primitive value as leaf node
{
inputObj: {
"path1.path2": [
{
"path3.path4": "value",
},
],
someotherPath: "testValue",
},
path: "path1.path2.1.path3.path4",
output: "value",
defaultValue: "will be returned",
},
//Path that traverse through an array with a primitive value as leaf node
{
inputObj: {
"path1.path2": [
{
path3: [
{
path4: "value",
},
],
},
],
someotherPath: "testValue",
},
path: "path1.path2.2.path3.0.path4",
output: "value",
defaultValue: "will be returned",
},
//Path that traverse through an array with a non primitive value as leaf node
{
inputObj: {
"path1.path2": [
{
path3: {
path4: "value",
},
},
],
someotherPath: "testValue",
},
path: "path1.0.path3",
output: {
path4: "value",
},
defaultValue: "will be returned",
},
//Path that traverse through an array with a non primitive value as leaf node
{
inputObj: {
"path1.path2.path3": [
{
path4: "value",
},
],
},
path: "path1.path2.0",
output: {
path4: "value",
},
defaultValue: "will be returned",
},
//Path that traverse through an array with a non primitive value as leaf node
{
inputObj: {
"path1.path2.path3": [
{
path4: [
{
path5: "value",
},
],
},
],
},
path: "path1.path2.0.path4.0",
output: {
path5: "value",
},
defaultValue: "will be returned",
},
//Path that traverse through an array with a non primitive value as leaf node
{
inputObj: {
"path1.path2.path3": [
{
"path4.path5": [
{
path6: "value",
},
],
},
],
},
path: "path1.path2.path3.0.path4.0",
output: {
path6: "value",
},
defaultValue: "will be returned",
},
].forEach((testObj: any) => {
expect(
getValueFromTree(testObj.inputObj, testObj.path, testObj.defaultValue),
).toEqual(testObj.defaultValue);
});
});
it("should check that invalid path strucutre should return defaultValue", () => {
[
{
inputObj: {
path1: {
path2: {
path3: "value",
},
},
},
path: "path1.path2..path3",
output: {
path6: "value",
},
defaultValue: "will be returned",
},
{
inputObj: {
path1: {
path2: [
{
path3: "value",
},
],
},
},
path: "path1.path2.0..path3",
output: {
path6: "value",
},
defaultValue: "will be returned",
},
].forEach((testObj: any) => {
expect(
getValueFromTree(testObj.inputObj, testObj.path, testObj.defaultValue),
).toEqual(testObj.defaultValue);
});
});
describe("test resizeCanvasToLowestWidget and resizePublishedMainCanvasToLowestWidget", () => {
const widgets = {
0: { bottomRow: 100, children: ["1", "2"], type: "CANVAS_WIDGET" },
1: {
bottomRow: 10,
children: ["3", "4"],
type: "CANVAS_WIDGET",
minHeight: 260,
},
2: { bottomRow: 35, children: [] },
3: { bottomRow: 15, children: [] },
4: { bottomRow: 20, children: [] },
} as unknown as CanvasWidgetsReduxState;
it("should trim canvas close to the lowest bottomRow of it's children widget", () => {
const currentWidgets = klona(widgets);
resizePublishedMainCanvasToLowestWidget(currentWidgets);
expect(currentWidgets["0"].bottomRow).toEqual(400);
});
});
});
|
1,210 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/sagas/WidgetSelectUtils.test.ts | import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsReducer";
import {
deselectAll,
pushPopWidgetSelection,
selectMultipleWidgets,
selectOneWidget,
shiftSelectWidgets,
unselectWidget,
} from "./WidgetSelectUtils";
describe("Wigdet selection methods", () => {
const allWidgetsMock: CanvasWidgetsReduxState = {
widgetId1: {
widgetId: "widgetId1",
parentId: "0",
type: "BUTTON_WIDGET",
widgetName: "Button1",
version: 0,
renderMode: "CANVAS",
parentColumnSpace: 0,
parentRowSpace: 0,
leftColumn: 0,
rightColumn: 0,
topRow: 0,
bottomRow: 0,
isLoading: false,
},
widgetId2: {
widgetId: "widgetId2",
parentId: "0",
type: "BUTTON_WIDGET",
widgetName: "Button2",
version: 0,
renderMode: "CANVAS",
parentColumnSpace: 0,
parentRowSpace: 0,
leftColumn: 0,
rightColumn: 0,
topRow: 0,
bottomRow: 0,
isLoading: false,
},
widgetId3: {
widgetId: "widgetId3",
parentId: "1",
type: "BUTTON_WIDGET",
widgetName: "Button3",
version: 0,
renderMode: "CANVAS",
parentColumnSpace: 0,
parentRowSpace: 0,
leftColumn: 0,
rightColumn: 0,
topRow: 0,
bottomRow: 0,
isLoading: false,
},
};
describe("Deselect", () => {
it("returns an empty selection", () => {
const result = deselectAll([]);
expect(result).toStrictEqual([]);
});
it("will error out when request has any widgets", () => {
expect(() => deselectAll(["any"])).toThrow("Wrong payload supplied");
});
});
describe("Select One", () => {
it("returns a selection", () => {
const result = selectOneWidget(["widgetId"]);
expect(result).toStrictEqual(["widgetId"]);
});
it("will error out when wrong payload supplied", () => {
expect(() => selectOneWidget([])).toThrow("Wrong payload supplied");
expect(() => selectOneWidget(["widgetId1", "widgetId2"])).toThrow(
"Wrong payload supplied",
);
});
});
describe("Select Multiple", () => {
it("returns a selection", () => {
const result = selectMultipleWidgets(
["widgetId1", "widgetId2"],
allWidgetsMock,
);
expect(result).toStrictEqual(["widgetId1", "widgetId2"]);
});
it("returns no selection if widgets are not siblings", () => {
const result = selectMultipleWidgets(
["widgetId1", "widgetId3"],
allWidgetsMock,
);
expect(result).toBeUndefined();
});
});
describe("Shift Select", () => {
it("forward selection", () => {
const result = shiftSelectWidgets(
["w5"],
["w1", "w2", "w3", "w4", "w5"],
["w1"],
"w1",
);
expect(result).toStrictEqual(["w1", "w5", "w2", "w3", "w4"]);
});
it("backwards selection", () => {
const result = shiftSelectWidgets(
["w2"],
["w1", "w2", "w3", "w4", "w5"],
["w5"],
"w5",
);
expect(result).toStrictEqual(["w5", "w2", "w3", "w4"]);
});
it("appended selection on overlap", () => {
const result = shiftSelectWidgets(
["w1"],
["w1", "w2", "w3", "w4", "w5"],
["w5", "w3"],
"w5",
);
expect(result).toStrictEqual(["w5", "w3", "w1", "w2", "w4"]);
});
it("a single selection when last selected is not a sibling", () => {
const result = shiftSelectWidgets(
["w2"],
["w1", "w2", "w3", "w4", "w5"],
["w7"],
"w7",
);
expect(result).toStrictEqual(["w2"]);
});
it("unselect when already selected", () => {
const result = shiftSelectWidgets(
["w2"],
["w1", "w2", "w3", "w4", "w5"],
["w1", "w2"],
"w2",
);
expect(result).toStrictEqual(["w1"]);
});
});
describe("Push Pop Select", () => {
it("adds a selection", () => {
const result = pushPopWidgetSelection(
["w1"],
["w2", "w3"],
["w1", "w2", "w3"],
);
expect(result).toStrictEqual(["w2", "w3", "w1"]);
});
it("removes a selection", () => {
const result = pushPopWidgetSelection(
["w1"],
["w2", "w1"],
["w1", "w2", "w3"],
);
expect(result).toStrictEqual(["w2"]);
});
it("removes other if new selection is not a sibling", () => {
const result = pushPopWidgetSelection(["w1"], ["w3", "w4"], ["w1", "w2"]);
expect(result).toStrictEqual(["w1"]);
});
});
describe("UnSelect", () => {
it("returns selection without the widget", () => {
const result = unselectWidget(["w1"], ["w1", "w2", "w3"]);
expect(result).toStrictEqual(["w2", "w3"]);
});
it("returns selection even if not selected", () => {
const result = unselectWidget(["w1"], ["w2", "w3"]);
expect(result).toStrictEqual(["w2", "w3"]);
});
});
});
|
1,214 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/sagas/helper.test.ts | /**
* @jest-environment jsdom
*/
import { TextEncoder, TextDecoder } from "util";
Object.assign(global, { TextDecoder, TextEncoder });
import {
enhanceRequestPayloadWithEventData,
cleanValuesInObjectForHashing,
generateHashFromString,
} from "sagas/helper";
describe("tests the redux saga helper functions", () => {
it("tests the enhanceRequestPayloadWithEventData function", () => {
const inputs = [
{ payload: { id: "xyz" }, type: "COPY_ACTION_INIT" },
{ payload: { id: "xyz" }, type: "DUMMY_ACTION" },
{
payload: {
id: "xyz",
eventData: { analyticsData: { originalActionId: "abc" } },
},
type: "COPY_ACTION_INIT",
},
{ payload: {}, type: "COPY_ACTION_INIT" },
{ payload: {}, type: "" },
{ payload: undefined, type: "" },
];
const outputs = [
{ id: "xyz", eventData: { analyticsData: { originalActionId: "xyz" } } },
{ id: "xyz" },
{ id: "xyz", eventData: { analyticsData: { originalActionId: "abc" } } },
{},
{},
undefined,
];
inputs.forEach((input, index) => {
expect(
enhanceRequestPayloadWithEventData(input.payload, input.type),
).toStrictEqual(outputs[index]);
});
});
it("tests the cleanValuesInObjectForHashing function", () => {
const inputs = [
{
body: 'UPDATE public.users SET "id"= \'{{Table2.updatedRow.id}}\', "gender"= \'{{Table2.updatedRow.gender}}\', "latitude"= \'{{Table2.updatedRow.latitude}}\', "longitude"= \'{{Table2.updatedRow.longitude}}\', "dob"= \'{{Table2.updatedRow.dob}}\', "phone"= \'{{Table2.updatedRow.phone}}\', "email"= \'{{Table2.updatedRow.email}}\', "image"= \'{{Table2.updatedRow.image}}\', "country"= \'{{Table2.updatedRow.country}}\', "name"= \'{{Table2.updatedRow.name}}\' WHERE "id"= {{Table2.updatedRow.id}};',
},
{
paginationType: "NONE",
encodeParamsToggle: true,
body: 'UPDATE public.users SET "id"= \'{{Table2.updatedRow.id}}\', "gender"= \'{{Table2.updatedRow.gender}}\', "latitude"= \'{{Table2.updatedRow.latitude}}\', "longitude"= \'{{Table2.updatedRow.longitude}}\', "dob"= \'{{Table2.updatedRow.dob}}\', "phone"= \'{{Table2.updatedRow.phone}}\', "email"= \'{{Table2.updatedRow.email}}\', "image"= \'{{Table2.updatedRow.image}}\', "country"= \'{{Table2.updatedRow.country}}\', "name"= \'{{Table2.updatedRow.name}}\' WHERE "id"= {{Table2.updatedRow.id}};',
selfReferencingDataPaths: [],
pluginSpecifiedTemplates: [{ value: false }],
},
{
paginationType: "NONE",
encodeParamsToggle: true,
selfReferencingDataPaths: [],
formData: {
aggregate: { limit: { data: "10" } },
smartSubstitution: { data: true },
insert: { documents: { data: "{{(Table3.newRow || {})}}" } },
command: { data: "INSERT" },
collection: { data: "movies" },
},
},
{
timeoutInMillisecond: 10000.0,
paginationType: "NONE",
encodeParamsToggle: true,
selfReferencingDataPaths: [],
formData: { pageSize: "100", command: "", sort: "" },
},
{
body: 'UPDATE public.users SET "id"= \'{{Table2.updatedRow.id}}\', "gender"= \'{{Table2.updatedRow.gender}}\', "latitude"= \'{{Table2.updatedRow.latitude}}\', "longitude"= \'{{Table2.updatedRow.longitude}}\', "dob"= \'{{Table2.updatedRow.dob}}\', "phone"= \'{{Table2.updatedRow.phone}}\', "email"= \'{{Table2.updatedRow.email}}\', "image"= \'{{Table2.updatedRow.image}}\', "country"= \'{{Table2.updatedRow.country}}\', "name"= \'{{Table2.updatedRow.name}}\' WHERE "id"= {{Table2.updatedRow.id}}; \n -- I am an SQL comment',
},
];
const outputs = [
{
body: `updatepublic.usersset"id"='',"gender"='',"latitude"='',"longitude"='',"dob"='',"phone"='',"email"='',"image"='',"country"='',"name"=''where"id"=;`,
},
{
paginationType: "none",
encodeParamsToggle: true,
body: `updatepublic.usersset"id"='',"gender"='',"latitude"='',"longitude"='',"dob"='',"phone"='',"email"='',"image"='',"country"='',"name"=''where"id"=;`,
selfReferencingDataPaths: [],
pluginSpecifiedTemplates: [{ value: false }],
},
{
paginationType: "none",
encodeParamsToggle: true,
selfReferencingDataPaths: [],
formData: {
aggregate: { limit: { data: "10" } },
smartSubstitution: { data: true },
insert: { documents: { data: "" } },
command: { data: "insert" },
collection: { data: "movies" },
},
},
{
timeoutInMillisecond: 10000.0,
paginationType: "none",
encodeParamsToggle: true,
selfReferencingDataPaths: [],
formData: { pageSize: "100", command: "", sort: "" },
},
{
body: `updatepublic.usersset"id"='',"gender"='',"latitude"='',"longitude"='',"dob"='',"phone"='',"email"='',"image"='',"country"='',"name"=''where"id"=;`,
},
];
inputs.forEach((input, index) => {
expect(cleanValuesInObjectForHashing(input)).toStrictEqual(
outputs[index],
);
});
});
it("tests the generateHashFromString function", async () => {
// verify that the same strings generate the same SHA1
const sameInputs = ["testString1", "testString1"];
const output1 = await generateHashFromString(sameInputs[0]);
const output2 = await generateHashFromString(sameInputs[1]);
expect(output1).toEqual(output2);
// verify that different strings generate different SHA1
const differentInputs = ["testString1", "testString2"];
const output3 = await generateHashFromString(differentInputs[0]);
const output4 = await generateHashFromString(differentInputs[1]);
expect(output3).not.toEqual(output4);
// verify that the SHA1 is the same in the future
// Note: There is something up with the algorithm, due to the it using
// ByteArrays and converting to hex strings
// If you google, the SHA1 for "testString", you get "956265657d0b637ef65b9b59f9f858eecf55ed6a"
// Nevertheless, for our purposes, this is fine
const testString = "testString";
const sha1fortestString = "21b695cef037e9a8e0b3edccac3e5e58271edf22";
const output = await generateHashFromString(testString);
expect(output).toEqual(sha1fortestString);
});
it("tests the generateHashFromString function with a complex object", async () => {
const input1 = {
body: 'UPDATE public.users SET "id"= \'{{Table2.updatedRow.id}}\', "gender"= \'{{Table2.updatedRow.gender}}\', "latitude"= \'{{Table2.updatedRow.latitude}}\', "longitude"= \'{{Table2.updatedRow.longitude}}\', "dob"= \'{{Table2.updatedRow.dob}}\', "phone"= \'{{Table2.updatedRow.phone}}\', "email"= \'{{Table2.updatedRow.email}}\', "image"= \'{{Table2.updatedRow.image}}\', "country"= \'{{Table2.updatedRow.country}}\', "name"= \'{{Table2.updatedRow.name}}\' WHERE "id"= {{Table2.updatedRow.id}}; \n -- I am an SQL comment',
};
const input2 = {
body: `UPDATE public.users SET "id"= \'{{Table2.updatedRow.id}}\', "gender"= \'{{Table2.updatedRow.gender}}\', "latitude"= \'{{Table2.updatedRow.latitude}}\', "longitude"= \'{{Table2.updatedRow.longitude}}\', "dob"= \'{{Table2.updatedRow.dob}}\', "phone"= \'{{Table2.updatedRow.phone}}\', "email"= \'{{Table2.updatedRow.email}}\', "image"= \'{{(() => { return "myvalue" })}}\', "country"= \'{{Table2.updatedRow.country}}\', "name"= \'{{GetQuery.updatedRow.name}}\' WHERE "id"= {{Table5.updatedRow.id}};`,
};
const cleanObjectInput1 = cleanValuesInObjectForHashing(input1);
const cleanObjectInput2 = cleanValuesInObjectForHashing(input2);
const hash1 = await generateHashFromString(
JSON.stringify(cleanObjectInput1),
);
const hash2 = await generateHashFromString(
JSON.stringify(cleanObjectInput2),
);
expect(hash1).toEqual(hash2);
});
});
|
1,223 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/sagas | petrpan-code/appsmithorg/appsmith/app/client/src/sagas/ActionExecution/PluginActionSagaUtils.test.ts | import { put } from "redux-saga/effects";
import { setDefaultActionDisplayFormat } from "./PluginActionSagaUtils";
const actionid = "test-id";
const plugin: any = {
id: "test-plugin",
name: "Test",
type: "API",
packageName: "test-package",
uiComponent: "ApiEditorForm",
datasourceComponent: "RestAPIDatasourceForm",
templates: {
test: "test",
},
responseType: "JSON",
};
describe("PluginActionSagasUtils", () => {
it("should set the default action display format without any bugs as long as dataTypes is there", () => {
const payload = {
body: [],
headers: {
headers: ["test-headers"],
},
statusCode: "200",
dataTypes: [
{
dataType: "JSON",
},
],
duration: "1000",
size: "10kb",
};
const generator = setDefaultActionDisplayFormat(actionid, plugin, payload);
expect(generator.next().value).toEqual(
put({
type: "SET_ACTION_RESPONSE_DISPLAY_FORMAT",
payload: {
id: "test-id",
field: "responseDisplayFormat",
value: "JSON",
},
}),
);
});
it("If the response type is not present in the dataType, then it should pick the first dataType in the array", () => {
const payload = {
body: [],
headers: {
headers: ["test-headers"],
},
statusCode: "200",
dataTypes: [
{
dataType: "TABLE",
},
{
dataType: "RAW",
},
],
duration: "1000",
size: "10kb",
};
const generator = setDefaultActionDisplayFormat(actionid, plugin, payload);
expect(generator.next().value).toEqual(
put({
type: "SET_ACTION_RESPONSE_DISPLAY_FORMAT",
payload: {
id: "test-id",
field: "responseDisplayFormat",
value: "TABLE",
},
}),
);
});
it("If dataType is an empty array, then no action should be dispatched and no bugs should happen", () => {
const payload = {
body: [],
headers: {
headers: ["test-headers"],
},
statusCode: "200",
dataTypes: [],
duration: "1000",
size: "10kb",
};
const generator = setDefaultActionDisplayFormat(actionid, plugin, payload);
expect(generator.next().value).toBeUndefined();
});
});
|
1,225 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/sagas | petrpan-code/appsmithorg/appsmith/app/client/src/sagas/ActionExecution/PostMessage.test.ts | import { postMessageSaga, executePostMessage } from "./PostMessageSaga";
import { spawn } from "redux-saga/effects";
import { runSaga } from "redux-saga";
describe("PostMessageSaga", () => {
describe("postMessageSaga function", () => {
const generator = postMessageSaga({
type: "POST_MESSAGE",
payload: {
message: "hello world",
source: "window",
targetOrigin: "https://dev.appsmith.com",
},
});
it("executes postMessageSaga with the payload and trigger meta", () => {
expect(generator.next().value).toStrictEqual(
spawn(executePostMessage, {
message: "hello world",
source: "window",
targetOrigin: "https://dev.appsmith.com",
}),
);
});
it("should be done on next iteration", () => {
expect(generator.next().done).toBeTruthy();
});
});
describe("executePostMessage function", () => {
it("calls window.parent with message and target origin", () => {
const dispatched: any[] = [];
const postMessage = jest.spyOn(window.parent, "postMessage");
runSaga(
{
dispatch: (action) => dispatched.push(action),
},
executePostMessage,
{
message: "hello world",
source: "window",
targetOrigin: "https://dev.appsmith.com",
},
);
expect(postMessage).toHaveBeenCalledWith(
"hello world",
"https://dev.appsmith.com",
undefined,
);
expect(dispatched).toEqual([]);
});
});
});
|
1,232 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/sagas | petrpan-code/appsmithorg/appsmith/app/client/src/sagas/ActionExecution/geolocationSaga.test.ts | import { call, put } from "redux-saga/effects";
import {
extractGeoLocation,
getCurrentLocationSaga,
getUserLocation,
} from "./geolocationSaga";
import { setUserCurrentGeoLocation } from "actions/browserRequestActions";
import { logActionExecutionError } from "./errorUtils";
const mockFn = jest.fn();
jest.mock("./errorUtils.ts", () => ({
logActionExecutionError: (payload: any) => mockFn(payload),
}));
describe("getCurrentLocationSaga", () => {
beforeAll(() => {
class GeolocationPositionErrorClass extends Error {
readonly code!: number;
readonly message!: string;
readonly PERMISSION_DENIED!: number;
readonly POSITION_UNAVAILABLE!: number;
readonly TIMEOUT!: number;
constructor(msg?: string) {
super(msg);
}
}
Object.defineProperty(global, "GeolocationPositionError", {
value: GeolocationPositionErrorClass,
});
});
it("should call the onSuccess callback with the current location", () => {
const options = { enableHighAccuracy: true };
const payload = {
options,
};
const trigger = {
type: "GET_CURRENT_LOCATION" as const,
payload,
};
const location = {
coords: {
accuracy: 0,
altitude: 0,
altitudeAccuracy: 0,
heading: 0,
latitude: 0,
longitude: 0,
speed: 0,
},
timestamp: 0,
};
const currentLocation = extractGeoLocation(location);
const iter = getCurrentLocationSaga(trigger);
expect(iter.next().value).toEqual(call(getUserLocation, payload.options));
// For setUserCurrentGeoLocation yield
// Pass the location that should be returned in the first yield
expect(iter.next(location).value).toEqual(
put(setUserCurrentGeoLocation(currentLocation)),
);
expect(iter.next().done).toBe(true);
});
it("should call the onError callback when there is an error", () => {
const options = { enableHighAccuracy: true };
const payload = {
options,
};
const trigger = {
type: "GET_CURRENT_LOCATION" as const,
payload,
};
const iter = getCurrentLocationSaga(trigger);
expect(iter.next().value).toEqual(call(getUserLocation, payload.options));
expect(iter.next().value).toEqual(
call(
logActionExecutionError,
"Cannot read properties of undefined (reading 'coords')",
true,
),
);
expect(iter.next().done).toBe(true);
});
});
|
1,243 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/sagas | petrpan-code/appsmithorg/appsmith/app/client/src/sagas/__tests__/initSagas.test.ts | import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
import { APP_MODE } from "entities/App";
import type AppEngine from "entities/Engine";
import AppEngineFactory from "entities/Engine/factory";
import { call } from "redux-saga/effects";
import { startAppEngine } from "sagas/InitSagas";
jest.mock("../../api/Api", () => ({
__esModule: true,
default: class Api {},
}));
describe("tests the sagas in initSagas", () => {
it("tests the order of execute in startAppEngine", () => {
const action = {
type: ReduxActionTypes.INITIALIZE_EDITOR,
payload: {
applicationId: "appId",
pageId: "pageId",
mode: APP_MODE.EDIT,
},
};
const gen = startAppEngine(action);
const engine: AppEngine = AppEngineFactory.create(
APP_MODE.EDIT,
APP_MODE.EDIT,
);
expect(JSON.stringify(gen.next().value)).toStrictEqual(
JSON.stringify(call(engine.setupEngine, action.payload)),
);
expect(JSON.stringify(gen.next().value)).toStrictEqual(
JSON.stringify(call(engine.loadAppData, action.payload)),
);
expect(
JSON.stringify(
gen.next({
applicationId: action.payload.applicationId,
toLoadPageId: action.payload.pageId,
}).value,
),
).toStrictEqual(
JSON.stringify(
call(engine.loadAppURL, action.payload.pageId, action.payload.pageId),
),
);
expect(JSON.stringify(gen.next().value)).toStrictEqual(
JSON.stringify(
call(
engine.loadAppEntities,
action.payload.pageId,
action.payload.applicationId,
),
),
);
expect(JSON.stringify(gen.next().value)).toStrictEqual(
JSON.stringify(call(engine.loadGit, action.payload.applicationId)),
);
expect(JSON.stringify(gen.next().value)).toStrictEqual(
JSON.stringify(call(engine.completeChore)),
);
});
});
|
1,246 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/sagas | petrpan-code/appsmithorg/appsmith/app/client/src/sagas/autoHeightSagas/helpers.test.ts | import { mutation_setPropertiesToUpdate } from "./helpers";
describe("auto height saga helpers", () => {
it("When property exists, it should update correctly", () => {
const propertiesToUpdate = {
x: 50,
y: "newValue",
};
const originalObject = {
key1: [
{
propertyPath: "z",
propertyValue: 20,
},
],
};
const expectedResult = {
key1: [
{
propertyPath: "z",
propertyValue: 20,
},
{
propertyPath: "x",
propertyValue: 50,
},
{
propertyPath: "y",
propertyValue: "newValue",
},
],
};
const result = mutation_setPropertiesToUpdate(
originalObject,
"key1",
propertiesToUpdate,
);
expect(result).toStrictEqual(expectedResult);
});
it("When property does not exist, it should update correctly", () => {
const propertiesToUpdate = {
x: 50,
y: "newValue",
};
const originalObject = {
key1: [
{
propertyPath: "z",
propertyValue: 20,
},
],
};
const expectedResult = {
key1: [
{
propertyPath: "z",
propertyValue: 20,
},
],
key2: [
{
propertyPath: "x",
propertyValue: 50,
},
{
propertyPath: "y",
propertyValue: "newValue",
},
],
};
const result = mutation_setPropertiesToUpdate(
originalObject,
"key2",
propertiesToUpdate,
);
expect(result).toStrictEqual(expectedResult);
});
});
|
1,266 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/selectors/debuggerSelectors.test.ts | import { Severity, ENTITY_TYPE, LOG_CATEGORY } from "entities/AppsmithConsole";
import LOG_TYPE from "entities/AppsmithConsole/logtype";
import type { DataTree } from "entities/DataTree/dataTreeTypes";
import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsReducer";
import { PropertyEvaluationErrorType } from "utils/DynamicBindingUtils";
import { getFilteredErrors } from "./debuggerSelectors";
describe("getFilteredErrors", () => {
it("hides error from hidden widget in main canvas", () => {
const TestData = {
debuggerErrors: {
"main_input_id-defaultText": {
id: "main_input_id-defaultText",
logType: LOG_TYPE.EVAL_ERROR,
text: "The value at defaultText is invalid",
messages: [
{
message: {
name: "TypeError",
message:
"Cannot read properties of undefined (reading 'users')",
},
type: PropertyEvaluationErrorType.PARSE,
},
],
source: {
id: "main_input_id",
name: "main_input",
type: ENTITY_TYPE.WIDGET,
propertyPath: "defaultText",
},
state: {
defaultText: "",
},
analytics: {
widgetType: "INPUT_WIDGET_V2",
},
severity: Severity.ERROR,
timestamp: "02:40:10",
category: LOG_CATEGORY.PLATFORM_GENERATED,
isExpanded: false,
},
},
canvasWidgets: {
main_input_id: {
widgetName: "main_input",
type: "INPUT_WIDGET_V2",
widgetId: "main_input_id",
parentId: "0",
},
},
dataTree: {
main_input: {
isVisible: false,
parentId: "0",
widgetId: "main_input_id",
type: "INPUT_WIDGET_V2",
ENTITY_TYPE: ENTITY_TYPE.WIDGET,
},
},
expectedResult: {},
};
const result = getFilteredErrors.resultFunc(
TestData.debuggerErrors,
false,
TestData.canvasWidgets as unknown as CanvasWidgetsReduxState,
TestData.dataTree as unknown as DataTree,
);
expect(result).toStrictEqual(TestData.expectedResult);
});
it("hides error from widget in closed modal", () => {
const TestData = {
debuggerErrors: {
"modal_input-defaultText": {
id: "modal_input-defaultText",
logType: LOG_TYPE.EVAL_ERROR,
text: "The value at defaultText is invalid",
messages: [
{
message: {
name: "TypeError",
message:
"Cannot read properties of undefined (reading 'users')",
},
type: PropertyEvaluationErrorType.PARSE,
},
],
source: {
id: "modal_input",
name: "ModalInput",
type: ENTITY_TYPE.WIDGET,
propertyPath: "defaultText",
},
state: {
defaultText: "",
},
analytics: {
widgetType: "INPUT_WIDGET_V2",
},
severity: Severity.ERROR,
category: LOG_CATEGORY.PLATFORM_GENERATED,
timestamp: "02:40:10",
isExpanded: false,
},
},
canvasWidgets: {
modal_input: {
widgetName: "ModalInput",
type: "INPUT_WIDGET_V2",
widgetId: "modal_input",
parentId: "modal_canvas_id",
},
modal_canvas_id: {
widgetName: "ModalCanvas",
type: "CANVAS_WIDGET",
widgetId: "modal_canvas_id",
parentId: "modal1_id",
},
modal1_id: {
widgetName: "Modal1",
type: "MODAL_WIDGET",
widgetId: "modal1_id",
parentId: "0",
},
},
dataTree: {
ModalInput: {
isVisible: true,
parentId: "modal_canvas_id",
widgetId: "modal_input",
type: "INPUT_WIDGET_V2",
ENTITY_TYPE: ENTITY_TYPE.WIDGET,
},
ModalCanvas: {
isVisible: true,
type: "CANVAS_WIDGET",
widgetId: "modal_canvas_id",
parentId: "modal1_id",
ENTITY_TYPE: ENTITY_TYPE.WIDGET,
},
Modal1: {
isVisible: false,
type: "MODAL_WIDGET",
widgetId: "modal1_id",
parentId: "0",
ENTITY_TYPE: ENTITY_TYPE.WIDGET,
},
},
expectedResult: {},
};
const result = getFilteredErrors.resultFunc(
TestData.debuggerErrors,
false,
TestData.canvasWidgets as unknown as CanvasWidgetsReduxState,
TestData.dataTree as unknown as DataTree,
);
expect(result).toStrictEqual(TestData.expectedResult);
});
it("hides error from widget in non-active tab", () => {
const TestData = {
debuggerErrors: {
"tab2_input-defaultText": {
id: "tab2_input-defaultText",
logType: LOG_TYPE.EVAL_ERROR,
text: "The value at defaultText is invalid",
messages: [
{
message: {
name: "TypeError",
message:
"Cannot read properties of undefined (reading 'users')",
},
type: PropertyEvaluationErrorType.PARSE,
},
],
source: {
id: "tab2_input",
name: "Tab2Input",
type: ENTITY_TYPE.WIDGET,
propertyPath: "defaultText",
},
state: {
defaultText: "",
},
analytics: {
widgetType: "INPUT_WIDGET_V2",
},
severity: Severity.ERROR,
category: LOG_CATEGORY.PLATFORM_GENERATED,
timestamp: "02:40:10",
isExpanded: false,
},
},
canvasWidgets: {
tab1_id: {
tabId: "tab1",
widgetName: "Tab1Canvas",
type: "CANVAS_WIDGET",
tabName: "Tab 1",
widgetId: "tab1_id",
parentId: "tabs_widget_id",
},
tab2_input: {
widgetName: "Tab2Input",
type: "INPUT_WIDGET_V2",
widgetId: "tab2_input",
parentId: "tab2_id",
},
tab2_id: {
tabId: "tab2",
widgetName: "Tab2Canvas",
type: "CANVAS_WIDGET",
tabName: "Tab 2",
widgetId: "tab2_id",
parentId: "tabs_widget_id",
},
tabs_widget_id: {
widgetName: "Tabs1",
type: "TABS_WIDGET",
widgetId: "tabs_widget_id",
defaultTab: "Tab 1",
parentId: "0",
},
},
dataTree: {
Tab1Canvas: {
tabId: "tab1",
type: "CANVAS_WIDGET",
tabName: "Tab 1",
widgetId: "tab1_id",
isVisible: true,
parentId: "tabs_widget_id",
ENTITY_TYPE: "WIDGET",
},
Tab2Input: {
type: "INPUT_WIDGET_V2",
widgetId: "tab2_input",
isVisible: true,
parentId: "tab2_id",
ENTITY_TYPE: "WIDGET",
},
Tab2Canvas: {
tabId: "tab2",
tabName: "Tab 2",
widgetId: "tab2_id",
isVisible: true,
parentId: "tabs_widget_id",
ENTITY_TYPE: "WIDGET",
},
Tabs1: {
isVisible: true,
widgetName: "Tabs1",
type: "TABS_WIDGET",
widgetId: "tabs_widget_id",
defaultTab: "Tab 1",
parentId: "0",
selectedTab: "Tab 1",
ENTITY_TYPE: "WIDGET",
},
},
expectedResult: {},
};
const result = getFilteredErrors.resultFunc(
TestData.debuggerErrors,
false,
TestData.canvasWidgets as unknown as CanvasWidgetsReduxState,
TestData.dataTree as unknown as DataTree,
);
expect(result).toStrictEqual(TestData.expectedResult);
});
it("hides error from widget in active tab (hidden tab widget)", () => {
const TestData = {
debuggerErrors: {
"tab2_input-defaultText": {
id: "tab2_input-defaultText",
logType: LOG_TYPE.EVAL_ERROR,
text: "The value at defaultText is invalid",
messages: [
{
message: {
name: "TypeError",
message:
"Cannot read properties of undefined (reading 'users')",
},
type: PropertyEvaluationErrorType.PARSE,
},
],
source: {
id: "tab2_input",
name: "Tab2Input",
type: ENTITY_TYPE.WIDGET,
propertyPath: "defaultText",
},
state: {
defaultText: "",
},
analytics: {
widgetType: "INPUT_WIDGET_V2",
},
severity: Severity.ERROR,
category: LOG_CATEGORY.PLATFORM_GENERATED,
timestamp: "02:40:10",
isExpanded: false,
},
},
canvasWidgets: {
tab1_id: {
tabId: "tab1",
widgetName: "Tab1Canvas",
type: "CANVAS_WIDGET",
tabName: "Tab 1",
widgetId: "tab1_id",
parentId: "tabs_widget_id",
},
tab2_input: {
widgetName: "Tab2Input",
type: "INPUT_WIDGET_V2",
widgetId: "tab2_input",
parentId: "tab2_id",
},
tab2_id: {
tabId: "tab2",
widgetName: "Tab2Canvas",
type: "CANVAS_WIDGET",
tabName: "Tab 2",
widgetId: "tab2_id",
parentId: "tabs_widget_id",
},
tabs_widget_id: {
widgetName: "Tabs1",
type: "TABS_WIDGET",
widgetId: "tabs_widget_id",
defaultTab: "Tab 1",
parentId: "0",
},
},
dataTree: {
Tab1Canvas: {
tabId: "tab1",
type: "CANVAS_WIDGET",
tabName: "Tab 1",
widgetId: "tab1_id",
isVisible: true,
parentId: "tabs_widget_id",
ENTITY_TYPE: "WIDGET",
},
Tab2Input: {
type: "INPUT_WIDGET_V2",
widgetId: "tab2_input",
isVisible: true,
parentId: "tab2_id",
ENTITY_TYPE: "WIDGET",
},
Tab2Canvas: {
tabId: "tab2",
tabName: "Tab 2",
widgetId: "tab2_id",
isVisible: true,
parentId: "tabs_widget_id",
ENTITY_TYPE: "WIDGET",
},
Tabs1: {
isVisible: false,
widgetName: "Tabs1",
type: "TABS_WIDGET",
widgetId: "tabs_widget_id",
defaultTab: "Tab 1",
parentId: "0",
selectedTab: "Tab 2",
ENTITY_TYPE: "WIDGET",
},
},
expectedResult: {},
};
const result = getFilteredErrors.resultFunc(
TestData.debuggerErrors,
false,
TestData.canvasWidgets as unknown as CanvasWidgetsReduxState,
TestData.dataTree as unknown as DataTree,
);
expect(result).toStrictEqual(TestData.expectedResult);
});
it("hides error from widget in active tab (tab widget inside hidden container)", () => {
const TestData = {
debuggerErrors: {
"tab2_input-defaultText": {
id: "tab2_input-defaultText",
logType: LOG_TYPE.EVAL_ERROR,
text: "The value at defaultText is invalid",
messages: [
{
message: {
name: "TypeError",
message:
"Cannot read properties of undefined (reading 'users')",
},
type: PropertyEvaluationErrorType.PARSE,
},
],
source: {
id: "tab2_input",
name: "Tab2Input",
type: ENTITY_TYPE.WIDGET,
propertyPath: "defaultText",
},
state: {
defaultText: "",
},
analytics: {
widgetType: "INPUT_WIDGET_V2",
},
severity: Severity.ERROR,
category: LOG_CATEGORY.PLATFORM_GENERATED,
timestamp: "02:40:10",
isExpanded: false,
},
},
canvasWidgets: {
tab1_id: {
tabId: "tab1",
widgetName: "Tab1Canvas",
type: "CANVAS_WIDGET",
tabName: "Tab 1",
widgetId: "tab1_id",
parentId: "tabs_widget_id",
},
tab2_input: {
widgetName: "Tab2Input",
type: "INPUT_WIDGET_V2",
widgetId: "tab2_input",
parentId: "tab2_id",
},
tab2_id: {
tabId: "tab2",
widgetName: "Tab2Canvas",
type: "CANVAS_WIDGET",
tabName: "Tab 2",
widgetId: "tab2_id",
parentId: "tabs_widget_id",
},
tabs_widget_id: {
widgetName: "Tabs1",
type: "TABS_WIDGET",
widgetId: "tabs_widget_id",
defaultTab: "Tab 1",
parentId: "canvas_widget_id",
},
canvas_widget_id: {
widgetName: "ContainerCanvas",
type: "CANVAS_WIDGET",
widgetId: "canvas_widget_id",
parentId: "container1_id",
},
container1_id: {
widgetName: "Container1",
type: "CONTAINER_WIDGET",
widgetId: "container1_id",
parentId: "0",
},
},
dataTree: {
Tab1Canvas: {
tabId: "tab1",
type: "CANVAS_WIDGET",
tabName: "Tab 1",
widgetId: "tab1_id",
isVisible: true,
parentId: "tabs_widget_id",
ENTITY_TYPE: "WIDGET",
},
Tab2Input: {
type: "INPUT_WIDGET_V2",
widgetId: "tab2_input",
isVisible: true,
parentId: "tab2_id",
ENTITY_TYPE: "WIDGET",
},
Tab2Canvas: {
tabId: "tab2",
tabName: "Tab 2",
widgetId: "tab2_id",
isVisible: true,
parentId: "tabs_widget_id",
ENTITY_TYPE: "WIDGET",
},
Tabs1: {
isVisible: true,
widgetName: "Tabs1",
type: "TABS_WIDGET",
widgetId: "tabs_widget_id",
defaultTab: "Tab 1",
parentId: "canvas_widget_id",
selectedTab: "Tab 2",
ENTITY_TYPE: "WIDGET",
},
ContainerCanvas: {
type: "CANVAS_WIDGET",
widgetId: "canvas_widget_id",
isVisible: true,
parentId: "container1_id",
ENTITY_TYPE: "WIDGET",
},
Container1: {
type: "CONTAINER_WIDGET",
widgetId: "container1_id",
isVisible: false,
parentId: "0",
ENTITY_TYPE: "WIDGET",
},
},
expectedResult: {},
};
const result = getFilteredErrors.resultFunc(
TestData.debuggerErrors,
false,
TestData.canvasWidgets as unknown as CanvasWidgetsReduxState,
TestData.dataTree as unknown as DataTree,
);
expect(result).toStrictEqual(TestData.expectedResult);
});
it("hides error from widget in hidden container", () => {
const TestData = {
debuggerErrors: {
"container1_input_id-defaultText": {
id: "container1_input_id-defaultText",
logType: LOG_TYPE.EVAL_ERROR,
text: "The value at defaultText is invalid",
messages: [
{
message: {
name: "TypeError",
message:
"Cannot read properties of undefined (reading 'users')",
},
type: PropertyEvaluationErrorType.PARSE,
},
],
source: {
id: "container1_input_id",
name: "container1_input",
type: ENTITY_TYPE.WIDGET,
propertyPath: "defaultText",
},
state: {
defaultText: "",
},
analytics: {
widgetType: "INPUT_WIDGET_V2",
},
severity: Severity.ERROR,
category: LOG_CATEGORY.PLATFORM_GENERATED,
timestamp: "02:40:10",
isExpanded: false,
},
},
canvasWidgets: {
container1_input_id: {
widgetName: "container1_input",
type: "INPUT_WIDGET_V2",
widgetId: "container1_input_id",
parentId: "canvas_widget_id",
},
canvas_widget_id: {
widgetName: "ContainerCanvas",
type: "CANVAS_WIDGET",
widgetId: "canvas_widget_id",
parentId: "container1_id",
},
container1_id: {
widgetName: "Container1",
type: "CONTAINER_WIDGET",
widgetId: "container1_id",
parentId: "0",
},
},
dataTree: {
container1_input: {
type: "INPUT_WIDGET_V2",
widgetId: "container1_input_id",
isVisible: true,
parentId: "canvas_widget_id",
ENTITY_TYPE: "WIDGET",
},
ContainerCanvas: {
type: "CANVAS_WIDGET",
widgetId: "canvas_widget_id",
isVisible: true,
parentId: "container1_id",
ENTITY_TYPE: "WIDGET",
},
Container1: {
type: "CONTAINER_WIDGET",
widgetId: "container1_id",
isVisible: false,
parentId: "0",
ENTITY_TYPE: "WIDGET",
},
},
expectedResult: {},
};
const result = getFilteredErrors.resultFunc(
TestData.debuggerErrors,
false,
TestData.canvasWidgets as unknown as CanvasWidgetsReduxState,
TestData.dataTree as unknown as DataTree,
);
expect(result).toStrictEqual(TestData.expectedResult);
});
it("shows error for widget with faulty binding for isVisible prop", () => {
const TestData = {
debuggerErrors: {
"main_input_id-isVisible": {
id: "main_input_id-isVisible",
logType: LOG_TYPE.EVAL_ERROR,
text: "The value at isVisible is invalid",
messages: [
{
message: {
name: "TypeError",
message:
"Cannot read properties of undefined (reading 'users')",
},
type: PropertyEvaluationErrorType.PARSE,
},
],
source: {
id: "main_input_id",
name: "main_input",
type: ENTITY_TYPE.WIDGET,
propertyPath: "isVisible",
},
state: {
isVisible: "{{users}}",
},
analytics: {
widgetType: "INPUT_WIDGET_V2",
},
severity: Severity.ERROR,
category: LOG_CATEGORY.PLATFORM_GENERATED,
timestamp: "02:40:10",
isExpanded: false,
},
},
canvasWidgets: {
main_input_id: {
widgetName: "main_input",
type: "INPUT_WIDGET_V2",
widgetId: "main_input_id",
parentId: "0",
},
},
dataTree: {
main_input: {
isVisible: false,
parentId: "0",
widgetId: "main_input_id",
type: "INPUT_WIDGET_V2",
ENTITY_TYPE: ENTITY_TYPE.WIDGET,
},
},
expectedResult: {
"main_input_id-isVisible": {
id: "main_input_id-isVisible",
logType: LOG_TYPE.EVAL_ERROR,
category: LOG_CATEGORY.PLATFORM_GENERATED,
text: "The value at isVisible is invalid",
messages: [
{
message: {
name: "TypeError",
message:
"Cannot read properties of undefined (reading 'users')",
},
type: PropertyEvaluationErrorType.PARSE,
},
],
source: {
id: "main_input_id",
name: "main_input",
type: ENTITY_TYPE.WIDGET,
propertyPath: "isVisible",
},
state: {
isVisible: "{{users}}",
},
analytics: {
widgetType: "INPUT_WIDGET_V2",
},
severity: Severity.ERROR,
timestamp: "02:40:10",
isExpanded: false,
},
},
};
const result = getFilteredErrors.resultFunc(
TestData.debuggerErrors,
false,
TestData.canvasWidgets as unknown as CanvasWidgetsReduxState,
TestData.dataTree as unknown as DataTree,
);
expect(result).toStrictEqual(TestData.expectedResult);
});
it("shows error for widget with faulty binding for isVisible prop (visible parent container)", () => {
const TestData = {
debuggerErrors: {
"container1_input_id-isVisible": {
id: "container1_input_id-isVisible",
logType: LOG_TYPE.EVAL_ERROR,
text: "The value at isVisible is invalid",
messages: [
{
message: {
name: "TypeError",
message:
"Cannot read properties of undefined (reading 'users')",
},
type: PropertyEvaluationErrorType.PARSE,
},
],
source: {
id: "container1_input_id",
name: "container1_input",
type: ENTITY_TYPE.WIDGET,
propertyPath: "isVisible",
},
state: {
isVisible: "{{users}}",
},
analytics: {
widgetType: "INPUT_WIDGET_V2",
},
severity: Severity.ERROR,
category: LOG_CATEGORY.PLATFORM_GENERATED,
timestamp: "02:40:10",
isExpanded: false,
},
},
canvasWidgets: {
container1_input_id: {
widgetName: "container1_input",
type: "INPUT_WIDGET_V2",
widgetId: "container1_input_id",
parentId: "canvas_widget_id",
},
canvas_widget_id: {
widgetName: "ContainerCanvas",
type: "CANVAS_WIDGET",
widgetId: "canvas_widget_id",
parentId: "container1_id",
},
container1_id: {
widgetName: "Container1",
type: "CONTAINER_WIDGET",
widgetId: "container1_id",
parentId: "0",
},
},
dataTree: {
container1_input: {
type: "INPUT_WIDGET_V2",
widgetId: "container1_input_id",
isVisible: false,
parentId: "canvas_widget_id",
ENTITY_TYPE: "WIDGET",
},
ContainerCanvas: {
type: "CANVAS_WIDGET",
widgetId: "canvas_widget_id",
isVisible: true,
parentId: "container1_id",
ENTITY_TYPE: "WIDGET",
},
Container1: {
type: "CONTAINER_WIDGET",
widgetId: "container1_id",
isVisible: true,
parentId: "0",
ENTITY_TYPE: "WIDGET",
},
},
expectedResult: {
"container1_input_id-isVisible": {
id: "container1_input_id-isVisible",
logType: LOG_TYPE.EVAL_ERROR,
text: "The value at isVisible is invalid",
messages: [
{
message: {
name: "TypeError",
message:
"Cannot read properties of undefined (reading 'users')",
},
type: PropertyEvaluationErrorType.PARSE,
},
],
source: {
id: "container1_input_id",
name: "container1_input",
type: ENTITY_TYPE.WIDGET,
propertyPath: "isVisible",
},
state: {
isVisible: "{{users}}",
},
analytics: {
widgetType: "INPUT_WIDGET_V2",
},
severity: Severity.ERROR,
category: LOG_CATEGORY.PLATFORM_GENERATED,
timestamp: "02:40:10",
isExpanded: false,
},
},
};
const result = getFilteredErrors.resultFunc(
TestData.debuggerErrors,
false,
TestData.canvasWidgets as unknown as CanvasWidgetsReduxState,
TestData.dataTree as unknown as DataTree,
);
expect(result).toStrictEqual(TestData.expectedResult);
});
it("hides error for widget with faulty binding for isVisible prop (hidden parent container)", () => {
const TestData = {
debuggerErrors: {
"container1_input_id-isVisible": {
id: "container1_input_id-isVisible",
logType: LOG_TYPE.EVAL_ERROR,
text: "The value at isVisible is invalid",
messages: [
{
message: {
name: "TypeError",
message:
"Cannot read properties of undefined (reading 'users')",
},
type: PropertyEvaluationErrorType.PARSE,
},
],
source: {
id: "container1_input_id",
name: "container1_input",
type: ENTITY_TYPE.WIDGET,
propertyPath: "isVisible",
},
state: {
isVisible: "{{users}}",
},
analytics: {
widgetType: "INPUT_WIDGET_V2",
},
severity: Severity.ERROR,
category: LOG_CATEGORY.PLATFORM_GENERATED,
timestamp: "02:40:10",
isExpanded: false,
},
},
canvasWidgets: {
container1_input_id: {
widgetName: "container1_input",
type: "INPUT_WIDGET_V2",
widgetId: "container1_input_id",
parentId: "canvas_widget_id",
},
canvas_widget_id: {
widgetName: "ContainerCanvas",
type: "CANVAS_WIDGET",
widgetId: "canvas_widget_id",
parentId: "container1_id",
},
container1_id: {
widgetName: "Container1",
type: "CONTAINER_WIDGET",
widgetId: "container1_id",
parentId: "0",
},
},
dataTree: {
container1_input: {
type: "INPUT_WIDGET_V2",
widgetId: "container1_input_id",
isVisible: false,
parentId: "canvas_widget_id",
ENTITY_TYPE: "WIDGET",
},
ContainerCanvas: {
type: "CANVAS_WIDGET",
widgetId: "canvas_widget_id",
isVisible: true,
parentId: "container1_id",
ENTITY_TYPE: "WIDGET",
},
Container1: {
type: "CONTAINER_WIDGET",
widgetId: "container1_id",
isVisible: false,
parentId: "0",
ENTITY_TYPE: "WIDGET",
},
},
expectedResult: {},
};
const result = getFilteredErrors.resultFunc(
TestData.debuggerErrors,
false,
TestData.canvasWidgets as unknown as CanvasWidgetsReduxState,
TestData.dataTree as unknown as DataTree,
);
expect(result).toStrictEqual(TestData.expectedResult);
});
});
|
1,300 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/selectors/widgetSelectors.test.tsx | import React from "react";
import { Provider, useSelector } from "react-redux";
import { shouldWidgetIgnoreClicksSelector } from "./widgetSelectors";
import { renderHook, act } from "@testing-library/react-hooks";
import store from "../store";
import { useAutoHeightUIState } from "utils/hooks/autoHeightUIHooks";
describe("shouldWidgetIgnoreClicksSelector", () => {
it("should return true when we are changing the auto height with limits", () => {
const wrapper = ({ children }: { children: React.ReactNode }) => (
<Provider store={store}>{children}</Provider>
);
const { result: shouldIgnore } = renderHook(
() => useSelector(shouldWidgetIgnoreClicksSelector("0")),
{ wrapper },
);
const { result: autoHeightUIState } = renderHook(
() => useAutoHeightUIState(),
{ wrapper },
);
act(() => {
autoHeightUIState.current.setIsAutoHeightWithLimitsChanging(true);
});
expect(shouldIgnore.current).toBe(true);
});
});
|
1,306 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/transformers/CurlImportTransformer.test.ts | import transformCurlImport from "transformers/CurlImportTransformer";
describe("CurlImportTransformer", () => {
it("has quotes in start and end and escapes special characters", () => {
const inputs = [
`curl -X GET`,
`"curl -X GET`,
`curl -X GET"`,
`curl google.com\n`,
];
const outputs = [
`"curl -X GET"`,
`"\\"curl -X GET"`,
`"curl -X GET\\""`,
`"curl google.com\\n"`,
];
inputs.forEach((input, index) => {
const result = transformCurlImport(input);
expect(result).toBe(outputs[index]);
});
});
});
|
1,310 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/transformers/RestActionTransformers.test.ts | import {
extractApiUrlPath,
transformRestAction,
} from "transformers/RestActionTransformer";
import type { ApiAction } from "entities/Action";
import { PluginType } from "entities/Action";
import {
MultiPartOptionTypes,
POST_BODY_FORMAT_OPTIONS,
// POST_BODY_FORMAT_OPTIONS_ENUM,
} from "constants/ApiEditorConstants/CommonApiConstants";
// jest.mock("POST_");
const BASE_ACTION: ApiAction = {
dynamicBindingPathList: [],
cacheResponse: "",
executeOnLoad: false,
invalids: [],
isValid: false,
workspaceId: "",
pageId: "",
pluginId: "",
id: "testId",
datasource: {
id: "testDataSource",
},
name: "testName",
pluginType: PluginType.API,
actionConfiguration: {
httpMethod: "GET",
encodeParamsToggle: true,
path: "users",
headers: [],
formData: {
apiContentType: "none",
},
timeoutInMillisecond: 5000,
},
jsonPathKeys: [],
messages: [],
};
describe("Api action transformer", () => {
it("Removes params from path", () => {
const input: ApiAction = {
...BASE_ACTION,
actionConfiguration: {
...BASE_ACTION.actionConfiguration,
path: "users?page=1",
queryParameters: [
{
key: "page",
value: "1",
},
],
},
};
const output = {
...BASE_ACTION,
actionConfiguration: {
...BASE_ACTION.actionConfiguration,
path: "users",
queryParameters: [
{
key: "page",
value: "1",
},
],
},
};
const result = transformRestAction(input);
expect(result).toEqual(output);
});
it("Sets the correct body for JSON display type", () => {
const input = {
...BASE_ACTION,
actionConfiguration: {
...BASE_ACTION.actionConfiguration,
httpMethod: "POST",
headers: [{ key: "content-type", value: "application/json" }],
body: "{ name: 'test' }",
},
};
const output = {
...BASE_ACTION,
actionConfiguration: {
...BASE_ACTION.actionConfiguration,
httpMethod: "POST",
headers: [{ key: "content-type", value: "application/json" }],
body: "{ name: 'test' }",
},
};
const result = transformRestAction(input);
expect(result).toEqual(output);
});
it("bodyFormData should not be reset for non xxx-form-encoded-data type", () => {
const input = {
...BASE_ACTION,
actionConfiguration: {
...BASE_ACTION.actionConfiguration,
httpMethod: "POST",
headers: [{ key: "content-type", value: "application/json" }],
body: "{ name: 'test' }",
bodyFormData: [
{
key: "hey",
value: "ho",
editable: true,
mandatory: false,
description: "I been tryin to do it right",
type: "",
},
],
},
};
const output = {
...BASE_ACTION,
actionConfiguration: {
...BASE_ACTION.actionConfiguration,
httpMethod: "POST",
headers: [{ key: "content-type", value: "application/json" }],
body: "{ name: 'test' }",
bodyFormData: [
{
key: "hey",
value: "ho",
editable: true,
mandatory: false,
description: "I been tryin to do it right",
type: "",
},
],
},
};
const result = transformRestAction(input);
expect(result).toEqual(output);
});
it("body should not be reset for xxx-form-encoded-data type", () => {
const input = {
...BASE_ACTION,
actionConfiguration: {
...BASE_ACTION.actionConfiguration,
httpMethod: "POST",
headers: [
{
key: "content-type",
value: POST_BODY_FORMAT_OPTIONS.FORM_URLENCODED,
},
],
bodyFormData: [
{
key: "hey",
value: "ho",
editable: true,
mandatory: false,
description: "I been tryin to do it right",
type: "",
},
],
body: "{ name: 'test' }",
},
};
const output = {
...BASE_ACTION,
actionConfiguration: {
...BASE_ACTION.actionConfiguration,
httpMethod: "POST",
headers: [
{
key: "content-type",
value: POST_BODY_FORMAT_OPTIONS.FORM_URLENCODED,
},
],
body: "{ name: 'test' }",
bodyFormData: [
{
key: "hey",
value: "ho",
editable: true,
mandatory: false,
description: "I been tryin to do it right",
type: "",
},
],
},
};
const result = transformRestAction(input);
expect(result).toEqual(output);
});
it("Sets the correct body for xxx-form-encoded-data display type", () => {
const input = {
...BASE_ACTION,
actionConfiguration: {
...BASE_ACTION.actionConfiguration,
httpMethod: "POST",
headers: [
{
key: "content-type",
value: POST_BODY_FORMAT_OPTIONS.FORM_URLENCODED,
},
],
bodyFormData: [
{
key: "hey",
value: "ho",
editable: true,
mandatory: false,
description: "I been tryin to do it right",
type: "",
},
],
},
};
const output = {
...BASE_ACTION,
actionConfiguration: {
...BASE_ACTION.actionConfiguration,
httpMethod: "POST",
headers: [
{
key: "content-type",
value: POST_BODY_FORMAT_OPTIONS.FORM_URLENCODED,
},
],
body: "",
bodyFormData: [
{
key: "hey",
value: "ho",
editable: true,
mandatory: false,
description: "I been tryin to do it right",
type: "",
},
],
},
};
const result = transformRestAction(input);
expect(result).toEqual(output);
});
it("Sets the correct body for custom/raw display type", () => {
const input = {
...BASE_ACTION,
actionConfiguration: {
...BASE_ACTION.actionConfiguration,
headers: [{ key: "content-type", value: "text/html" }],
httpMethod: "POST",
body: "raw body",
},
};
const output = {
...BASE_ACTION,
actionConfiguration: {
...BASE_ACTION.actionConfiguration,
headers: [{ key: "content-type", value: "text/html" }],
httpMethod: "POST",
body: "raw body",
},
};
const result = transformRestAction(input);
expect(result).toEqual(output);
});
it("filters empty pairs from form data", () => {
const input: ApiAction = {
...BASE_ACTION,
actionConfiguration: {
...BASE_ACTION.actionConfiguration,
httpMethod: "POST",
headers: [
{
key: "content-type",
value: POST_BODY_FORMAT_OPTIONS.MULTIPART_FORM_DATA,
},
],
body: "",
bodyFormData: [
{
key: "hey",
value: "ho",
type: MultiPartOptionTypes.TEXT,
editable: true,
mandatory: false,
description: "I been tryin to do it right",
},
{
key: "",
value: "",
editable: true,
mandatory: false,
description: "I been tryin to do it right",
type: "",
},
],
},
};
// output object should not include the second bodyFormData object
// as its key, value and type are empty
const output: ApiAction = {
...BASE_ACTION,
actionConfiguration: {
...BASE_ACTION.actionConfiguration,
httpMethod: "POST",
headers: [
{
key: "content-type",
value: POST_BODY_FORMAT_OPTIONS.MULTIPART_FORM_DATA,
},
],
body: "",
bodyFormData: [
{
key: "hey",
value: "ho",
type: MultiPartOptionTypes.TEXT,
editable: true,
mandatory: false,
description: "I been tryin to do it right",
},
],
},
};
const result = transformRestAction(input);
expect(result).toEqual(output);
});
it("Ensures that Api url path is being correctly extracted regardless of expressions witin dynamic bindings", () => {
// testing for simple dynamic bindings in path
const path1 = `/{{Text1.text ? 'users' : 'user'}}`;
const output1 = `/{{Text1.text ? 'users' : 'user'}}`;
const result1 = extractApiUrlPath(path1);
expect(result1).toEqual(output1);
// testing multiple dynamic bindings in path with empty query params
const path2 = `/{{Text1.text ? 'users' : 'user'}}/{{"test"}}?`;
const output2 = `/{{Text1.text ? 'users' : 'user'}}/{{"test"}}`;
const result2 = extractApiUrlPath(path2);
expect(result2).toEqual(output2);
// testing multiple dynamic bindings in path with non-empty query params
const path3 = `/{{Text1.text ? 'users' : 'user'}}/{{"test"}}?a=hello&b=world`;
const output3 = `/{{Text1.text ? 'users' : 'user'}}/{{"test"}}`;
const result3 = extractApiUrlPath(path3);
expect(result3).toEqual(output3);
// testing normal strings and dynamic bindings in path with non-empty query params
const path4 = `/key/{{Text1.text}}?a=hello&b=world`;
const output4 = `/key/{{Text1.text}}`;
const result4 = extractApiUrlPath(path4);
expect(result4).toEqual(output4);
const path5 = "/{{Text1.text ?? 'user1'}}";
const output5 = "/{{Text1.text ?? 'user1'}}";
const result5 = extractApiUrlPath(path5);
expect(result5).toEqual(output5);
});
});
|
1,312 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/usagePulse/usagePulse.test.ts | import UsagePulse from "usagePulse";
describe("Usage pulse", () => {
describe("isTrackableUrl", () => {
it("should return true when called with trackable URL", () => {
// All application URLS are trackable.
[
"/app/test/mypage-123123/edit",
"/app/test/mypage-123123",
"/app/test-123123/edit",
"/app/test-123123",
"/applications/123123test/pages/123123test/edit",
"/applications/123123test/pages/123123test",
].forEach((url) => {
expect(UsagePulse.isTrackableUrl(url)).toBeTruthy();
});
});
it("should return false when called with untrackable URL", () => {
[
"/applications",
"/login",
"/signup",
"/settings",
"/generate-page",
].forEach(async (url) => {
expect(await UsagePulse.isTrackableUrl(url)).toBeFalsy();
});
});
});
});
|
1,315 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/ApiPaneUtils.test.ts | import { POST_BODY_FORMAT_OPTIONS } from "constants/ApiEditorConstants/CommonApiConstants";
import {
getContentTypeHeaderValue,
getIndextoUpdate,
parseUrlForQueryParams,
} from "utils/ApiPaneUtils";
describe("api pane header insertion or removal", () => {
describe("index for header needs to be returned", () => {
test("it gives correct index", () => {
const headers = [
{ key: "content-type", value: "application/json" },
{ key: "", value: "" },
{ key: "", value: "" },
{ key: "", value: "" },
];
const headerIndex = 0;
expect(getIndextoUpdate(headers, headerIndex)).toEqual(headerIndex);
const headers2 = [
{ key: "", value: "" },
{ key: "", value: "" },
{ key: "", value: "" },
];
const headerIndex2 = -1;
expect(getIndextoUpdate(headers2, headerIndex2)).toEqual(0);
const headers3 = [
{ key: "abc", value: "abc" },
{ key: "def", value: "def" },
{ key: "ghi", value: "ghi" },
];
const headerIndex3 = -1;
expect(getIndextoUpdate(headers3, headerIndex3)).toEqual(headers3.length);
});
});
});
describe("Api pane query parameters parsing", () => {
test("It gives correct query parameters", () => {
const url1 = "user?q=2&b='Auth=xyz'";
const params1 = [
{ key: "q", value: "2" },
{ key: "b", value: "'Auth=xyz'" },
];
expect(parseUrlForQueryParams(url1)).toEqual(params1);
const url2 = "/user?q=2&b='Auth=xyz'";
expect(parseUrlForQueryParams(url2)).toEqual(params1);
const url3 = "user?q=2&b={{Api1.data.isLatest ? 'v1' : 'v2'}}";
const params2 = [
{ key: "q", value: "2" },
{ key: "b", value: "{{Api1.data.isLatest ? 'v1' : 'v2'}}" },
];
expect(parseUrlForQueryParams(url3)).toEqual(params2);
const url4 = "";
const params3 = [
{ key: "", value: "" },
{ key: "", value: "" },
];
expect(parseUrlForQueryParams(url4)).toEqual(params3);
const url5 = "/";
expect(parseUrlForQueryParams(url5)).toEqual(params3);
});
});
describe("API Body Format Test", () => {
it("it checks whether selected body format is as per the content-type header or not", () => {
const headers = [
{
key: "Content-Type",
value: "application/x-www-form-urlencoded",
},
];
expect(getContentTypeHeaderValue(headers)).toEqual(
POST_BODY_FORMAT_OPTIONS.FORM_URLENCODED,
);
});
});
|
1,319 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/AppsmithUtils.test.ts | import {
areArraysEqual,
createBlobUrl,
DataType,
getCamelCaseString,
getDatatype,
parseBlobUrl,
} from "utils/AppsmithUtils";
import { isURL } from "./TypeHelpers";
describe("getCamelCaseString", () => {
it("Should return a string in camelCase", () => {
const inputs = ["abcd", "ab12cd", "开关", "😃 😃 😃"];
const expected = ["abcd", "ab12Cd", "", ""];
inputs.forEach((input, index) => {
const result = getCamelCaseString(input);
expect(result).toStrictEqual(expected[index]);
});
});
});
describe("test areArraysEqual", () => {
it("test areArraysEqual method", () => {
const OGArray = ["test1", "test2", "test3"];
let testArray: string[] = [];
expect(areArraysEqual(OGArray, testArray)).toBe(false);
testArray = ["test1", "test3"];
expect(areArraysEqual(OGArray, testArray)).toBe(false);
testArray = ["test1", "test2", "test3"];
expect(areArraysEqual(OGArray, testArray)).toBe(true);
testArray = ["test1", "test3", "test2"];
expect(areArraysEqual(OGArray, testArray)).toBe(true);
});
});
describe("isURL", () => {
test("returns true for valid URLs", () => {
expect(isURL("http://example.com")).toBe(true);
expect(isURL("https://www.google.com/search?q=javascript")).toBe(true);
expect(isURL("https://en.wikipedia.org/wiki/Regular_expression")).toBe(
true,
);
expect(
isURL("https://www.example.com/path(withparentheses)/file.html"),
).toBe(true);
expect(
isURL("https://www.example.com/path[withparentheses]/file_(1)[2].html"),
).toBe(true);
});
test("returns false for invalid URLs", () => {
expect(isURL("http://localhost:3000")).toBe(false);
expect(isURL("not a URL")).toBe(false);
expect(isURL("ftp:/example.com")).toBe(false);
expect(isURL("http://example.")).toBe(false);
expect(isURL("http://localhost:port")).toBe(false);
expect(isURL("notAURL")).toBe(false);
expect(isURL("httpsnotAURL")).toBe(false);
});
});
describe("createBlobUrl", () => {
beforeEach(() => {
URL.createObjectURL = jest
.fn()
.mockReturnValue(`blob:${window.location.origin}/123-123-123-123-123`);
});
it("should test that it created correct blob URL", () => {
expect(createBlobUrl(new Blob(), "base64")).toMatch(
/blob:[a-z0-9-]*\?type=base64/,
);
expect(createBlobUrl(new Blob(), "raw")).toMatch(
/blob:[a-z0-9-]*\?type=raw/,
);
});
});
describe("parseBlobUrl", () => {
it("should test that it created correct blob URL", () => {
expect(parseBlobUrl("blob:123-123?type=base")).toEqual([
`blob:${window.location.origin}/123-123`,
"base",
]);
expect(parseBlobUrl("blob:123-123?type=raw")).toEqual([
`blob:${window.location.origin}/123-123`,
"raw",
]);
});
});
describe("getDatatype - should test the datatypes", () => {
it("1. String", () => {
expect(getDatatype("test")).toBe(DataType.STRING);
});
it("2. Number", () => {
[1, NaN].forEach((d) => {
expect(getDatatype(d)).toBe(DataType.NUMBER);
});
});
it("3. Boolean", () => {
[true, false].forEach((d) => {
expect(getDatatype(d)).toBe(DataType.BOOLEAN);
});
});
it("4. Object", () => {
expect(getDatatype({})).toBe(DataType.OBJECT);
});
it("5. Array", () => {
expect(getDatatype([])).toBe(DataType.ARRAY);
});
it("6. Rest of the types", () => {
expect(getDatatype(null)).toBe(DataType.NULL);
expect(getDatatype(undefined)).toBe(DataType.UNDEFINED);
});
});
|
1,322 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/DSLMigration.test.ts | import type { WidgetProps } from "widgets/BaseWidget";
import type { ContainerWidgetProps } from "widgets/ContainerWidget/widget";
import * as DSLMigrations from "./DSLMigrations";
import * as chartWidgetReskinningMigrations from "./migrations/ChartWidgetReskinningMigrations";
import * as tableMigrations from "./migrations/TableWidget";
import * as IncorrectDynamicBindingPathLists from "./migrations/IncorrectDynamicBindingPathLists";
import * as TextStyleFromTextWidget from "./migrations/TextWidget";
import * as menuButtonWidgetMigrations from "./migrations/MenuButtonWidget";
import * as modalMigration from "./migrations/ModalWidget";
import * as mapWidgetMigration from "./migrations/MapWidget";
import * as checkboxMigration from "./migrations/CheckboxGroupWidget";
import * as buttonWidgetMigrations from "./migrations/ButtonWidgetMigrations";
import * as phoneInputMigration from "./migrations/PhoneInputWidgetMigrations";
import * as inputCurrencyMigration from "./migrations/CurrencyInputWidgetMigrations";
import * as radioGroupMigration from "./migrations/RadioGroupWidget";
import * as propertyPaneMigrations from "./migrations/PropertyPaneMigrations";
import * as themingMigration from "./migrations/ThemingMigrations";
import * as selectWidgetMigration from "./migrations/SelectWidget";
import * as mapChartReskinningMigrations from "./migrations/MapChartReskinningMigrations";
import { LATEST_PAGE_VERSION } from "constants/WidgetConstants";
import { originalDSLForDSLMigrations } from "./testDSLs";
import * as rateWidgetMigrations from "./migrations/RateWidgetMigrations";
import * as codeScannerWidgetMigrations from "./migrations/CodeScannerWidgetMigrations";
import * as migrateLabelPosition from "./migrations/MigrateLabelPosition";
import * as migrateAutoHeight from "./migrations/autoHeightMigrations";
import * as chartMigrations from "./migrations/ChartWidget";
interface Migration {
functionLookup: {
moduleObj: any;
functionName: string;
}[];
version: number | undefined;
}
/**
* Migrations is an array of objects, were each object has
* - moduleObj: A namespace import that includes all the exported function present in the module. Refer to line 3.
* - functionName: Name of the migration function to spyOn
* - version: The DSL version in which the function is executing
*
* Migrations will be used to construct mockFnObj object where mockFnObj's key is the version and value is an array of jest mock functions.
*
* NOTE:
* - In Migrations the sequence of object should exactly match the sequence that is present in the transformDSL function.
*
* - For cases were migration is skipped, we include them in Migrations.
* Simply add the object with functionLookup and version of the skipped migration.
* Refer to the skippedMigration50 object inside Migrations
*/
const migrations: Migration[] = [
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "calculateDynamicHeight",
},
],
version: undefined,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "updateContainers",
},
],
version: 1,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "chartDataMigration",
},
],
version: 2,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "mapDataMigration",
},
],
version: 3,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "singleChartDataMigration",
},
],
version: 4,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "tabsWidgetTabsPropertyMigration",
},
],
version: 5,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "dynamicPathListMigration",
},
],
version: 6,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "canvasNameConflictMigration",
},
],
version: 7,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "renamedCanvasNameConflictMigration",
},
],
version: 8,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "tableWidgetPropertyPaneMigrations",
},
],
version: 9,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "addVersionNumberMigration",
},
],
version: 10,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "migrateTablePrimaryColumnsBindings",
},
],
version: 11,
},
{
functionLookup: [
{
moduleObj: IncorrectDynamicBindingPathLists,
functionName: "migrateIncorrectDynamicBindingPathLists",
},
],
version: 12,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "migrateOldChartData",
},
],
version: 13,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "rteDefaultValueMigration",
},
],
version: 14,
},
{
functionLookup: [
{
moduleObj: TextStyleFromTextWidget,
functionName: "migrateTextStyleFromTextWidget",
},
],
version: 15,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "migrateChartDataFromArrayToObject",
},
],
version: 16,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "migrateTabsData",
},
],
version: 17,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "migrateInitialValues",
},
],
version: 18,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "migrateToNewLayout",
},
],
version: 19,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "migrateNewlyAddedTabsWidgetsMissingData",
},
],
version: 20,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "migrateWidgetsWithoutLeftRightColumns",
},
{
moduleObj: DSLMigrations,
functionName: "migrateOverFlowingTabsWidgets",
},
],
version: 21,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "migrateTableWidgetParentRowSpaceProperty",
},
],
version: 22,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "addLogBlackListToAllListWidgetChildren",
},
],
version: 23,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "migrateTableWidgetHeaderVisibilityProperties",
},
],
version: 24,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "migrateItemsToListDataInListWidget",
},
],
version: 25,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "migrateDatePickerMinMaxDate",
},
],
version: 26,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "migrateFilterValueForDropDownWidget",
},
],
version: 27,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "migrateTablePrimaryColumnsComputedValue",
},
],
version: 28,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "migrateToNewMultiSelect",
},
],
version: 29,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "migrateTableWidgetDelimiterProperties",
},
],
version: 30,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "migrateIsDisabledToButtonColumn",
},
],
version: 31,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "migrateTableDefaultSelectedRow",
},
],
version: 32,
},
{
functionLookup: [
{
moduleObj: menuButtonWidgetMigrations,
functionName: "migrateMenuButtonWidgetButtonProperties",
},
],
version: 33,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "migrateButtonWidgetValidation",
},
],
version: 34,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "migrateInputValidation",
},
],
version: 35,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "revertTableDefaultSelectedRow",
},
],
version: 36,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "migrateTableSanitizeColumnKeys",
},
],
version: 37,
},
{
functionLookup: [
{
moduleObj: modalMigration,
functionName: "migrateResizableModalWidgetProperties",
},
],
version: 38,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "migrateTableWidgetSelectedRowBindings",
},
],
version: 39,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "revertButtonStyleToButtonColor",
},
],
version: 40,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "migrateButtonVariant",
},
],
version: 41,
},
{
functionLookup: [
{
moduleObj: mapWidgetMigration,
functionName: "migrateMapWidgetIsClickedMarkerCentered",
},
],
version: 42,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "mapAllowHorizontalScrollMigration",
},
],
version: 43,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "isSortableMigration",
},
],
version: 44,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "migrateTableWidgetIconButtonVariant",
},
],
version: 45,
},
{
functionLookup: [
{
moduleObj: checkboxMigration,
functionName: "migrateCheckboxGroupWidgetInlineProperty",
},
],
version: 46,
},
{
functionLookup: [
{
moduleObj: "",
functionName: "skippedMigration47",
},
],
version: 47,
},
{
functionLookup: [
{
moduleObj: buttonWidgetMigrations,
functionName: "migrateRecaptchaType",
},
],
version: 48,
},
{
functionLookup: [
{
moduleObj: DSLMigrations,
functionName: "addPrivateWidgetsToAllListWidgets",
},
],
version: 49,
},
{
functionLookup: [
{
moduleObj: "",
functionName: "skippedMigration50",
},
],
version: 50,
},
{
functionLookup: [
{
moduleObj: phoneInputMigration,
functionName: "migratePhoneInputWidgetAllowFormatting",
},
],
version: 51,
},
{
functionLookup: [
{
moduleObj: modalMigration,
functionName: "migrateModalIconButtonWidget",
},
],
version: 52,
},
{
functionLookup: [
{
moduleObj: TextStyleFromTextWidget,
functionName: "migrateScrollTruncateProperties",
},
],
version: 53,
},
{
functionLookup: [
{
moduleObj: phoneInputMigration,
functionName: "migratePhoneInputWidgetDefaultDialCode",
},
],
version: 54,
},
{
functionLookup: [
{
moduleObj: inputCurrencyMigration,
functionName: "migrateCurrencyInputWidgetDefaultCurrencyCode",
},
],
version: 55,
},
{
functionLookup: [
{
moduleObj: radioGroupMigration,
functionName: "migrateRadioGroupAlignmentProperty",
},
],
version: 56,
},
{
functionLookup: [
{
moduleObj: themingMigration,
functionName: "migrateStylingPropertiesForTheming",
},
],
version: 57,
},
{
functionLookup: [
{
moduleObj: propertyPaneMigrations,
functionName: "migrateCheckboxSwitchProperty",
},
],
version: 58,
},
{
functionLookup: [
{
moduleObj: chartWidgetReskinningMigrations,
functionName: "migrateChartWidgetReskinningData",
},
],
version: 59,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "migrateTableWidgetV2Validation",
},
],
version: 60,
},
{
functionLookup: [
{
moduleObj: chartWidgetReskinningMigrations,
functionName: "migrateChartWidgetReskinningData",
},
],
version: 61,
},
{
functionLookup: [
{
moduleObj: selectWidgetMigration,
functionName: "MigrateSelectTypeWidgetDefaultValue",
},
],
version: 62,
},
{
functionLookup: [
{
moduleObj: mapChartReskinningMigrations,
functionName: "migrateMapChartWidgetReskinningData",
},
],
version: 63,
},
{
functionLookup: [
{
moduleObj: rateWidgetMigrations,
functionName: "migrateRateWidgetDisabledState",
},
],
version: 64,
},
{
functionLookup: [
{
moduleObj: codeScannerWidgetMigrations,
functionName: "migrateCodeScannerLayout",
},
],
version: 65,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "migrateTableWidgetV2ValidationBinding",
},
],
version: 66,
},
{
functionLookup: [
{
moduleObj: migrateLabelPosition,
functionName: "migrateLabelPosition",
},
],
version: 67,
},
{
functionLookup: [
{
moduleObj: migrateAutoHeight,
functionName: "migratePropertiesForDynamicHeight",
},
],
version: 68,
},
{
functionLookup: [
{
moduleObj: menuButtonWidgetMigrations,
functionName: "migrateMenuButtonDynamicItems",
},
],
version: 69,
},
{
functionLookup: [
{
moduleObj: themingMigration,
functionName: "migrateChildStylesheetFromDynamicBindingPathList",
},
],
version: 70,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "migrateTableWidgetV2SelectOption",
},
],
version: 71,
},
{
functionLookup: [
{
moduleObj: migrateAutoHeight,
functionName: "migrateListWidgetChildrenForAutoHeight",
},
],
version: 72,
},
{
functionLookup: [
{
moduleObj: inputCurrencyMigration,
functionName: "migrateInputWidgetShowStepArrows",
},
],
version: 73,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "migrateMenuButtonDynamicItemsInsideTableWidget",
},
],
version: 74,
},
{
functionLookup: [
{
moduleObj: migrateAutoHeight,
functionName: "migrateInputWidgetsMultiLineInputType",
},
],
version: 75,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "migrateColumnFreezeAttributes",
},
],
version: 76,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "migrateTableSelectOptionAttributesForNewRow",
},
],
version: 77,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName:
"migrateBindingPrefixSuffixForInlineEditValidationControl",
},
],
version: 78,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "migrateTableWidgetTableDataJsMode",
},
],
version: 79,
},
{
functionLookup: [
{
moduleObj: selectWidgetMigration,
functionName: "migrateSelectWidgetOptionToSourceData",
},
],
version: 80,
},
{
functionLookup: [
{
moduleObj: selectWidgetMigration,
functionName: "migrateSelectWidgetSourceDataBindingPathList",
},
],
version: 81,
},
{
functionLookup: [
{
moduleObj: chartMigrations,
functionName: "migrateChartWidgetLabelOrientationStaggerOption",
},
],
version: 82,
},
{
functionLookup: [
{
moduleObj: chartMigrations,
functionName: "migrateAddShowHideDataPointLabels",
},
],
version: 83,
},
{
functionLookup: [
{
moduleObj: selectWidgetMigration,
functionName: "migrateSelectWidgetAddSourceDataPropertyPathList",
},
],
version: 84,
},
{
functionLookup: [
{
moduleObj: chartMigrations,
functionName: "migrateDefaultValuesForCustomEChart",
},
],
version: 85,
},
{
functionLookup: [
{
moduleObj: tableMigrations,
functionName: "migrateTableServerSideFiltering",
},
],
version: 86,
},
];
const mockFnObj: Record<number, any> = {};
describe("Test all the migrations are running", () => {
afterAll(() => {
jest.clearAllMocks();
});
migrations.forEach((migration: Migration) => {
/**
* Generates mock fucntion for each migration function.
* Mocks the implementation
*/
const version = migration.version ?? 0;
mockFnObj[version] = [];
migration.functionLookup.forEach((lookup) => {
const { functionName, moduleObj } = lookup;
if (moduleObj) {
mockFnObj[version].push({
spyOnFunc: jest
.spyOn(moduleObj, functionName)
.mockImplementation((dsl: any) => {
/**
* We need to delete the children property on the first migration(calculateDynamicHeight),
* to avoid the recursion in the second migration(updateContainers)
*/
dsl && delete dsl.children;
return {
version: dsl?.version,
validationFuncName: functionName,
};
}),
});
}
});
});
// Runs all the migrations
DSLMigrations.transformDSL(
originalDSLForDSLMigrations as unknown as ContainerWidgetProps<WidgetProps>,
);
migrations.forEach((item: any, testIdx: number) => {
const { functionLookup, version } = item;
const dslVersion = version ?? 0;
functionLookup.forEach(
(lookup: { moduleObj: any; functionName: string }, index: number) => {
const { functionName, moduleObj } = lookup;
if (moduleObj) {
const mockObj = mockFnObj[dslVersion][index].spyOnFunc;
const calls = mockObj.mock?.calls;
const results = mockObj.mock?.results;
const resultsLastIdx = mockObj.mock.results.length - 1;
describe(`Test ${testIdx}:`, () => {
test(`Has ${functionName} function executed?`, () => {
// Check if the migration function is called
expect(results[resultsLastIdx].value.validationFuncName).toEqual(
functionName,
);
});
// Check if the migration function is called with the current DSL version
calls.forEach((args: any) => {
test(`Does ${functionName} executes with DSL version: ${version}?`, () => {
if (args[0]?.version === version) {
expect(args[0]?.version).toEqual(version);
}
});
test(`For ${functionName}, is the ${args[0]?.version} registerd in tests?`, () => {
expect(
Object.keys(mockFnObj).includes(
args[0]?.version.toString() ?? "0",
),
).toBe(true);
});
});
});
}
},
);
});
test("Check the migration count matches the lates page version", () => {
expect(migrations.length).toEqual(LATEST_PAGE_VERSION);
});
});
|
1,324 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/DSLMigrationsUtils.test.ts | import { transformDSL } from "./DSLMigrations";
import { LATEST_PAGE_VERSION, RenderModes } from "constants/WidgetConstants";
import type { ContainerWidgetProps } from "widgets/ContainerWidget/widget";
import type { WidgetProps } from "widgets/BaseWidget";
import { OverflowTypes } from "widgets/TextWidget/constants";
import { migrateRadioGroupAlignmentProperty } from "./migrations/RadioGroupWidget";
import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants";
describe("correctly migrate dsl", () => {
it("transformDSL for private widget", () => {
const currentVersion = 49; // before adding privateWidgets to all List widgets
const nextVersion = LATEST_PAGE_VERSION; // It runs Two Migrations, Always Update as migration increases
const currentDSL: ContainerWidgetProps<WidgetProps> = {
backgroundColor: "none",
bottomRow: 740,
canExtend: true,
children: [
{
widgetName: "Input1",
displayName: "Input",
iconSVG: "/static/media/icon.9f505595.svg",
topRow: 18,
bottomRow: 22,
parentRowSpace: 10,
autoFocus: false,
type: "INPUT_WIDGET",
hideCard: false,
animateLoading: true,
parentColumnSpace: 15.0625,
dynamicTriggerPathList: [],
resetOnSubmit: true,
leftColumn: 23,
dynamicBindingPathList: [],
labelStyle: "",
inputType: "TEXT",
isDisabled: false,
key: "ftefjorusw",
isRequired: false,
rightColumn: 43,
widgetId: "lz9hvhcltl",
isVisible: true,
label: "",
allowCurrencyChange: false,
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
iconAlign: "left",
defaultText: "",
},
{
widgetName: "Button1",
onClick:
'{{Api1.run(()=>{\ndownload((\nfunction(){\nreturn "data:image/jpeg;base64,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"\n}\n)(), "test.png", "image/png")\n})}}',
buttonColor: "#03B365",
dynamicPropertyPathList: [
{
key: "onClick",
},
],
displayName: "Button",
iconSVG: "/static/media/icon.cca02633.svg",
topRow: 29,
bottomRow: 33,
tooltip: "",
parentRowSpace: 10,
type: "BUTTON_WIDGET",
hideCard: false,
animateLoading: true,
parentColumnSpace: 14.0625,
dynamicTriggerPathList: [
{
key: "onClick",
},
],
leftColumn: 20,
dynamicBindingPathList: [],
text: "Submit",
isDisabled: false,
key: "pg01cxraj1",
rightColumn: 36,
isDefaultClickDisabled: true,
widgetId: "d229q1ydul",
isVisible: true,
recaptchaType: "V3",
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
buttonVariant: "PRIMARY",
placement: "CENTER",
},
{
widgetName: "Input2",
displayName: "Input",
iconSVG: "/static/media/icon.9f505595.svg",
topRow: 44,
bottomRow: 48,
parentRowSpace: 10,
autoFocus: false,
type: "INPUT_WIDGET",
hideCard: false,
animateLoading: true,
parentColumnSpace: 14.0625,
resetOnSubmit: true,
leftColumn: 9,
labelStyle: "",
inputType: "TEXT",
isDisabled: false,
key: "519sr07k1u",
isRequired: false,
rightColumn: 29,
widgetId: "eenq4c022d",
isVisible: true,
label: "",
allowCurrencyChange: false,
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
iconAlign: "left",
defaultText: "",
},
{
version: 1,
template: {
Image1: {
isVisible: true,
defaultImage: `${ASSETS_CDN_URL}/widgets/default.png`,
imageShape: "RECTANGLE",
maxZoomLevel: 1,
enableRotation: false,
enableDownload: false,
objectFit: "contain",
image: "{{List1.listData.map((currentItem) => currentItem.img)}}",
widgetName: "Image1",
version: 1,
animateLoading: true,
type: "IMAGE_WIDGET",
hideCard: false,
displayName: "Image",
key: "9cn4ooadxj",
iconSVG: "/static/media/icon.52d8fb96.svg",
dynamicBindingPathList: [
{
key: "image",
},
],
dynamicTriggerPathList: [],
widgetId: "yqofym38tn",
renderMode: "CANVAS",
isLoading: false,
leftColumn: 0,
rightColumn: 16,
topRow: 0,
bottomRow: 8.4,
parentId: "vqn2okwc6a",
},
Text1: {
isVisible: true,
text: "{{List1.listData.map((currentItem) => currentItem.name)}}",
fontSize: "PARAGRAPH",
fontStyle: "BOLD",
textAlign: "LEFT",
textColor: "#231F20",
truncateButtonColor: "#FFC13D",
widgetName: "Text1",
shouldScroll: false,
shouldTruncate: false,
version: 1,
animateLoading: true,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
displayName: "Text",
key: "yd217bk315",
iconSVG: "/static/media/icon.97c59b52.svg",
textStyle: "HEADING",
dynamicBindingPathList: [
{
key: "text",
},
],
dynamicTriggerPathList: [],
widgetId: "zeqf6yfm3s",
renderMode: "CANVAS",
isLoading: false,
leftColumn: 16,
rightColumn: 28,
topRow: 0,
bottomRow: 4,
parentId: "vqn2okwc6a",
},
Text2: {
isVisible: true,
text: "{{List1.listData.map((currentItem) => currentItem.id)}}",
fontSize: "PARAGRAPH",
fontStyle: "BOLD",
textAlign: "LEFT",
textColor: "#231F20",
truncateButtonColor: "#FFC13D",
widgetName: "Text2",
shouldScroll: false,
shouldTruncate: false,
version: 1,
animateLoading: true,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
displayName: "Text",
key: "yd217bk315",
iconSVG: "/static/media/icon.97c59b52.svg",
textStyle: "BODY",
dynamicBindingPathList: [
{
key: "text",
},
],
dynamicTriggerPathList: [],
widgetId: "8wyekp2o6e",
renderMode: "CANVAS",
isLoading: false,
leftColumn: 16,
rightColumn: 24,
topRow: 4,
bottomRow: 8,
parentId: "vqn2okwc6a",
},
},
widgetName: "List1",
listData: [
{
id: "001",
name: "Blue",
img: `${ASSETS_CDN_URL}/widgets/default.png`,
},
{
id: "002",
name: "Green",
img: `${ASSETS_CDN_URL}/widgets/default.png`,
},
{
id: "003",
name: "Red",
img: `${ASSETS_CDN_URL}/widgets/default.png`,
},
],
isCanvas: true,
displayName: "List",
iconSVG: "/static/media/icon.9925ee17.svg",
topRow: 34,
bottomRow: 74,
parentRowSpace: 10,
type: "LIST_WIDGET",
hideCard: false,
gridGap: 0,
animateLoading: true,
parentColumnSpace: 14.0625,
leftColumn: 39,
dynamicBindingPathList: [
{
key: "template.Image1.image",
},
{
key: "template.Text1.text",
},
{
key: "template.Text2.text",
},
],
gridType: "vertical",
enhancements: true,
children: [
{
widgetName: "Canvas1",
displayName: "Canvas",
topRow: 0,
bottomRow: 400,
parentRowSpace: 1,
type: "CANVAS_WIDGET",
canExtend: false,
hideCard: true,
dropDisabled: true,
openParentPropertyPane: true,
minHeight: 400,
noPad: true,
parentColumnSpace: 1,
leftColumn: 0,
children: [
{
boxShadow: "NONE",
widgetName: "Container1",
borderColor: "transparent",
disallowCopy: true,
isCanvas: true,
displayName: "Container",
iconSVG: "/static/media/icon.1977dca3.svg",
topRow: 0,
bottomRow: 12,
dragDisabled: true,
type: "CONTAINER_WIDGET",
hideCard: false,
openParentPropertyPane: true,
isDeletable: false,
animateLoading: true,
leftColumn: 0,
children: [
{
widgetName: "Canvas2",
detachFromLayout: true,
displayName: "Canvas",
widgetId: "vqn2okwc6a",
containerStyle: "none",
topRow: 0,
parentRowSpace: 1,
isVisible: true,
type: "CANVAS_WIDGET",
canExtend: false,
version: 1,
hideCard: true,
parentId: "9e77epyavg",
renderMode: "CANVAS",
isLoading: false,
parentColumnSpace: 1,
leftColumn: 0,
children: [
{
widgetName: "Image1",
displayName: "Image",
iconSVG: "/static/media/icon.52d8fb96.svg",
topRow: 0,
bottomRow: 8.4,
type: "IMAGE_WIDGET",
hideCard: false,
animateLoading: true,
dynamicTriggerPathList: [],
imageShape: "RECTANGLE",
dynamicBindingPathList: [
{
key: "image",
},
],
leftColumn: 0,
defaultImage: `${ASSETS_CDN_URL}/widgets/default.png`,
key: "9cn4ooadxj",
image: "{{currentItem.img}}",
rightColumn: 16,
objectFit: "contain",
widgetId: "yqofym38tn",
logBlackList: {
isVisible: true,
defaultImage: true,
imageShape: true,
maxZoomLevel: true,
enableRotation: true,
enableDownload: true,
objectFit: true,
image: true,
widgetName: true,
version: true,
animateLoading: true,
type: true,
hideCard: true,
displayName: true,
key: true,
iconSVG: true,
isCanvas: true,
dynamicBindingPathList: true,
dynamicTriggerPathList: true,
minHeight: true,
widgetId: true,
renderMode: true,
isLoading: true,
parentColumnSpace: true,
parentRowSpace: true,
leftColumn: true,
rightColumn: true,
topRow: true,
bottomRow: true,
parentId: true,
},
isVisible: true,
version: 1,
parentId: "vqn2okwc6a",
renderMode: "CANVAS",
isLoading: false,
maxZoomLevel: 1,
enableDownload: false,
enableRotation: false,
},
{
widgetName: "Text1",
displayName: "Text",
iconSVG: "/static/media/icon.97c59b52.svg",
topRow: 0,
bottomRow: 4,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
animateLoading: true,
dynamicTriggerPathList: [],
dynamicBindingPathList: [
{
key: "text",
},
],
leftColumn: 16,
shouldTruncate: false,
truncateButtonColor: "#FFC13D",
text: "{{currentItem.name}}",
key: "yd217bk315",
rightColumn: 28,
textAlign: "LEFT",
widgetId: "zeqf6yfm3s",
logBlackList: {
isVisible: true,
text: true,
fontSize: true,
fontStyle: true,
textAlign: true,
textColor: true,
truncateButtonColor: true,
widgetName: true,
shouldScroll: true,
shouldTruncate: true,
version: true,
animateLoading: true,
type: true,
hideCard: true,
displayName: true,
key: true,
iconSVG: true,
isCanvas: true,
textStyle: true,
dynamicBindingPathList: true,
dynamicTriggerPathList: true,
minHeight: true,
widgetId: true,
renderMode: true,
isLoading: true,
parentColumnSpace: true,
parentRowSpace: true,
leftColumn: true,
rightColumn: true,
topRow: true,
bottomRow: true,
parentId: true,
},
isVisible: true,
fontStyle: "BOLD",
textColor: "#231F20",
shouldScroll: false,
version: 1,
parentId: "vqn2okwc6a",
renderMode: "CANVAS",
isLoading: false,
fontSize: "PARAGRAPH",
textStyle: "HEADING",
},
{
widgetName: "Text2",
displayName: "Text",
iconSVG: "/static/media/icon.97c59b52.svg",
topRow: 4,
bottomRow: 8,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
animateLoading: true,
dynamicTriggerPathList: [],
dynamicBindingPathList: [
{
key: "text",
},
],
leftColumn: 16,
shouldTruncate: false,
truncateButtonColor: "#FFC13D",
text: "{{currentItem.id}}",
dynamicHeight: "FIXED",
maxDynamicHeight: 9000,
minDynamicHeight: 4,
key: "yd217bk315",
rightColumn: 24,
textAlign: "LEFT",
widgetId: "8wyekp2o6e",
logBlackList: {
isVisible: true,
text: true,
fontSize: true,
fontStyle: true,
textAlign: true,
textColor: true,
truncateButtonColor: true,
widgetName: true,
shouldScroll: true,
shouldTruncate: true,
version: true,
animateLoading: true,
type: true,
hideCard: true,
displayName: true,
key: true,
iconSVG: true,
isCanvas: true,
textStyle: true,
dynamicBindingPathList: true,
dynamicTriggerPathList: true,
minHeight: true,
widgetId: true,
renderMode: true,
isLoading: true,
parentColumnSpace: true,
parentRowSpace: true,
leftColumn: true,
rightColumn: true,
topRow: true,
bottomRow: true,
parentId: true,
},
isVisible: true,
fontStyle: "BOLD",
textColor: "#231F20",
shouldScroll: false,
version: 1,
parentId: "vqn2okwc6a",
renderMode: "CANVAS",
isLoading: false,
fontSize: "PARAGRAPH",
textStyle: "BODY",
},
],
key: "omhgz5cakp",
},
],
borderWidth: "0",
key: "ca3a42k2a4",
disablePropertyPane: true,
backgroundColor: "white",
rightColumn: 64,
widgetId: "9e77epyavg",
containerStyle: "card",
isVisible: true,
version: 1,
parentId: "q3ype57cdo",
renderMode: "CANVAS",
isLoading: false,
borderRadius: "0",
},
],
key: "omhgz5cakp",
rightColumn: 337.5,
detachFromLayout: true,
widgetId: "q3ype57cdo",
containerStyle: "none",
isVisible: true,
version: 1,
parentId: "iupz1d99ka",
renderMode: "CANVAS",
isLoading: false,
},
],
key: "axex98spx3",
backgroundColor: "transparent",
rightColumn: 63,
itemBackgroundColor: "#FFFFFF",
widgetId: "iupz1d99ka",
isVisible: true,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
},
],
containerStyle: "none",
detachFromLayout: true,
dynamicBindingPathList: [],
dynamicTriggerPathList: [],
leftColumn: 0,
minHeight: 640,
parentColumnSpace: 1,
parentRowSpace: 1,
rightColumn: 912,
snapColumns: 64,
snapRows: 125,
topRow: 0,
type: "CANVAS_WIDGET",
version: currentVersion,
widgetId: "0",
widgetName: "MainContainer",
renderMode: "CANVAS",
isLoading: false,
};
const expectedNextDSL: ContainerWidgetProps<WidgetProps> = {
backgroundColor: "none",
bottomRow: 740,
canExtend: true,
version: nextVersion,
children: [
{
widgetName: "Input1",
displayName: "Input",
iconSVG: "/static/media/icon.9f505595.svg",
topRow: 18,
bottomRow: 22,
parentRowSpace: 10,
autoFocus: false,
type: "INPUT_WIDGET",
hideCard: false,
animateLoading: true,
parentColumnSpace: 15.0625,
dynamicTriggerPathList: [],
resetOnSubmit: true,
leftColumn: 23,
labelTextSize: "0.875rem",
dynamicBindingPathList: [
{
key: "accentColor",
},
],
labelStyle: "",
inputType: "TEXT",
isDisabled: false,
key: "ftefjorusw",
isRequired: false,
rightColumn: 43,
widgetId: "lz9hvhcltl",
isVisible: true,
label: "",
allowCurrencyChange: false,
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
iconAlign: "left",
defaultText: "",
borderRadius: "0px",
boxShadow: "none",
accentColor: "{{appsmith.theme.colors.primaryColor}}",
},
{
widgetName: "Button1",
onClick:
'{{Api1.run(()=>{\ndownload((\nfunction(){\nreturn "data:image/jpeg;base64,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"\n}\n)(), "test.png", "image/png")\n})}}',
buttonColor: "#03B365",
dynamicPropertyPathList: [
{
key: "onClick",
},
],
displayName: "Button",
iconSVG: "/static/media/icon.cca02633.svg",
topRow: 29,
bottomRow: 33,
tooltip: "",
parentRowSpace: 10,
type: "BUTTON_WIDGET",
hideCard: false,
animateLoading: true,
parentColumnSpace: 14.0625,
dynamicTriggerPathList: [
{
key: "onClick",
},
],
leftColumn: 20,
dynamicBindingPathList: [],
text: "Submit",
isDisabled: false,
key: "pg01cxraj1",
labelTextSize: "0.875rem",
rightColumn: 36,
isDefaultClickDisabled: true,
widgetId: "d229q1ydul",
isVisible: true,
recaptchaType: "V3",
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
buttonVariant: "PRIMARY",
placement: "CENTER",
borderRadius: "0px",
boxShadow: "none",
},
{
widgetName: "Input2",
displayName: "Input",
iconSVG: "/static/media/icon.9f505595.svg",
topRow: 44,
bottomRow: 48,
parentRowSpace: 10,
autoFocus: false,
type: "INPUT_WIDGET",
hideCard: false,
animateLoading: true,
parentColumnSpace: 14.0625,
resetOnSubmit: true,
leftColumn: 9,
labelTextSize: "0.875rem",
labelStyle: "",
inputType: "TEXT",
isDisabled: false,
key: "519sr07k1u",
isRequired: false,
rightColumn: 29,
widgetId: "eenq4c022d",
isVisible: true,
label: "",
allowCurrencyChange: false,
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
iconAlign: "left",
defaultText: "",
borderRadius: "0px",
boxShadow: "none",
accentColor: "{{appsmith.theme.colors.primaryColor}}",
dynamicBindingPathList: [
{
key: "accentColor",
},
],
},
{
widgetName: "List1",
template: {
Image1: {
isVisible: true,
defaultImage: `${ASSETS_CDN_URL}/widgets/default.png`,
imageShape: "RECTANGLE",
maxZoomLevel: 1,
enableRotation: false,
enableDownload: false,
objectFit: "contain",
image: "{{List1.listData.map((currentItem) => currentItem.img)}}",
widgetName: "Image1",
version: 1,
animateLoading: true,
type: "IMAGE_WIDGET",
hideCard: false,
displayName: "Image",
key: "9cn4ooadxj",
iconSVG: "/static/media/icon.52d8fb96.svg",
dynamicBindingPathList: [
{
key: "image",
},
],
dynamicTriggerPathList: [],
widgetId: "yqofym38tn",
renderMode: "CANVAS",
isLoading: false,
leftColumn: 0,
rightColumn: 16,
topRow: 0,
bottomRow: 8.4,
parentId: "vqn2okwc6a",
},
Text1: {
isVisible: true,
text: "{{List1.listData.map((currentItem) => currentItem.name)}}",
fontSize: "PARAGRAPH",
fontStyle: "BOLD",
textAlign: "LEFT",
textColor: "#231F20",
truncateButtonColor: "#FFC13D",
widgetName: "Text1",
shouldScroll: false,
shouldTruncate: false,
version: 1,
animateLoading: true,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
displayName: "Text",
key: "yd217bk315",
iconSVG: "/static/media/icon.97c59b52.svg",
textStyle: "HEADING",
dynamicBindingPathList: [
{
key: "text",
},
],
dynamicTriggerPathList: [],
widgetId: "zeqf6yfm3s",
renderMode: "CANVAS",
isLoading: false,
leftColumn: 16,
rightColumn: 28,
topRow: 0,
bottomRow: 4,
parentId: "vqn2okwc6a",
},
Text2: {
isVisible: true,
text: "{{List1.listData.map((currentItem) => currentItem.id)}}",
fontSize: "PARAGRAPH",
fontStyle: "BOLD",
textAlign: "LEFT",
textColor: "#231F20",
truncateButtonColor: "#FFC13D",
widgetName: "Text2",
shouldScroll: false,
shouldTruncate: false,
version: 1,
animateLoading: true,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
displayName: "Text",
key: "yd217bk315",
iconSVG: "/static/media/icon.97c59b52.svg",
textStyle: "BODY",
dynamicBindingPathList: [
{
key: "text",
},
],
dynamicTriggerPathList: [],
widgetId: "8wyekp2o6e",
renderMode: "CANVAS",
isLoading: false,
leftColumn: 16,
rightColumn: 24,
topRow: 4,
bottomRow: 8,
parentId: "vqn2okwc6a",
},
},
listData: [
{
id: "001",
name: "Blue",
img: `${ASSETS_CDN_URL}/widgets/default.png`,
},
{
id: "002",
name: "Green",
img: `${ASSETS_CDN_URL}/widgets/default.png`,
},
{
id: "003",
name: "Red",
img: `${ASSETS_CDN_URL}/widgets/default.png`,
},
],
isCanvas: true,
displayName: "List",
iconSVG: "/static/media/icon.9925ee17.svg",
topRow: 34,
bottomRow: 74,
parentRowSpace: 10,
type: "LIST_WIDGET",
hideCard: false,
gridGap: 0,
animateLoading: true,
parentColumnSpace: 14.0625,
leftColumn: 39,
dynamicBindingPathList: [
{
key: "template.Image1.image",
},
{
key: "template.Text1.text",
},
{
key: "template.Text2.text",
},
{
key: "accentColor",
},
],
gridType: "vertical",
enhancements: true,
children: [
{
widgetName: "Canvas1",
displayName: "Canvas",
topRow: 0,
bottomRow: 400,
parentRowSpace: 1,
type: "CANVAS_WIDGET",
canExtend: false,
hideCard: true,
dropDisabled: true,
openParentPropertyPane: true,
minHeight: 400,
noPad: true,
parentColumnSpace: 1,
leftColumn: 0,
children: [
{
boxShadow: "none",
widgetName: "Container1",
borderColor: "transparent",
disallowCopy: true,
isCanvas: true,
displayName: "Container",
iconSVG: "/static/media/icon.1977dca3.svg",
dynamicPropertyPathList: [
{
key: "borderRadius",
},
],
topRow: 0,
bottomRow: 12,
dragDisabled: true,
type: "CONTAINER_WIDGET",
hideCard: false,
openParentPropertyPane: true,
isDeletable: false,
animateLoading: true,
leftColumn: 0,
dynamicHeight: "FIXED",
maxDynamicHeight: 9000,
minDynamicHeight: 4,
children: [
{
widgetName: "Canvas2",
detachFromLayout: true,
displayName: "Canvas",
widgetId: "vqn2okwc6a",
containerStyle: "none",
topRow: 0,
parentRowSpace: 1,
isVisible: true,
type: "CANVAS_WIDGET",
canExtend: false,
version: 1,
hideCard: true,
parentId: "9e77epyavg",
renderMode: "CANVAS",
isLoading: false,
parentColumnSpace: 1,
leftColumn: 0,
children: [
{
widgetName: "Image1",
displayName: "Image",
iconSVG: "/static/media/icon.52d8fb96.svg",
topRow: 0,
bottomRow: 8.4,
type: "IMAGE_WIDGET",
hideCard: false,
animateLoading: true,
dynamicTriggerPathList: [],
imageShape: "RECTANGLE",
dynamicBindingPathList: [
{
key: "image",
},
],
leftColumn: 0,
defaultImage: `${ASSETS_CDN_URL}/widgets/default.png`,
key: "9cn4ooadxj",
labelTextSize: "0.875rem",
image: "{{currentItem.img}}",
rightColumn: 16,
objectFit: "contain",
widgetId: "yqofym38tn",
logBlackList: {
isVisible: true,
defaultImage: true,
imageShape: true,
maxZoomLevel: true,
enableRotation: true,
enableDownload: true,
objectFit: true,
image: true,
widgetName: true,
version: true,
animateLoading: true,
type: true,
hideCard: true,
displayName: true,
key: true,
iconSVG: true,
isCanvas: true,
dynamicBindingPathList: true,
dynamicTriggerPathList: true,
minHeight: true,
widgetId: true,
renderMode: true,
isLoading: true,
parentColumnSpace: true,
parentRowSpace: true,
leftColumn: true,
rightColumn: true,
topRow: true,
bottomRow: true,
parentId: true,
},
isVisible: true,
version: 1,
parentId: "vqn2okwc6a",
renderMode: "CANVAS",
isLoading: false,
maxZoomLevel: 1,
enableDownload: false,
enableRotation: false,
borderRadius: "0px",
boxShadow: "none",
dynamicHeight: "FIXED",
},
{
widgetName: "Text1",
displayName: "Text",
iconSVG: "/static/media/icon.97c59b52.svg",
topRow: 0,
bottomRow: 4,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
animateLoading: true,
dynamicTriggerPathList: [],
dynamicBindingPathList: [
{
key: "text",
},
],
dynamicHeight: "FIXED",
maxDynamicHeight: 9000,
minDynamicHeight: 4,
leftColumn: 16,
truncateButtonColor: "#FFC13D",
text: "{{currentItem.name}}",
key: "yd217bk315",
labelTextSize: "0.875rem",
rightColumn: 28,
textAlign: "LEFT",
widgetId: "zeqf6yfm3s",
logBlackList: {
isVisible: true,
text: true,
fontSize: true,
fontStyle: true,
textAlign: true,
textColor: true,
truncateButtonColor: true,
widgetName: true,
shouldScroll: true,
shouldTruncate: true,
version: true,
animateLoading: true,
type: true,
hideCard: true,
displayName: true,
key: true,
iconSVG: true,
isCanvas: true,
textStyle: true,
dynamicBindingPathList: true,
dynamicTriggerPathList: true,
minHeight: true,
widgetId: true,
renderMode: true,
isLoading: true,
parentColumnSpace: true,
parentRowSpace: true,
leftColumn: true,
rightColumn: true,
topRow: true,
bottomRow: true,
parentId: true,
},
isVisible: true,
fontStyle: "BOLD",
textColor: "#231F20",
overflow: OverflowTypes.NONE,
version: 1,
parentId: "vqn2okwc6a",
renderMode: "CANVAS",
isLoading: false,
fontSize: "0.875rem",
textStyle: "HEADING",
borderRadius: "0px",
boxShadow: "none",
},
{
widgetName: "Text2",
displayName: "Text",
iconSVG: "/static/media/icon.97c59b52.svg",
topRow: 4,
bottomRow: 8,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
animateLoading: true,
dynamicTriggerPathList: [],
dynamicBindingPathList: [
{
key: "text",
},
],
dynamicHeight: "FIXED",
maxDynamicHeight: 9000,
minDynamicHeight: 4,
leftColumn: 16,
truncateButtonColor: "#FFC13D",
text: "{{currentItem.id}}",
key: "yd217bk315",
labelTextSize: "0.875rem",
rightColumn: 24,
textAlign: "LEFT",
widgetId: "8wyekp2o6e",
logBlackList: {
isVisible: true,
text: true,
fontSize: true,
fontStyle: true,
textAlign: true,
textColor: true,
truncateButtonColor: true,
widgetName: true,
shouldScroll: true,
shouldTruncate: true,
version: true,
animateLoading: true,
type: true,
hideCard: true,
displayName: true,
key: true,
iconSVG: true,
isCanvas: true,
textStyle: true,
dynamicBindingPathList: true,
dynamicTriggerPathList: true,
minHeight: true,
widgetId: true,
renderMode: true,
isLoading: true,
parentColumnSpace: true,
parentRowSpace: true,
leftColumn: true,
rightColumn: true,
topRow: true,
bottomRow: true,
parentId: true,
},
isVisible: true,
fontStyle: "BOLD",
textColor: "#231F20",
overflow: OverflowTypes.NONE,
version: 1,
parentId: "vqn2okwc6a",
renderMode: "CANVAS",
isLoading: false,
fontSize: "0.875rem",
textStyle: "BODY",
borderRadius: "0px",
boxShadow: "none",
},
],
key: "omhgz5cakp",
labelTextSize: "0.875rem",
borderRadius: "0px",
boxShadow: "none",
},
],
borderWidth: "0",
key: "ca3a42k2a4",
labelTextSize: "0.875rem",
disablePropertyPane: true,
backgroundColor: "white",
rightColumn: 64,
widgetId: "9e77epyavg",
containerStyle: "card",
isVisible: true,
version: 1,
parentId: "q3ype57cdo",
renderMode: "CANVAS",
isLoading: false,
borderRadius: "0px",
},
],
key: "omhgz5cakp",
labelTextSize: "0.875rem",
rightColumn: 337.5,
detachFromLayout: true,
widgetId: "q3ype57cdo",
containerStyle: "none",
isVisible: true,
version: 1,
parentId: "iupz1d99ka",
renderMode: "CANVAS",
isLoading: false,
borderRadius: "0px",
boxShadow: "none",
},
],
privateWidgets: {
Image1: true,
Text1: true,
Text2: true,
},
key: "axex98spx3",
labelTextSize: "0.875rem",
backgroundColor: "transparent",
rightColumn: 63,
itemBackgroundColor: "#FFFFFF",
widgetId: "iupz1d99ka",
isVisible: true,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
version: 1,
borderRadius: "0px",
boxShadow: "none",
accentColor: "{{appsmith.theme.colors.primaryColor}}",
},
],
containerStyle: "none",
detachFromLayout: true,
dynamicBindingPathList: [],
dynamicTriggerPathList: [],
leftColumn: 0,
minHeight: 640,
parentColumnSpace: 1,
parentRowSpace: 1,
rightColumn: 912,
snapColumns: 64,
snapRows: 125,
topRow: 0,
type: "CANVAS_WIDGET",
widgetId: "0",
widgetName: "MainContainer",
renderMode: RenderModes.CANVAS,
isLoading: false,
};
const actualNextDsl = transformDSL(currentDSL);
expect(actualNextDsl).toEqual(expectedNextDSL);
});
it("transformDSL for theming v1", () => {
const currentVersion = 53;
const nextVersion = LATEST_PAGE_VERSION;
const currentDSL: ContainerWidgetProps<WidgetProps> = {
backgroundColor: "none",
bottomRow: 740,
canExtend: true,
children: [
{
widgetName: "Input1",
displayName: "Input",
iconSVG: "/static/media/icon.9f505595.svg",
topRow: 18,
bottomRow: 22,
parentRowSpace: 10,
autoFocus: false,
type: "INPUT_WIDGET",
hideCard: false,
animateLoading: true,
parentColumnSpace: 15.0625,
dynamicTriggerPathList: [],
resetOnSubmit: true,
leftColumn: 23,
dynamicBindingPathList: [],
labelStyle: "",
inputType: "TEXT",
isDisabled: false,
key: "ftefjorusw",
isRequired: false,
rightColumn: 43,
widgetId: "lz9hvhcltl",
isVisible: true,
label: "",
allowCurrencyChange: false,
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
iconAlign: "left",
defaultText: "",
},
{
widgetName: "Button1",
onClick:
'{{Api1.run(()=>{\ndownload((\nfunction(){\nreturn "data:image/jpeg;base64,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"\n}\n)(), "test.png", "image/png")\n})}}',
buttonColor: "#03B365",
dynamicPropertyPathList: [
{
key: "onClick",
},
],
displayName: "Button",
iconSVG: "/static/media/icon.cca02633.svg",
topRow: 29,
bottomRow: 33,
tooltip: "",
parentRowSpace: 10,
type: "BUTTON_WIDGET",
hideCard: false,
animateLoading: true,
parentColumnSpace: 14.0625,
dynamicTriggerPathList: [
{
key: "onClick",
},
],
leftColumn: 20,
dynamicBindingPathList: [],
text: "Submit",
isDisabled: false,
key: "pg01cxraj1",
rightColumn: 36,
isDefaultClickDisabled: true,
widgetId: "d229q1ydul",
isVisible: true,
recaptchaType: "V3",
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
buttonVariant: "PRIMARY",
placement: "CENTER",
},
{
widgetName: "Input2",
displayName: "Input",
iconSVG: "/static/media/icon.9f505595.svg",
topRow: 44,
bottomRow: 48,
parentRowSpace: 10,
autoFocus: false,
type: "INPUT_WIDGET",
hideCard: false,
animateLoading: true,
parentColumnSpace: 14.0625,
resetOnSubmit: true,
leftColumn: 9,
labelStyle: "",
inputType: "TEXT",
isDisabled: false,
key: "519sr07k1u",
isRequired: false,
rightColumn: 29,
widgetId: "eenq4c022d",
isVisible: true,
label: "",
allowCurrencyChange: false,
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
iconAlign: "left",
defaultText: "",
},
{
version: 1,
template: {
Image1: {
isVisible: true,
defaultImage: `${ASSETS_CDN_URL}/widgets/default.png`,
imageShape: "RECTANGLE",
maxZoomLevel: 1,
enableRotation: false,
enableDownload: false,
objectFit: "contain",
image: "{{List1.listData.map((currentItem) => currentItem.img)}}",
widgetName: "Image1",
version: 1,
animateLoading: true,
type: "IMAGE_WIDGET",
hideCard: false,
displayName: "Image",
key: "9cn4ooadxj",
iconSVG: "/static/media/icon.52d8fb96.svg",
dynamicBindingPathList: [
{
key: "image",
},
],
dynamicTriggerPathList: [],
widgetId: "yqofym38tn",
renderMode: "CANVAS",
isLoading: false,
leftColumn: 0,
rightColumn: 16,
topRow: 0,
bottomRow: 8.4,
parentId: "vqn2okwc6a",
},
Text1: {
isVisible: true,
text: "{{List1.listData.map((currentItem) => currentItem.name)}}",
fontSize: "PARAGRAPH",
fontStyle: "BOLD",
textAlign: "LEFT",
textColor: "#231F20",
truncateButtonColor: "#FFC13D",
widgetName: "Text1",
shouldScroll: false,
shouldTruncate: false,
version: 1,
animateLoading: true,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
displayName: "Text",
key: "yd217bk315",
iconSVG: "/static/media/icon.97c59b52.svg",
textStyle: "HEADING",
dynamicBindingPathList: [
{
key: "text",
},
],
dynamicTriggerPathList: [],
widgetId: "zeqf6yfm3s",
renderMode: "CANVAS",
isLoading: false,
leftColumn: 16,
rightColumn: 28,
topRow: 0,
bottomRow: 4,
parentId: "vqn2okwc6a",
},
Text2: {
isVisible: true,
text: "{{List1.listData.map((currentItem) => currentItem.id)}}",
fontSize: "PARAGRAPH",
fontStyle: "BOLD",
textAlign: "LEFT",
textColor: "#231F20",
truncateButtonColor: "#FFC13D",
widgetName: "Text2",
shouldScroll: false,
shouldTruncate: false,
version: 1,
animateLoading: true,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
displayName: "Text",
key: "yd217bk315",
iconSVG: "/static/media/icon.97c59b52.svg",
textStyle: "BODY",
dynamicBindingPathList: [
{
key: "text",
},
],
dynamicTriggerPathList: [],
widgetId: "8wyekp2o6e",
renderMode: "CANVAS",
isLoading: false,
leftColumn: 16,
rightColumn: 24,
topRow: 4,
bottomRow: 8,
parentId: "vqn2okwc6a",
},
},
widgetName: "List1",
listData: [
{
id: "001",
name: "Blue",
img: `${ASSETS_CDN_URL}/widgets/default.png`,
},
{
id: "002",
name: "Green",
img: `${ASSETS_CDN_URL}/widgets/default.png`,
},
{
id: "003",
name: "Red",
img: `${ASSETS_CDN_URL}/widgets/default.png`,
},
],
isCanvas: true,
displayName: "List",
iconSVG: "/static/media/icon.9925ee17.svg",
topRow: 34,
bottomRow: 74,
parentRowSpace: 10,
type: "LIST_WIDGET",
hideCard: false,
gridGap: 0,
animateLoading: true,
parentColumnSpace: 14.0625,
leftColumn: 39,
dynamicBindingPathList: [
{
key: "template.Image1.image",
},
{
key: "template.Text1.text",
},
{
key: "template.Text2.text",
},
],
gridType: "vertical",
enhancements: true,
children: [
{
widgetName: "Canvas1",
displayName: "Canvas",
topRow: 0,
bottomRow: 400,
parentRowSpace: 1,
type: "CANVAS_WIDGET",
canExtend: false,
hideCard: true,
dropDisabled: true,
openParentPropertyPane: true,
minHeight: 400,
noPad: true,
parentColumnSpace: 1,
leftColumn: 0,
children: [
{
boxShadow: "NONE",
widgetName: "Container1",
borderColor: "transparent",
disallowCopy: true,
isCanvas: true,
displayName: "Container",
iconSVG: "/static/media/icon.1977dca3.svg",
topRow: 0,
bottomRow: 12,
dragDisabled: true,
type: "CONTAINER_WIDGET",
hideCard: false,
openParentPropertyPane: true,
isDeletable: false,
animateLoading: true,
leftColumn: 0,
children: [
{
widgetName: "Canvas2",
detachFromLayout: true,
displayName: "Canvas",
widgetId: "vqn2okwc6a",
containerStyle: "none",
topRow: 0,
parentRowSpace: 1,
isVisible: true,
type: "CANVAS_WIDGET",
canExtend: false,
version: 1,
hideCard: true,
parentId: "9e77epyavg",
renderMode: "CANVAS",
isLoading: false,
parentColumnSpace: 1,
leftColumn: 0,
children: [
{
widgetName: "Image1",
displayName: "Image",
iconSVG: "/static/media/icon.52d8fb96.svg",
topRow: 0,
bottomRow: 8.4,
type: "IMAGE_WIDGET",
hideCard: false,
animateLoading: true,
dynamicTriggerPathList: [],
imageShape: "RECTANGLE",
dynamicBindingPathList: [
{
key: "image",
},
],
leftColumn: 0,
defaultImage: `${ASSETS_CDN_URL}/widgets/default.png`,
key: "9cn4ooadxj",
image: "{{currentItem.img}}",
rightColumn: 16,
objectFit: "contain",
widgetId: "yqofym38tn",
logBlackList: {
isVisible: true,
defaultImage: true,
imageShape: true,
maxZoomLevel: true,
enableRotation: true,
enableDownload: true,
objectFit: true,
image: true,
widgetName: true,
version: true,
animateLoading: true,
type: true,
hideCard: true,
displayName: true,
key: true,
iconSVG: true,
isCanvas: true,
dynamicBindingPathList: true,
dynamicTriggerPathList: true,
minHeight: true,
widgetId: true,
renderMode: true,
isLoading: true,
parentColumnSpace: true,
parentRowSpace: true,
leftColumn: true,
rightColumn: true,
topRow: true,
bottomRow: true,
parentId: true,
},
isVisible: true,
version: 1,
parentId: "vqn2okwc6a",
renderMode: "CANVAS",
isLoading: false,
maxZoomLevel: 1,
enableDownload: false,
enableRotation: false,
dynamicHeight: "FIXED",
},
{
widgetName: "Text1",
displayName: "Text",
iconSVG: "/static/media/icon.97c59b52.svg",
topRow: 0,
bottomRow: 4,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
animateLoading: true,
dynamicTriggerPathList: [],
dynamicBindingPathList: [
{
key: "text",
},
],
leftColumn: 16,
shouldTruncate: false,
truncateButtonColor: "#FFC13D",
text: "{{currentItem.name}}",
key: "yd217bk315",
rightColumn: 28,
textAlign: "LEFT",
widgetId: "zeqf6yfm3s",
logBlackList: {
isVisible: true,
text: true,
fontSize: true,
fontStyle: true,
textAlign: true,
textColor: true,
truncateButtonColor: true,
widgetName: true,
shouldScroll: true,
shouldTruncate: true,
version: true,
animateLoading: true,
type: true,
hideCard: true,
displayName: true,
key: true,
iconSVG: true,
isCanvas: true,
textStyle: true,
dynamicBindingPathList: true,
dynamicTriggerPathList: true,
minHeight: true,
widgetId: true,
renderMode: true,
isLoading: true,
parentColumnSpace: true,
parentRowSpace: true,
leftColumn: true,
rightColumn: true,
topRow: true,
bottomRow: true,
parentId: true,
},
isVisible: true,
fontStyle: "BOLD",
textColor: "#231F20",
shouldScroll: false,
version: 1,
parentId: "vqn2okwc6a",
renderMode: "CANVAS",
isLoading: false,
fontSize: "PARAGRAPH",
textStyle: "HEADING",
dynamicHeight: "FIXED",
},
{
widgetName: "Text2",
displayName: "Text",
iconSVG: "/static/media/icon.97c59b52.svg",
topRow: 4,
bottomRow: 8,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
animateLoading: true,
dynamicTriggerPathList: [],
dynamicBindingPathList: [
{
key: "text",
},
],
leftColumn: 16,
shouldTruncate: false,
truncateButtonColor: "#FFC13D",
text: "{{currentItem.id}}",
key: "yd217bk315",
rightColumn: 24,
textAlign: "LEFT",
widgetId: "8wyekp2o6e",
logBlackList: {
isVisible: true,
text: true,
fontSize: true,
fontStyle: true,
textAlign: true,
textColor: true,
truncateButtonColor: true,
widgetName: true,
shouldScroll: true,
shouldTruncate: true,
version: true,
animateLoading: true,
type: true,
hideCard: true,
displayName: true,
key: true,
iconSVG: true,
isCanvas: true,
textStyle: true,
dynamicBindingPathList: true,
dynamicTriggerPathList: true,
minHeight: true,
widgetId: true,
renderMode: true,
isLoading: true,
parentColumnSpace: true,
parentRowSpace: true,
leftColumn: true,
rightColumn: true,
topRow: true,
bottomRow: true,
parentId: true,
},
isVisible: true,
fontStyle: "BOLD",
textColor: "#231F20",
shouldScroll: false,
version: 1,
parentId: "vqn2okwc6a",
renderMode: "CANVAS",
isLoading: false,
fontSize: "PARAGRAPH",
textStyle: "BODY",
dynamicHeight: "FIXED",
},
],
key: "omhgz5cakp",
},
],
borderWidth: "0",
key: "ca3a42k2a4",
disablePropertyPane: true,
backgroundColor: "white",
rightColumn: 64,
widgetId: "9e77epyavg",
containerStyle: "card",
isVisible: true,
version: 1,
parentId: "q3ype57cdo",
renderMode: "CANVAS",
isLoading: false,
borderRadius: "0",
},
],
key: "omhgz5cakp",
rightColumn: 337.5,
detachFromLayout: true,
widgetId: "q3ype57cdo",
containerStyle: "none",
isVisible: true,
version: 1,
parentId: "iupz1d99ka",
renderMode: "CANVAS",
isLoading: false,
},
],
key: "axex98spx3",
backgroundColor: "transparent",
rightColumn: 63,
itemBackgroundColor: "#FFFFFF",
widgetId: "iupz1d99ka",
isVisible: true,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
},
],
containerStyle: "none",
detachFromLayout: true,
dynamicBindingPathList: [],
dynamicTriggerPathList: [],
leftColumn: 0,
minHeight: 640,
parentColumnSpace: 1,
parentRowSpace: 1,
rightColumn: 912,
snapColumns: 64,
snapRows: 125,
topRow: 0,
type: "CANVAS_WIDGET",
version: currentVersion,
widgetId: "0",
widgetName: "MainContainer",
renderMode: "CANVAS",
isLoading: false,
};
const expectedNextDSL: ContainerWidgetProps<WidgetProps> = {
backgroundColor: "none",
bottomRow: 740,
canExtend: true,
version: nextVersion,
children: [
{
widgetName: "Input1",
displayName: "Input",
iconSVG: "/static/media/icon.9f505595.svg",
topRow: 18,
bottomRow: 22,
parentRowSpace: 10,
autoFocus: false,
type: "INPUT_WIDGET",
hideCard: false,
animateLoading: true,
parentColumnSpace: 15.0625,
dynamicTriggerPathList: [],
resetOnSubmit: true,
leftColumn: 23,
dynamicBindingPathList: [
{
key: "accentColor",
},
],
labelStyle: "",
inputType: "TEXT",
isDisabled: false,
key: "ftefjorusw",
labelTextSize: "0.875rem",
isRequired: false,
rightColumn: 43,
widgetId: "lz9hvhcltl",
isVisible: true,
label: "",
allowCurrencyChange: false,
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
iconAlign: "left",
defaultText: "",
borderRadius: "0px",
boxShadow: "none",
accentColor: "{{appsmith.theme.colors.primaryColor}}",
},
{
widgetName: "Button1",
onClick:
'{{Api1.run(()=>{\ndownload((\nfunction(){\nreturn "data:image/jpeg;base64,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"\n}\n)(), "test.png", "image/png")\n})}}',
buttonColor: "#03B365",
dynamicPropertyPathList: [
{
key: "onClick",
},
],
displayName: "Button",
iconSVG: "/static/media/icon.cca02633.svg",
topRow: 29,
bottomRow: 33,
tooltip: "",
parentRowSpace: 10,
type: "BUTTON_WIDGET",
hideCard: false,
animateLoading: true,
parentColumnSpace: 14.0625,
dynamicTriggerPathList: [
{
key: "onClick",
},
],
leftColumn: 20,
dynamicBindingPathList: [],
text: "Submit",
isDisabled: false,
key: "pg01cxraj1",
labelTextSize: "0.875rem",
rightColumn: 36,
isDefaultClickDisabled: true,
widgetId: "d229q1ydul",
isVisible: true,
recaptchaType: "V3",
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
buttonVariant: "PRIMARY",
placement: "CENTER",
borderRadius: "0px",
boxShadow: "none",
},
{
widgetName: "Input2",
displayName: "Input",
iconSVG: "/static/media/icon.9f505595.svg",
topRow: 44,
bottomRow: 48,
parentRowSpace: 10,
autoFocus: false,
type: "INPUT_WIDGET",
hideCard: false,
animateLoading: true,
parentColumnSpace: 14.0625,
resetOnSubmit: true,
leftColumn: 9,
labelStyle: "",
inputType: "TEXT",
isDisabled: false,
key: "519sr07k1u",
labelTextSize: "0.875rem",
isRequired: false,
rightColumn: 29,
widgetId: "eenq4c022d",
isVisible: true,
label: "",
allowCurrencyChange: false,
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
iconAlign: "left",
defaultText: "",
borderRadius: "0px",
boxShadow: "none",
accentColor: "{{appsmith.theme.colors.primaryColor}}",
dynamicBindingPathList: [
{
key: "accentColor",
},
],
},
{
widgetName: "List1",
template: {
Image1: {
isVisible: true,
defaultImage: `${ASSETS_CDN_URL}/widgets/default.png`,
imageShape: "RECTANGLE",
maxZoomLevel: 1,
enableRotation: false,
enableDownload: false,
objectFit: "contain",
image: "{{List1.listData.map((currentItem) => currentItem.img)}}",
widgetName: "Image1",
version: 1,
animateLoading: true,
type: "IMAGE_WIDGET",
hideCard: false,
displayName: "Image",
key: "9cn4ooadxj",
iconSVG: "/static/media/icon.52d8fb96.svg",
dynamicBindingPathList: [
{
key: "image",
},
],
dynamicTriggerPathList: [],
widgetId: "yqofym38tn",
renderMode: "CANVAS",
isLoading: false,
leftColumn: 0,
rightColumn: 16,
topRow: 0,
bottomRow: 8.4,
parentId: "vqn2okwc6a",
},
Text1: {
isVisible: true,
text: "{{List1.listData.map((currentItem) => currentItem.name)}}",
fontSize: "PARAGRAPH",
fontStyle: "BOLD",
textAlign: "LEFT",
textColor: "#231F20",
truncateButtonColor: "#FFC13D",
widgetName: "Text1",
shouldScroll: false,
shouldTruncate: false,
version: 1,
animateLoading: true,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
displayName: "Text",
key: "yd217bk315",
iconSVG: "/static/media/icon.97c59b52.svg",
textStyle: "HEADING",
dynamicBindingPathList: [
{
key: "text",
},
],
dynamicTriggerPathList: [],
widgetId: "zeqf6yfm3s",
renderMode: "CANVAS",
isLoading: false,
leftColumn: 16,
rightColumn: 28,
topRow: 0,
bottomRow: 4,
parentId: "vqn2okwc6a",
},
Text2: {
isVisible: true,
text: "{{List1.listData.map((currentItem) => currentItem.id)}}",
fontSize: "PARAGRAPH",
fontStyle: "BOLD",
textAlign: "LEFT",
textColor: "#231F20",
truncateButtonColor: "#FFC13D",
widgetName: "Text2",
shouldScroll: false,
shouldTruncate: false,
version: 1,
animateLoading: true,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
displayName: "Text",
key: "yd217bk315",
iconSVG: "/static/media/icon.97c59b52.svg",
textStyle: "BODY",
dynamicBindingPathList: [
{
key: "text",
},
],
dynamicTriggerPathList: [],
widgetId: "8wyekp2o6e",
renderMode: "CANVAS",
isLoading: false,
leftColumn: 16,
rightColumn: 24,
topRow: 4,
bottomRow: 8,
parentId: "vqn2okwc6a",
},
},
listData: [
{
id: "001",
name: "Blue",
img: `${ASSETS_CDN_URL}/widgets/default.png`,
},
{
id: "002",
name: "Green",
img: `${ASSETS_CDN_URL}/widgets/default.png`,
},
{
id: "003",
name: "Red",
img: `${ASSETS_CDN_URL}/widgets/default.png`,
},
],
isCanvas: true,
displayName: "List",
iconSVG: "/static/media/icon.9925ee17.svg",
topRow: 34,
bottomRow: 74,
parentRowSpace: 10,
type: "LIST_WIDGET",
hideCard: false,
gridGap: 0,
animateLoading: true,
parentColumnSpace: 14.0625,
leftColumn: 39,
dynamicBindingPathList: [
{
key: "template.Image1.image",
},
{
key: "template.Text1.text",
},
{
key: "template.Text2.text",
},
{
key: "accentColor",
},
],
gridType: "vertical",
enhancements: true,
children: [
{
widgetName: "Canvas1",
displayName: "Canvas",
topRow: 0,
bottomRow: 400,
parentRowSpace: 1,
type: "CANVAS_WIDGET",
canExtend: false,
hideCard: true,
dropDisabled: true,
openParentPropertyPane: true,
minHeight: 400,
noPad: true,
parentColumnSpace: 1,
leftColumn: 0,
children: [
{
boxShadow: "none",
widgetName: "Container1",
borderColor: "transparent",
disallowCopy: true,
isCanvas: true,
displayName: "Container",
iconSVG: "/static/media/icon.1977dca3.svg",
dynamicPropertyPathList: [
{
key: "borderRadius",
},
],
topRow: 0,
bottomRow: 12,
dragDisabled: true,
type: "CONTAINER_WIDGET",
hideCard: false,
openParentPropertyPane: true,
isDeletable: false,
animateLoading: true,
leftColumn: 0,
dynamicHeight: "FIXED",
maxDynamicHeight: 9000,
minDynamicHeight: 4,
children: [
{
widgetName: "Canvas2",
detachFromLayout: true,
displayName: "Canvas",
widgetId: "vqn2okwc6a",
containerStyle: "none",
topRow: 0,
parentRowSpace: 1,
isVisible: true,
type: "CANVAS_WIDGET",
canExtend: false,
version: 1,
hideCard: true,
parentId: "9e77epyavg",
renderMode: "CANVAS",
isLoading: false,
parentColumnSpace: 1,
leftColumn: 0,
children: [
{
widgetName: "Image1",
displayName: "Image",
iconSVG: "/static/media/icon.52d8fb96.svg",
topRow: 0,
bottomRow: 8.4,
type: "IMAGE_WIDGET",
hideCard: false,
animateLoading: true,
dynamicTriggerPathList: [],
imageShape: "RECTANGLE",
dynamicBindingPathList: [
{
key: "image",
},
],
leftColumn: 0,
defaultImage: `${ASSETS_CDN_URL}/widgets/default.png`,
key: "9cn4ooadxj",
labelTextSize: "0.875rem",
image: "{{currentItem.img}}",
rightColumn: 16,
objectFit: "contain",
widgetId: "yqofym38tn",
logBlackList: {
isVisible: true,
defaultImage: true,
imageShape: true,
maxZoomLevel: true,
enableRotation: true,
enableDownload: true,
objectFit: true,
image: true,
widgetName: true,
version: true,
animateLoading: true,
type: true,
hideCard: true,
displayName: true,
key: true,
iconSVG: true,
isCanvas: true,
dynamicBindingPathList: true,
dynamicTriggerPathList: true,
minHeight: true,
widgetId: true,
renderMode: true,
isLoading: true,
parentColumnSpace: true,
parentRowSpace: true,
leftColumn: true,
rightColumn: true,
topRow: true,
bottomRow: true,
parentId: true,
},
isVisible: true,
version: 1,
parentId: "vqn2okwc6a",
renderMode: "CANVAS",
isLoading: false,
maxZoomLevel: 1,
enableDownload: false,
enableRotation: false,
borderRadius: "0px",
boxShadow: "none",
dynamicHeight: "FIXED",
},
{
widgetName: "Text1",
displayName: "Text",
iconSVG: "/static/media/icon.97c59b52.svg",
topRow: 0,
bottomRow: 4,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
animateLoading: true,
dynamicTriggerPathList: [],
dynamicBindingPathList: [
{
key: "text",
},
],
dynamicHeight: "FIXED",
maxDynamicHeight: 9000,
minDynamicHeight: 4,
leftColumn: 16,
truncateButtonColor: "#FFC13D",
text: "{{currentItem.name}}",
key: "yd217bk315",
labelTextSize: "0.875rem",
rightColumn: 28,
textAlign: "LEFT",
widgetId: "zeqf6yfm3s",
logBlackList: {
isVisible: true,
text: true,
fontSize: true,
fontStyle: true,
textAlign: true,
textColor: true,
truncateButtonColor: true,
widgetName: true,
shouldScroll: true,
shouldTruncate: true,
version: true,
animateLoading: true,
type: true,
hideCard: true,
displayName: true,
key: true,
iconSVG: true,
isCanvas: true,
textStyle: true,
dynamicBindingPathList: true,
dynamicTriggerPathList: true,
minHeight: true,
widgetId: true,
renderMode: true,
isLoading: true,
parentColumnSpace: true,
parentRowSpace: true,
leftColumn: true,
rightColumn: true,
topRow: true,
bottomRow: true,
parentId: true,
},
isVisible: true,
fontStyle: "BOLD",
textColor: "#231F20",
version: 1,
parentId: "vqn2okwc6a",
overflow: "NONE",
renderMode: "CANVAS",
isLoading: false,
fontSize: "0.875rem",
textStyle: "HEADING",
borderRadius: "0px",
boxShadow: "none",
},
{
widgetName: "Text2",
displayName: "Text",
iconSVG: "/static/media/icon.97c59b52.svg",
topRow: 4,
bottomRow: 8,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
animateLoading: true,
dynamicTriggerPathList: [],
dynamicBindingPathList: [
{
key: "text",
},
],
dynamicHeight: "FIXED",
maxDynamicHeight: 9000,
minDynamicHeight: 4,
leftColumn: 16,
truncateButtonColor: "#FFC13D",
text: "{{currentItem.id}}",
key: "yd217bk315",
labelTextSize: "0.875rem",
rightColumn: 24,
textAlign: "LEFT",
widgetId: "8wyekp2o6e",
logBlackList: {
isVisible: true,
text: true,
fontSize: true,
fontStyle: true,
textAlign: true,
textColor: true,
truncateButtonColor: true,
widgetName: true,
shouldScroll: true,
shouldTruncate: true,
version: true,
animateLoading: true,
type: true,
hideCard: true,
displayName: true,
key: true,
iconSVG: true,
isCanvas: true,
textStyle: true,
dynamicBindingPathList: true,
dynamicTriggerPathList: true,
minHeight: true,
widgetId: true,
renderMode: true,
isLoading: true,
parentColumnSpace: true,
parentRowSpace: true,
leftColumn: true,
rightColumn: true,
topRow: true,
bottomRow: true,
parentId: true,
},
isVisible: true,
fontStyle: "BOLD",
textColor: "#231F20",
version: 1,
parentId: "vqn2okwc6a",
overflow: "NONE",
renderMode: "CANVAS",
isLoading: false,
fontSize: "0.875rem",
textStyle: "BODY",
borderRadius: "0px",
boxShadow: "none",
},
],
key: "omhgz5cakp",
labelTextSize: "0.875rem",
borderRadius: "0px",
boxShadow: "none",
},
],
borderWidth: "0",
key: "ca3a42k2a4",
labelTextSize: "0.875rem",
disablePropertyPane: true,
backgroundColor: "white",
rightColumn: 64,
widgetId: "9e77epyavg",
containerStyle: "card",
isVisible: true,
version: 1,
parentId: "q3ype57cdo",
renderMode: "CANVAS",
isLoading: false,
borderRadius: "0px",
},
],
key: "omhgz5cakp",
labelTextSize: "0.875rem",
rightColumn: 337.5,
detachFromLayout: true,
widgetId: "q3ype57cdo",
containerStyle: "none",
isVisible: true,
version: 1,
parentId: "iupz1d99ka",
renderMode: "CANVAS",
isLoading: false,
borderRadius: "0px",
boxShadow: "none",
},
],
key: "axex98spx3",
backgroundColor: "transparent",
labelTextSize: "0.875rem",
rightColumn: 63,
itemBackgroundColor: "#FFFFFF",
widgetId: "iupz1d99ka",
isVisible: true,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
version: 1,
borderRadius: "0px",
boxShadow: "none",
accentColor: "{{appsmith.theme.colors.primaryColor}}",
},
],
containerStyle: "none",
detachFromLayout: true,
dynamicBindingPathList: [],
dynamicTriggerPathList: [],
leftColumn: 0,
minHeight: 640,
parentColumnSpace: 1,
parentRowSpace: 1,
rightColumn: 912,
snapColumns: 64,
snapRows: 125,
topRow: 0,
type: "CANVAS_WIDGET",
widgetId: "0",
widgetName: "MainContainer",
renderMode: RenderModes.CANVAS,
isLoading: false,
};
const actualNextDsl = transformDSL(currentDSL);
expect(actualNextDsl).toEqual(expectedNextDSL);
});
it("RadioGroupWidget: Add alignment property, set to LEFT", () => {
const currentVersion = 51;
const currentDSL: ContainerWidgetProps<WidgetProps> = {
widgetName: "MainContainer",
renderMode: RenderModes.CANVAS,
isLoading: false,
backgroundColor: "none",
rightColumn: 909,
snapColumns: 64,
detachFromLayout: true,
widgetId: "0",
topRow: 0,
bottomRow: 710,
containerStyle: "none",
snapRows: 125,
parentRowSpace: 1,
type: "CANVAS_WIDGET",
canExtend: true,
version: currentVersion,
minHeight: 690,
parentColumnSpace: 1,
dynamicBindingPathList: [],
leftColumn: 0,
children: [
{
widgetName: "RadioGroup1",
displayName: "Radio Group",
iconSVG: "/static/media/icon.ba2b2ee0.svg",
topRow: 6,
bottomRow: 14,
parentRowSpace: 10,
type: "RADIO_GROUP_WIDGET",
hideCard: false,
defaultOptionValue: "Y",
animateLoading: true,
parentColumnSpace: 14.015625,
leftColumn: 3,
options: [
{
label: "Yes",
value: "Y",
},
{
label: "No",
value: "N",
},
],
isDisabled: false,
key: "pfm838nmst",
isRequired: false,
rightColumn: 27,
widgetId: "zo3fvq3exo",
isVisible: true,
label: "",
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
},
{
boxShadow: "NONE",
widgetName: "Container1",
borderColor: "transparent",
isCanvas: true,
displayName: "Container",
iconSVG: "/static/media/icon.1977dca3.svg",
topRow: 17,
bottomRow: 35,
parentRowSpace: 10,
type: "CONTAINER_WIDGET",
hideCard: false,
animateLoading: true,
parentColumnSpace: 14.015625,
leftColumn: 3,
children: [
{
widgetName: "Canvas1",
rightColumn: 336.375,
detachFromLayout: true,
displayName: "Canvas",
widgetId: "07bpn6tbfi",
containerStyle: "none",
topRow: 0,
bottomRow: 390,
parentRowSpace: 1,
isVisible: true,
type: "CANVAS_WIDGET",
canExtend: false,
version: 1,
hideCard: true,
parentId: "tt24x0w1w8",
minHeight: 400,
renderMode: "CANVAS",
isLoading: false,
parentColumnSpace: 1,
leftColumn: 0,
children: [
{
widgetName: "RadioGroup2",
displayName: "Radio Group",
iconSVG: "/static/media/icon.ba2b2ee0.svg",
topRow: 2,
bottomRow: 10,
parentRowSpace: 10,
type: "RADIO_GROUP_WIDGET",
hideCard: false,
defaultOptionValue: "Y",
animateLoading: true,
parentColumnSpace: 4.943359375,
leftColumn: 2,
options: [
{
label: "Yes",
value: "Y",
},
{
label: "No",
value: "N",
},
],
isDisabled: false,
key: "pfm838nmst",
isRequired: false,
rightColumn: 64,
widgetId: "cu4xgfuj9c",
isVisible: true,
label: "",
version: 1,
parentId: "07bpn6tbfi",
renderMode: "CANVAS",
isLoading: false,
},
],
key: "xtt3p4czog",
},
],
borderWidth: "0",
key: "0s5opm25jx",
backgroundColor: "#FFFFFF",
rightColumn: 27,
widgetId: "tt24x0w1w8",
containerStyle: "card",
isVisible: true,
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
borderRadius: "0",
},
{
widgetName: "Form1",
version: 1,
backgroundColor: "white",
rightColumn: 54,
isCanvas: true,
displayName: "Form",
iconSVG: "/static/media/icon.ea3e08d1.svg",
widgetId: "ybeukm257w",
topRow: 6,
bottomRow: 46,
parentRowSpace: 10,
isVisible: true,
type: "FORM_WIDGET",
hideCard: false,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
animateLoading: true,
parentColumnSpace: 14.015625,
leftColumn: 30,
children: [
{
widgetName: "Canvas2",
rightColumn: 336.375,
detachFromLayout: true,
displayName: "Canvas",
widgetId: "ilkump68xe",
containerStyle: "none",
topRow: 0,
bottomRow: 390,
parentRowSpace: 1,
isVisible: true,
type: "CANVAS_WIDGET",
canExtend: false,
version: 1,
hideCard: true,
parentId: "ybeukm257w",
minHeight: 400,
renderMode: "CANVAS",
isLoading: false,
parentColumnSpace: 1,
leftColumn: 0,
children: [
{
widgetName: "Text1",
displayName: "Text",
iconSVG: "/static/media/icon.97c59b52.svg",
topRow: 1,
bottomRow: 5,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
animateLoading: true,
leftColumn: 1.5,
shouldTruncate: false,
truncateButtonColor: "#FFC13D",
text: "Form",
key: "jh3gip369p",
rightColumn: 25.5,
textAlign: "LEFT",
widgetId: "yp585y41d6",
isVisible: true,
fontStyle: "BOLD",
textColor: "#231F20",
shouldScroll: false,
version: 1,
parentId: "ilkump68xe",
renderMode: "CANVAS",
isLoading: false,
fontSize: "HEADING1",
},
{
resetFormOnClick: true,
widgetName: "FormButton1",
buttonColor: "#03B365",
displayName: "FormButton",
iconSVG: "/static/media/icon.c8f649ed.svg",
topRow: 33,
bottomRow: 37,
type: "FORM_BUTTON_WIDGET",
hideCard: true,
animateLoading: true,
leftColumn: 46,
text: "Submit",
key: "ahb522obua",
rightColumn: 62,
isDefaultClickDisabled: true,
widgetId: "jrpy8ke6tw",
isVisible: true,
recaptchaType: "V3",
version: 1,
parentId: "ilkump68xe",
renderMode: "CANVAS",
isLoading: false,
disabledWhenInvalid: true,
buttonVariant: "PRIMARY",
},
{
resetFormOnClick: true,
widgetName: "FormButton2",
buttonColor: "#03B365",
displayName: "FormButton",
iconSVG: "/static/media/icon.c8f649ed.svg",
topRow: 33,
bottomRow: 37,
type: "FORM_BUTTON_WIDGET",
hideCard: true,
animateLoading: true,
leftColumn: 30,
text: "Reset",
key: "ahb522obua",
rightColumn: 46,
isDefaultClickDisabled: true,
widgetId: "j1uwneh0zn",
isVisible: true,
recaptchaType: "V3",
version: 1,
parentId: "ilkump68xe",
renderMode: "CANVAS",
isLoading: false,
disabledWhenInvalid: false,
buttonVariant: "SECONDARY",
},
{
widgetName: "RadioGroup3",
displayName: "Radio Group",
iconSVG: "/static/media/icon.ba2b2ee0.svg",
topRow: 7,
bottomRow: 15,
parentRowSpace: 10,
type: "RADIO_GROUP_WIDGET",
hideCard: false,
defaultOptionValue: "Y",
animateLoading: true,
parentColumnSpace: 4.943359375,
leftColumn: 1,
options: [
{
label: "Yes",
value: "Y",
},
{
label: "No",
value: "N",
},
],
isDisabled: false,
key: "pfm838nmst",
isRequired: false,
rightColumn: 64,
widgetId: "d3orpb3ele",
isVisible: true,
label: "",
version: 1,
parentId: "ilkump68xe",
renderMode: "CANVAS",
isLoading: false,
},
],
key: "xtt3p4czog",
},
],
key: "04103tgkwj",
},
],
};
const expectedNextDSL: ContainerWidgetProps<WidgetProps> = {
widgetName: "MainContainer",
renderMode: RenderModes.CANVAS,
isLoading: false,
backgroundColor: "none",
rightColumn: 909,
snapColumns: 64,
detachFromLayout: true,
widgetId: "0",
topRow: 0,
bottomRow: 710,
containerStyle: "none",
snapRows: 125,
parentRowSpace: 1,
type: "CANVAS_WIDGET",
canExtend: true,
version: currentVersion,
minHeight: 690,
parentColumnSpace: 1,
dynamicBindingPathList: [],
leftColumn: 0,
children: [
{
widgetName: "RadioGroup1",
displayName: "Radio Group",
iconSVG: "/static/media/icon.ba2b2ee0.svg",
topRow: 6,
bottomRow: 14,
parentRowSpace: 10,
type: "RADIO_GROUP_WIDGET",
hideCard: false,
defaultOptionValue: "Y",
animateLoading: true,
parentColumnSpace: 14.015625,
leftColumn: 3,
options: [
{
label: "Yes",
value: "Y",
},
{
label: "No",
value: "N",
},
],
isDisabled: false,
key: "pfm838nmst",
isRequired: false,
rightColumn: 27,
widgetId: "zo3fvq3exo",
isVisible: true,
label: "",
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
alignment: "left",
},
{
boxShadow: "NONE",
widgetName: "Container1",
borderColor: "transparent",
isCanvas: true,
displayName: "Container",
iconSVG: "/static/media/icon.1977dca3.svg",
topRow: 17,
bottomRow: 35,
parentRowSpace: 10,
type: "CONTAINER_WIDGET",
hideCard: false,
animateLoading: true,
parentColumnSpace: 14.015625,
leftColumn: 3,
children: [
{
widgetName: "Canvas1",
rightColumn: 336.375,
detachFromLayout: true,
displayName: "Canvas",
widgetId: "07bpn6tbfi",
containerStyle: "none",
topRow: 0,
bottomRow: 390,
parentRowSpace: 1,
isVisible: true,
type: "CANVAS_WIDGET",
canExtend: false,
version: 1,
hideCard: true,
parentId: "tt24x0w1w8",
minHeight: 400,
renderMode: "CANVAS",
isLoading: false,
parentColumnSpace: 1,
leftColumn: 0,
children: [
{
widgetName: "RadioGroup2",
displayName: "Radio Group",
iconSVG: "/static/media/icon.ba2b2ee0.svg",
topRow: 2,
bottomRow: 10,
parentRowSpace: 10,
type: "RADIO_GROUP_WIDGET",
hideCard: false,
defaultOptionValue: "Y",
animateLoading: true,
parentColumnSpace: 4.943359375,
leftColumn: 2,
options: [
{
label: "Yes",
value: "Y",
},
{
label: "No",
value: "N",
},
],
isDisabled: false,
key: "pfm838nmst",
isRequired: false,
rightColumn: 64,
widgetId: "cu4xgfuj9c",
isVisible: true,
label: "",
version: 1,
parentId: "07bpn6tbfi",
renderMode: "CANVAS",
isLoading: false,
alignment: "left",
},
],
key: "xtt3p4czog",
},
],
borderWidth: "0",
key: "0s5opm25jx",
backgroundColor: "#FFFFFF",
rightColumn: 27,
widgetId: "tt24x0w1w8",
containerStyle: "card",
isVisible: true,
version: 1,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
borderRadius: "0",
},
{
widgetName: "Form1",
version: 1,
backgroundColor: "white",
rightColumn: 54,
isCanvas: true,
displayName: "Form",
iconSVG: "/static/media/icon.ea3e08d1.svg",
widgetId: "ybeukm257w",
topRow: 6,
bottomRow: 46,
parentRowSpace: 10,
isVisible: true,
type: "FORM_WIDGET",
hideCard: false,
parentId: "0",
renderMode: "CANVAS",
isLoading: false,
animateLoading: true,
parentColumnSpace: 14.015625,
leftColumn: 30,
children: [
{
widgetName: "Canvas2",
rightColumn: 336.375,
detachFromLayout: true,
displayName: "Canvas",
widgetId: "ilkump68xe",
containerStyle: "none",
topRow: 0,
bottomRow: 390,
parentRowSpace: 1,
isVisible: true,
type: "CANVAS_WIDGET",
canExtend: false,
version: 1,
hideCard: true,
parentId: "ybeukm257w",
minHeight: 400,
renderMode: "CANVAS",
isLoading: false,
parentColumnSpace: 1,
leftColumn: 0,
children: [
{
widgetName: "Text1",
displayName: "Text",
iconSVG: "/static/media/icon.97c59b52.svg",
topRow: 1,
bottomRow: 5,
type: "TEXT_WIDGET",
fontFamily: "System Default",
hideCard: false,
animateLoading: true,
leftColumn: 1.5,
shouldTruncate: false,
truncateButtonColor: "#FFC13D",
text: "Form",
key: "jh3gip369p",
rightColumn: 25.5,
textAlign: "LEFT",
widgetId: "yp585y41d6",
isVisible: true,
fontStyle: "BOLD",
textColor: "#231F20",
shouldScroll: false,
version: 1,
parentId: "ilkump68xe",
renderMode: "CANVAS",
isLoading: false,
fontSize: "HEADING1",
},
{
resetFormOnClick: true,
widgetName: "FormButton1",
buttonColor: "#03B365",
displayName: "FormButton",
iconSVG: "/static/media/icon.c8f649ed.svg",
topRow: 33,
bottomRow: 37,
type: "FORM_BUTTON_WIDGET",
hideCard: true,
animateLoading: true,
leftColumn: 46,
text: "Submit",
key: "ahb522obua",
rightColumn: 62,
isDefaultClickDisabled: true,
widgetId: "jrpy8ke6tw",
isVisible: true,
recaptchaType: "V3",
version: 1,
parentId: "ilkump68xe",
renderMode: "CANVAS",
isLoading: false,
disabledWhenInvalid: true,
buttonVariant: "PRIMARY",
},
{
resetFormOnClick: true,
widgetName: "FormButton2",
buttonColor: "#03B365",
displayName: "FormButton",
iconSVG: "/static/media/icon.c8f649ed.svg",
topRow: 33,
bottomRow: 37,
type: "FORM_BUTTON_WIDGET",
hideCard: true,
animateLoading: true,
leftColumn: 30,
text: "Reset",
key: "ahb522obua",
rightColumn: 46,
isDefaultClickDisabled: true,
widgetId: "j1uwneh0zn",
isVisible: true,
recaptchaType: "V3",
version: 1,
parentId: "ilkump68xe",
renderMode: "CANVAS",
isLoading: false,
disabledWhenInvalid: false,
buttonVariant: "SECONDARY",
},
{
widgetName: "RadioGroup3",
displayName: "Radio Group",
iconSVG: "/static/media/icon.ba2b2ee0.svg",
topRow: 7,
bottomRow: 15,
parentRowSpace: 10,
type: "RADIO_GROUP_WIDGET",
hideCard: false,
defaultOptionValue: "Y",
animateLoading: true,
parentColumnSpace: 4.943359375,
leftColumn: 1,
options: [
{
label: "Yes",
value: "Y",
},
{
label: "No",
value: "N",
},
],
isDisabled: false,
key: "pfm838nmst",
isRequired: false,
rightColumn: 64,
widgetId: "d3orpb3ele",
isVisible: true,
label: "",
version: 1,
parentId: "ilkump68xe",
renderMode: "CANVAS",
isLoading: false,
alignment: "left",
},
],
key: "xtt3p4czog",
},
],
key: "04103tgkwj",
},
],
};
const actualNextDSL = migrateRadioGroupAlignmentProperty(currentDSL);
expect(actualNextDSL).toEqual(expectedNextDSL);
});
it("correctly migrates currentIndex/currentRow properties for validations in table view", () => {
const currentVersion = 78;
const currentDSL: ContainerWidgetProps<WidgetProps> = {
bottomRow: 740,
containerStyle: "none",
detachFromLayout: true,
dynamicBindingPathList: [],
dynamicTriggerPathList: [],
leftColumn: 0,
minHeight: 640,
parentColumnSpace: 1,
parentRowSpace: 1,
rightColumn: 912,
snapColumns: 64,
snapRows: 125,
topRow: 0,
type: "CANVAS_WIDGET",
version: currentVersion,
widgetId: "0",
widgetName: "MainContainer",
renderMode: "CANVAS",
isLoading: false,
children: [
{
widgetName: "Table1",
type: "TABLE_WIDGET_V2",
widgetId: "123",
renderMode: "CANVAS",
version: 1,
parentColumnSpace: 15.0623,
leftColumn: 1,
rightColumn: 1,
topRow: 1,
bottomRow: 1,
parentRowSpace: 10,
isLoading: false,
primaryColumns: {
column1: {
validation: {
min: "{{\n (\n (isNewRow) => (\nisNewRow ? 1 : 0\n ))\n (\n Table1.isAddRowInProgress\n )\n }}\n ",
max: 1,
regex:
"{{\n (\n (isNewRow) => (\nisNewRow ? 1 : 0\n ))\n (\n Table1.isAddRowInProgress\n )\n }}\n ",
errorMessage: true,
isColumnEditableCellRequired:
"{{\n (\n (isNewRow) => (\nisNewRow ? true : false\n ))\n (\n Table1.isAddRowInProgress\n )\n }}\n ",
randomValidation: "hello",
isColumnEditableCellValid: `
{{
(
(editedValue, currentRow, currentIndex, isNewRow) => (
isNewRow ? true : false
))
(
(Table1.isAddRowInProgress ? Table1.newRow.orderAmount : Table1.columnEditableCellValue.orderAmount) || "",
Table1.isAddRowInProgress ? Table1.newRow : (Table1.processedTableData[Table1.editableCell.index] ||
Object.keys(Table1.processedTableData[0])
.filter(key => ["__originalIndex__", "__primaryKey__"].indexOf(key) === -1)
.reduce((prev, curr) => {
prev[curr] = "";
return prev;
}, {})),
Table1.isAddRowInProgress ? -1 : Table1.editableCell.index,
Table1.isAddRowInProgress
)
}}
`,
},
},
},
},
],
};
const nextDSL = transformDSL(currentDSL);
const validations = (nextDSL.children || [])[0].primaryColumns.column1
.validation;
for (const validationName in validations) {
const validation = validations[validationName];
if (
validationName == "min" ||
validationName == "regex" ||
validationName == "isColumnEditableCellRequired"
) {
expect(
validation.indexOf("(isNewRow, currentIndex, currentRow)"),
).toBeGreaterThan(-1);
expect(
validation.indexOf(
`.filter(key => ["__originalIndex__", "__primaryKey__"].indexOf(key) === -1)`,
),
).toBeGreaterThan(-1);
}
if (validationName == "errorMessage") {
expect(validation).toEqual(true);
}
if (validationName == "max") {
expect(validation).toEqual(1);
}
if (validationName == "isColumnEditableCellValid") {
expect(
validation.indexOf(
"(editedValue, currentRow, currentIndex, isNewRow)",
),
).toBeGreaterThan(-1);
expect(
validation.indexOf(
`.filter(key => ["__originalIndex__", "__primaryKey__"].indexOf(key) === -1)`,
),
).toBeGreaterThan(-1);
}
}
});
});
|
1,326 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/DynamicBindingUtils.test.ts | import type { Action } from "entities/Action";
import { PluginType } from "entities/Action";
import equal from "fast-deep-equal/es6";
import {
combineDynamicBindings,
getDynamicBindings,
getPropertyPath,
} from "./DynamicBindingUtils";
import {
EVAL_VALUE_PATH,
getDynamicBindingsChangesSaga,
getDynamicStringSegments,
getEvalValuePath,
isChildPropertyPath,
} from "./DynamicBindingUtils";
describe.each([
["{{A}}", ["{{A}}"]],
["A {{B}}", ["A ", "{{B}}"]],
[
"Hello {{Customer.Name}}, the status for your order id {{orderId}} is {{status}}",
[
"Hello ",
"{{Customer.Name}}",
", the status for your order id ",
"{{orderId}}",
" is ",
"{{status}}",
],
],
[
"{{data.map(datum => {return {id: datum}})}}",
["{{data.map(datum => {return {id: datum}})}}"],
],
["{{}}{{}}}", ["{{}}", "{{}}", "}"]],
["{{{}}", ["{{{}}"]],
["{{ {{", ["{{ {{"]],
["}} }}", ["}} }}"]],
["}} {{", ["}} {{"]],
])("Parse the dynamic string(%s, %j)", (dynamicString, expected) => {
test(`returns ${expected}`, () => {
expect(getDynamicStringSegments(dynamicString as string)).toStrictEqual(
expected,
);
});
});
describe("isChildPropertyPath function", () => {
it("works", () => {
const cases: Array<[string, string, boolean]> = [
["Table1.selectedRow", "Table1.selectedRow", true],
["Table1.selectedRow", "Table1.selectedRows", false],
["Table1.selectedRow", "Table1.selectedRow.email", true],
["Table1.selectedRow", "1Table1.selectedRow", false],
["Table1.selectedRow", "Table11selectedRow", false],
["Table1.selectedRow", "Table1.selectedRow", true],
["Dropdown1.options", "Dropdown1.options[1]", true],
["Dropdown1.options[1]", "Dropdown1.options[1].value", true],
["Dropdown1", "Dropdown1.options[1].value", true],
];
cases.forEach((testCase) => {
const result = isChildPropertyPath(testCase[0], testCase[1]);
expect(result).toBe(testCase[2]);
});
});
});
describe("DynamicBindingPathlist", () => {
it("Properly updates the dynamicBindingPathlist", () => {
// @ts-expect-error: Action type mismatch
const action: Action = {
cacheResponse: "",
id: "61810f59a0f5113e30ba72ac",
workspaceId: "61800c6bd504bf710747bf9a",
pluginType: PluginType.API,
pluginId: "5ca385dc81b37f0004b4db85",
name: "Api1",
datasource: {
// userPermissions: [],
name: "DEFAULT_REST_DATASOURCE",
pluginId: "5ca385dc81b37f0004b4db85",
workspaceId: "61800c6bd504bf710747bf9a",
datasourceConfiguration: {
url: "https://thatcopy.pw",
},
invalids: [],
messages: [],
isValid: true,
// new: true,
},
pageId: "61800cecd504bf710747bf9d",
actionConfiguration: {
// timeoutInMillisecond: 10000,
// paginationType: "NONE",
path: "/catapi/rest/",
headers: [
{
key: "content-type",
value: "application/json",
},
],
encodeParamsToggle: true,
queryParameters: [
{
key: "{{Button1.text}}",
value: "",
},
{
key: "",
value: "",
},
],
body: "{{Create_users.data}}",
httpMethod: "POST",
pluginSpecifiedTemplates: [
{
value: true,
},
],
},
executeOnLoad: false,
dynamicBindingPathList: [
{
key: "body",
},
{
key: "queryParameters[0].key",
},
],
isValid: true,
invalids: [],
messages: [],
jsonPathKeys: ["Create_users.data", "Button1.text"],
confirmBeforeExecute: false,
// userPermissions: ["read:actions", "execute:actions", "manage:actions"],
// validName: "Api1",
};
const value = [
{
key: "{{Button1.text}}",
value: "",
},
{
key: "",
value: "",
},
];
const field = "actionConfiguration.queryParameters";
const expectedResult = [
{
key: "body",
},
{
key: "queryParameters[0].key",
},
];
const actualResult = getDynamicBindingsChangesSaga(action, value, field);
expect(equal(expectedResult, actualResult)).toBeTruthy();
});
});
describe("getPropertyPath function", () => {
it("test getPropertyPath", () => {
const testCases = [
["Table1.searchText", "searchText"],
["Table1.selectedRow", "selectedRow"],
["Table1.meta.searchText", "meta.searchText"],
["Table1", "Table1"],
["Table1.", ""],
];
testCases.forEach(([input, expectedResult]) => {
const actualResult = getPropertyPath(input);
expect(actualResult).toStrictEqual(expectedResult);
});
});
});
describe("getNestedEvalPath", () => {
it("returns valid nested path", () => {
const actualUnpopulatedNestedPath = getEvalValuePath(
"Table1.primaryColumns.state",
{
isPopulated: false,
fullPath: true,
},
);
const actualPopulatedNestedPath = getEvalValuePath(
"Table1.primaryColumns.state",
{
isPopulated: true,
fullPath: true,
},
);
const expectedUnpopulatedNestedPath = `Table1.${EVAL_VALUE_PATH}.['primaryColumns.state']`;
const expectedPopulatedNestedPath = `Table1.${EVAL_VALUE_PATH}.primaryColumns.state`;
expect(actualPopulatedNestedPath).toEqual(expectedPopulatedNestedPath);
expect(actualUnpopulatedNestedPath).toEqual(expectedUnpopulatedNestedPath);
});
});
describe("getDynamicBindings and combineDynamicBindings function", () => {
const testCases = [
{
js: "(function(){return true;})()",
jsSnippets: ["(function(){return true;})()"],
propertyValue: "{{(function(){return true;})()}}",
stringSegments: ["{{(function(){return true;})()}}"],
},
{
js: '"Hello " + (Customer.Name) + ", the status for your order id " + (orderId) + " is " + (status)',
jsSnippets: ["", "Customer.Name", "", "orderId", "", "status"],
propertyValue:
"Hello {{Customer.Name}}, the status for your order id {{orderId}} is {{status}}",
stringSegments: [
"Hello ",
"{{Customer.Name}}",
", the status for your order id ",
"{{orderId}}",
" is ",
"{{status}}",
],
},
{
js: "(data.map(datum => {return {id: datum}}))",
jsSnippets: ["data.map(datum => {return {id: datum}})"],
propertyValue: "{{data.map(datum => {return {id: datum}})}}",
stringSegments: ["{{data.map(datum => {return {id: datum}})}}"],
},
{
js: '"{{}}"',
jsSnippets: [""],
propertyValue: "{{}}",
stringSegments: ["{{}}"],
},
{
js: "(Query1.data.splice(1).map((data, ind) => ({...data, ind })))",
jsSnippets: [
"Query1.data.splice(1).map((data, ind) => ({...data, ind }))",
],
propertyValue:
"{{Query1.data.splice(1).map((data, ind) => ({...data, ind }))}}",
stringSegments: [
"{{Query1.data.splice(1).map((data, ind) => ({...data, ind }))}}",
],
},
{
js: "(JSObject1.myFun1())",
jsSnippets: ["JSObject1.myFun1()"],
propertyValue: "{{JSObject1.myFun1()}}",
stringSegments: ["{{JSObject1.myFun1()}}"],
},
{
js: "showAlert(currentItem.name + 'Name', '');\nshowAlert(Button1.text, '');",
jsSnippets: [
"showAlert(currentItem.name + 'Name', '');\nshowAlert(Button1.text, '');",
],
propertyValue:
"{{showAlert(currentItem.name + 'Name', '');\nshowAlert(Button1.text, '');}}",
stringSegments: [
"{{showAlert(currentItem.name + 'Name', '');\nshowAlert(Button1.text, '');}}",
],
},
{
js: '"code " + ( currentItem.nol || "Blue;")',
jsSnippets: ["", ' currentItem.nol || "Blue;"'],
propertyValue: 'code {{ currentItem.nol || "Blue;"}}',
stringSegments: ["code ", '{{ currentItem.nol || "Blue;"}}'],
},
];
it("Returns expected js string", () => {
testCases.forEach(({ js, jsSnippets, propertyValue, stringSegments }) => {
expect(getDynamicBindings(propertyValue)).toStrictEqual({
jsSnippets,
stringSegments,
});
expect(combineDynamicBindings(jsSnippets, stringSegments)).toEqual(js);
});
});
});
|
1,329 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/JSPaneUtils.test.ts | import { PluginType } from "entities/Action";
import type { JSCollection } from "entities/JSCollection";
import type { ParsedBody } from "./JSPaneUtils";
import { getDifferenceInJSCollection } from "./JSPaneUtils";
const JSObject1: JSCollection = {
id: "1234",
applicationId: "app123",
workspaceId: "workspace123",
name: "JSObject2",
pageId: "page123",
pluginId: "plugin123",
pluginType: PluginType.JS,
actionIds: [],
archivedActionIds: [],
actions: [
{
id: "fun2",
applicationId: "app123",
workspaceId: "workspace123",
pluginType: "JS",
pluginId: "plugin123",
name: "myFun2",
fullyQualifiedName: "JSObject2.myFun2",
datasource: {
userPermissions: [],
name: "UNUSED_DATASOURCE",
pluginId: "plugin123",
workspaceId: "workspace123",
messages: [],
isValid: true,
new: true,
},
pageId: "page123",
collectionId: "1234",
actionConfiguration: {
timeoutInMillisecond: 10000,
// @ts-expect-error: paginationType does not exists on JSAction
paginationType: "NONE",
encodeParamsToggle: true,
body: "async () => {\n\t\t//use async-await or promises\n\t}",
jsArguments: [],
},
executeOnLoad: false,
clientSideExecution: true,
dynamicBindingPathList: [
{
key: "body",
},
],
isValid: true,
invalids: [],
messages: [],
jsonPathKeys: ["async () => {\n\t\t//use async-await or promises\n\t}"],
confirmBeforeExecute: false,
userPermissions: ["read:actions", "execute:actions", "manage:actions"],
validName: "JSObject2.myFun2",
},
{
id: "fun1",
applicationId: "app123",
workspaceId: "workspace123",
pluginType: "JS",
pluginId: "plugin123",
name: "myFun1",
fullyQualifiedName: "JSObject2.myFun1",
datasource: {
userPermissions: [],
name: "UNUSED_DATASOURCE",
pluginId: "plugin123",
workspaceId: "workspace123",
messages: [],
isValid: true,
new: true,
},
pageId: "page123",
collectionId: "1234",
actionConfiguration: {
timeoutInMillisecond: 10000,
// @ts-expect-error: paginationType does not exists on JSAction
paginationType: "NONE",
encodeParamsToggle: true,
body: "() => {\n\t\t//write code here\n\t}",
jsArguments: [],
},
executeOnLoad: false,
clientSideExecution: true,
dynamicBindingPathList: [
{
key: "body",
},
],
isValid: true,
invalids: [],
messages: [],
jsonPathKeys: ["() => {\n\t\t//write code here\n\t}"],
confirmBeforeExecute: false,
userPermissions: ["read:actions", "execute:actions", "manage:actions"],
validName: "JSObject2.myFun1",
},
],
archivedActions: [],
body: "export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\tmyFun1: () => {\n\t\t//write code here\n\t},\n\tmyFun2: async () => {\n\t\t//use async-await or promises\n\t}\n}",
variables: [
{
name: "myVar1",
value: [],
},
{
name: "myVar2",
value: {},
},
],
};
const JSObject2: JSCollection = {
id: "1234",
applicationId: "app123",
workspaceId: "workspace123",
name: "JSObject2",
pageId: "page123",
pluginId: "plugin123",
pluginType: PluginType.JS,
actionIds: [],
archivedActionIds: [],
actions: [
{
id: "fun1",
applicationId: "app123",
workspaceId: "workspace123",
pluginType: "JS",
pluginId: "plugin123",
name: "myFun1",
fullyQualifiedName: "JSObject2.myFun1",
datasource: {
userPermissions: [],
name: "UNUSED_DATASOURCE",
pluginId: "plugin123",
workspaceId: "workspace123",
messages: [],
isValid: true,
new: true,
},
pageId: "page123",
collectionId: "1234",
actionConfiguration: {
timeoutInMillisecond: 10000,
// @ts-expect-error: paginationType does not exists on JSAction
paginationType: "NONE",
encodeParamsToggle: true,
body: "() => {\n\t\t//write code here\n\t}",
jsArguments: [],
},
executeOnLoad: false,
clientSideExecution: true,
dynamicBindingPathList: [
{
key: "body",
},
],
isValid: true,
invalids: [],
messages: [],
jsonPathKeys: ["() => {\n\t\t//write code here\n\t}"],
confirmBeforeExecute: false,
userPermissions: ["read:actions", "execute:actions", "manage:actions"],
validName: "JSObject2.myFun1",
},
{
id: "fun2",
applicationId: "app123",
workspaceId: "workspace123",
pluginType: "JS",
pluginId: "plugin123",
name: "myFun2",
fullyQualifiedName: "JSObject2.myFun2",
datasource: {
userPermissions: [],
name: "UNUSED_DATASOURCE",
pluginId: "plugin123",
workspaceId: "workspace123",
messages: [],
isValid: true,
new: true,
},
pageId: "page123",
collectionId: "1234",
actionConfiguration: {
timeoutInMillisecond: 10000,
// @ts-expect-error: paginationType does not exists on JSAction
paginationType: "NONE",
encodeParamsToggle: true,
body: "async () => {\n\t\t//use async-await or promises\n\t}",
jsArguments: [],
},
executeOnLoad: false,
clientSideExecution: true,
dynamicBindingPathList: [
{
key: "body",
},
],
isValid: true,
invalids: [],
messages: [],
jsonPathKeys: ["async () => {\n\t\t//use async-await or promises\n\t}"],
confirmBeforeExecute: false,
userPermissions: ["read:actions", "execute:actions", "manage:actions"],
validName: "JSObject2.myFun2",
},
],
archivedActions: [],
body: "export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\tmyFun1: () => {\n\t\t//write code here\n\t},\n\tmyFun2: async () => {\n\t\t//use async-await or promises\n\t}\n}",
variables: [
{
name: "myVar1",
value: [],
},
{
name: "myVar2",
value: {},
},
],
};
const parsedBodyWithRenamedAction: ParsedBody = {
actions: [
{
name: "myFun11",
body: "() => {\n\t\t//write code here\n\t}",
arguments: [],
},
{
name: "myFun2",
body: "async () => {\n\t\t//use async-await or promises\n\t}",
arguments: [],
},
],
variables: [
{
name: "myVar1",
value: [],
},
{
name: "myVar2",
value: {},
},
],
};
const resultRenamedActions = {
newActions: [],
updateActions: [
{
id: "fun1",
applicationId: "app123",
workspaceId: "workspace123",
pluginType: "JS",
pluginId: "plugin123",
name: "myFun11",
fullyQualifiedName: "JSObject2.myFun1",
datasource: {
userPermissions: [],
name: "UNUSED_DATASOURCE",
pluginId: "plugin123",
workspaceId: "workspace123",
messages: [],
isValid: true,
new: true,
},
pageId: "page123",
collectionId: "1234",
actionConfiguration: {
timeoutInMillisecond: 10000,
paginationType: "NONE",
encodeParamsToggle: true,
body: "() => {\n\t\t//write code here\n\t}",
jsArguments: [],
},
executeOnLoad: false,
clientSideExecution: true,
dynamicBindingPathList: [
{
key: "body",
},
],
isValid: true,
invalids: [],
messages: [],
jsonPathKeys: ["() => {\n\t\t//write code here\n\t}"],
confirmBeforeExecute: false,
userPermissions: ["read:actions", "execute:actions", "manage:actions"],
validName: "JSObject2.myFun1",
},
],
deletedActions: [],
nameChangedActions: [
{
id: "fun1",
collectionId: "1234",
oldName: "myFun1",
newName: "myFun11",
pageId: "page123",
},
],
changedVariables: [],
};
const parsedBodyWithDeletedAction: ParsedBody = {
actions: [
{
name: "myFun1",
body: "() => {\n\t\t//write code here\n\t}",
arguments: [],
},
],
variables: [
{
name: "myVar1",
value: [],
},
{
name: "myVar2",
value: {},
},
],
};
const resultDeletedActions = {
newActions: [],
updateActions: [],
deletedActions: [
{
id: "fun2",
applicationId: "app123",
workspaceId: "workspace123",
pluginType: "JS",
pluginId: "plugin123",
name: "myFun2",
fullyQualifiedName: "JSObject2.myFun2",
datasource: {
userPermissions: [],
name: "UNUSED_DATASOURCE",
pluginId: "plugin123",
workspaceId: "workspace123",
messages: [],
isValid: true,
new: true,
},
pageId: "page123",
collectionId: "1234",
actionConfiguration: {
timeoutInMillisecond: 10000,
paginationType: "NONE",
encodeParamsToggle: true,
body: "async () => {\n\t\t//use async-await or promises\n\t}",
jsArguments: [],
},
executeOnLoad: false,
clientSideExecution: true,
dynamicBindingPathList: [
{
key: "body",
},
],
isValid: true,
invalids: [],
messages: [],
jsonPathKeys: ["async () => {\n\t\t//use async-await or promises\n\t}"],
confirmBeforeExecute: false,
userPermissions: ["read:actions", "execute:actions", "manage:actions"],
validName: "JSObject2.myFun2",
},
],
nameChangedActions: [],
changedVariables: [],
};
const parsedBodyWithChangedVariable: ParsedBody = {
actions: [
{
name: "myFun1",
body: "() => {\n\t\t//write code here\n\t}",
arguments: [],
},
{
name: "myFun2",
body: "async () => {\n\t\t//use async-await or promises\n\t}",
arguments: [],
},
],
variables: [
{
name: "myVar1",
value: "app",
},
{
name: "myVar2",
value: {},
},
],
};
const resultChangedVariable = {
newActions: [],
updateActions: [],
deletedActions: [],
nameChangedActions: [],
changedVariables: [
{
name: "myVar1",
value: "app",
},
],
};
const parsedBodyWithChangeInBody: ParsedBody = {
actions: [
{
name: "myFun1",
body: "() => {\n\t\t//write code here\n\t}",
arguments: [],
},
{
name: "myFun2",
body: "async () => {\n\t\t//use async-await or promises\n\tconsole.log('content changed')}",
arguments: [],
},
],
variables: [
{
name: "myVar1",
value: [],
},
{
name: "myVar2",
value: {},
},
],
};
const resultChangedBody = {
newActions: [],
updateActions: [
{
id: "fun2",
applicationId: "app123",
workspaceId: "workspace123",
pluginType: "JS",
pluginId: "plugin123",
name: "myFun2",
fullyQualifiedName: "JSObject2.myFun2",
datasource: {
userPermissions: [],
name: "UNUSED_DATASOURCE",
pluginId: "plugin123",
workspaceId: "workspace123",
messages: [],
isValid: true,
new: true,
},
pageId: "page123",
collectionId: "1234",
actionConfiguration: {
timeoutInMillisecond: 10000,
paginationType: "NONE",
encodeParamsToggle: true,
body: "async () => {\n\t\t//use async-await or promises\n\tconsole.log('content changed')}",
jsArguments: [],
},
executeOnLoad: false,
clientSideExecution: true,
dynamicBindingPathList: [
{
key: "body",
},
],
isValid: true,
invalids: [],
messages: [],
jsonPathKeys: ["async () => {\n\t\t//use async-await or promises\n\t}"],
confirmBeforeExecute: false,
userPermissions: ["read:actions", "execute:actions", "manage:actions"],
validName: "JSObject2.myFun2",
},
],
deletedActions: [],
nameChangedActions: [],
changedVariables: [],
};
const parsedBodyWithChangedParameters: ParsedBody = {
actions: [
{
name: "myFun1",
body: "() => {\n\t\t//write code here\n\t}",
arguments: [],
},
{
name: "myFun2",
body: "async (a,b) => {\n\t\t//use async-await or promises\n\t}",
arguments: [
{ name: "a", value: undefined },
{ name: "b", value: undefined },
],
},
],
variables: [
{
name: "myVar1",
value: [],
},
{
name: "myVar2",
value: {},
},
],
};
const resultChangedParameters = {
newActions: [],
updateActions: [
{
id: "fun2",
applicationId: "app123",
workspaceId: "workspace123",
pluginType: "JS",
pluginId: "plugin123",
name: "myFun2",
fullyQualifiedName: "JSObject2.myFun2",
datasource: {
userPermissions: [],
name: "UNUSED_DATASOURCE",
pluginId: "plugin123",
workspaceId: "workspace123",
messages: [],
isValid: true,
new: true,
},
pageId: "page123",
collectionId: "1234",
actionConfiguration: {
timeoutInMillisecond: 10000,
paginationType: "NONE",
encodeParamsToggle: true,
body: "async (a,b) => {\n\t\t//use async-await or promises\n\t}",
jsArguments: [
{ name: "a", value: undefined },
{ name: "b", value: undefined },
],
},
executeOnLoad: false,
clientSideExecution: true,
dynamicBindingPathList: [
{
key: "body",
},
],
isValid: true,
invalids: [],
messages: [],
jsonPathKeys: ["async () => {\n\t\t//use async-await or promises\n\t}"],
confirmBeforeExecute: false,
userPermissions: ["read:actions", "execute:actions", "manage:actions"],
validName: "JSObject2.myFun2",
},
],
deletedActions: [],
nameChangedActions: [],
changedVariables: [],
};
const parsedBodyWithRemovedAsync: ParsedBody = {
actions: [
{
name: "myFun1",
body: "() => {\n\t\t//write code here\n\t}",
arguments: [],
},
{
name: "myFun2",
body: "() => {\n\t\t//use async-await or promises\n\t}",
arguments: [],
},
],
variables: [
{
name: "myVar1",
value: [],
},
{
name: "myVar2",
value: {},
},
],
};
const resultRemovedAsync = {
newActions: [],
updateActions: [
{
id: "fun2",
applicationId: "app123",
workspaceId: "workspace123",
pluginType: "JS",
pluginId: "plugin123",
name: "myFun2",
fullyQualifiedName: "JSObject2.myFun2",
datasource: {
userPermissions: [],
name: "UNUSED_DATASOURCE",
pluginId: "plugin123",
workspaceId: "workspace123",
messages: [],
isValid: true,
new: true,
},
pageId: "page123",
collectionId: "1234",
actionConfiguration: {
timeoutInMillisecond: 10000,
paginationType: "NONE",
encodeParamsToggle: true,
body: "() => {\n\t\t//use async-await or promises\n\t}",
jsArguments: [],
},
executeOnLoad: false,
clientSideExecution: true,
dynamicBindingPathList: [
{
key: "body",
},
],
isValid: true,
invalids: [],
messages: [],
jsonPathKeys: ["async () => {\n\t\t//use async-await or promises\n\t}"],
confirmBeforeExecute: false,
userPermissions: ["read:actions", "execute:actions", "manage:actions"],
validName: "JSObject2.myFun2",
},
],
deletedActions: [],
nameChangedActions: [],
changedVariables: [],
};
const parsedBodyWithAddedAsync: ParsedBody = {
actions: [
{
name: "myFun1",
body: "async () => {\n\t\t//write code here\n\t}",
arguments: [],
},
{
name: "myFun2",
body: "async () => {\n\t\t//use async-await or promises\n\t}",
arguments: [],
},
],
variables: [
{
name: "myVar1",
value: [],
},
{
name: "myVar2",
value: {},
},
],
};
const resultAddedAsync = {
newActions: [],
updateActions: [
{
id: "fun1",
applicationId: "app123",
workspaceId: "workspace123",
pluginType: "JS",
pluginId: "plugin123",
name: "myFun1",
fullyQualifiedName: "JSObject2.myFun1",
datasource: {
userPermissions: [],
name: "UNUSED_DATASOURCE",
pluginId: "plugin123",
workspaceId: "workspace123",
messages: [],
isValid: true,
new: true,
},
pageId: "page123",
collectionId: "1234",
actionConfiguration: {
timeoutInMillisecond: 10000,
paginationType: "NONE",
encodeParamsToggle: true,
body: "async () => {\n\t\t//write code here\n\t}",
jsArguments: [],
},
executeOnLoad: false,
clientSideExecution: true,
dynamicBindingPathList: [
{
key: "body",
},
],
isValid: true,
invalids: [],
messages: [],
jsonPathKeys: ["() => {\n\t\t//write code here\n\t}"],
confirmBeforeExecute: false,
userPermissions: ["read:actions", "execute:actions", "manage:actions"],
validName: "JSObject2.myFun1",
},
],
deletedActions: [],
nameChangedActions: [],
changedVariables: [],
};
const parsedBodyWithAddedAction: ParsedBody = {
actions: [
{
name: "myFun1",
body: "() => {\n\t\t//write code here\n\t}",
arguments: [],
},
{
name: "myFun2",
body: "async () => {\n\t\t//use async-await or promises\n\t}",
arguments: [],
},
{
name: "myFun3",
body: "async () => {\n\t\t//use async-await or promises\n\t}",
arguments: [],
},
],
variables: [
{
name: "myVar1",
value: [],
},
{
name: "myVar2",
value: {},
},
],
};
const resultAddedAction = {
newActions: [
{
name: "myFun3",
executeOnLoad: false,
pageId: "page123",
collectionId: "1234",
workspaceId: "workspace123",
actionConfiguration: {
body: "async () => {\n\t\t//use async-await or promises\n\t}",
timeoutInMillisecond: 0,
jsArguments: [],
},
},
],
updateActions: [],
deletedActions: [],
nameChangedActions: [],
changedVariables: [],
};
describe("getDifferenceInJSCollection", () => {
it("gets name changed js action", () => {
const result = getDifferenceInJSCollection(
parsedBodyWithRenamedAction,
JSObject1,
);
expect(resultRenamedActions).toStrictEqual(result);
});
it("gets deleted js action", () => {
const result = getDifferenceInJSCollection(
parsedBodyWithDeletedAction,
JSObject1,
);
expect(resultDeletedActions).toStrictEqual(result);
});
it("gets added js action ", () => {
const result = getDifferenceInJSCollection(
parsedBodyWithAddedAction,
JSObject2,
);
expect(resultAddedAction).toStrictEqual(result);
});
it("gets changed variable value in difference", () => {
const result = getDifferenceInJSCollection(
parsedBodyWithChangedVariable,
JSObject2,
);
expect(resultChangedVariable).toStrictEqual(result);
});
it("gets updated body value in difference", () => {
const result = getDifferenceInJSCollection(
parsedBodyWithChangeInBody,
JSObject2,
);
expect(resultChangedBody).toStrictEqual(result);
});
it("gets updated params value in difference", () => {
const result = getDifferenceInJSCollection(
parsedBodyWithChangedParameters,
JSObject2,
);
expect(resultChangedParameters).toStrictEqual(result);
});
it("gets removed async tag in difference", () => {
const result = getDifferenceInJSCollection(
parsedBodyWithRemovedAsync,
JSObject2,
);
expect(resultRemovedAsync).toStrictEqual(result);
});
it("gets added async tag value in difference", () => {
const result = getDifferenceInJSCollection(
parsedBodyWithAddedAsync,
JSObject2,
);
expect(resultAddedAsync).toStrictEqual(result);
});
});
|
1,341 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/WidgetFeatures.test.ts | import { RenderModes } from "constants/WidgetConstants";
import type { WidgetProps } from "widgets/BaseWidget";
import {
DynamicHeight,
hideDynamicHeightPropertyControl,
} from "./WidgetFeatures";
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("Widget Features tests", () => {
it("Make sure hidden hook for dynamic Height disables if dynamic height is disabled", () => {
const inputs = [
DynamicHeight.FIXED,
"Some other value",
undefined,
null,
"hugcontents",
"hug_contents",
];
inputs.forEach((dynamicHeight) => {
const result = hideDynamicHeightPropertyControl({
...DUMMY_WIDGET,
dynamicHeight,
});
expect(result).toBe(true);
});
});
it("Make sure hidden hook for dynamic Height disabled if dynamic height with limits is disabled", () => {
const inputs = [DynamicHeight.AUTO_HEIGHT, "AUTO_HEIGHT"];
inputs.forEach((dynamicHeight) => {
const result = hideDynamicHeightPropertyControl({
...DUMMY_WIDGET,
dynamicHeight,
});
expect(result).toBe(true);
});
});
it("Make sure hidden hook for dynamic Height enabled if dynamic height with limits is enabled", () => {
const inputs = [
DynamicHeight.AUTO_HEIGHT_WITH_LIMITS,
"AUTO_HEIGHT_WITH_LIMITS",
];
inputs.forEach((dynamicHeight) => {
const result = hideDynamicHeightPropertyControl({
...DUMMY_WIDGET,
dynamicHeight,
});
expect(result).toBe(false);
});
});
});
|
1,343 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/WidgetLoadingStateUtils.test.ts | import { PluginType } from "entities/Action";
import type {
WidgetEntity,
ActionEntity,
JSActionEntity,
} from "@appsmith/entities/DataTree/types";
import { ENTITY_TYPE_VALUE } from "entities/DataTree/dataTreeFactory";
import {
findLoadingEntities,
getEntityDependantPaths,
groupAndFilterDependantsMap,
} from "utils/WidgetLoadingStateUtils";
import WidgetFactory from "../WidgetProvider/factory";
const JS_object_tree: JSActionEntity = {
pluginType: PluginType.JS,
name: "",
ENTITY_TYPE: ENTITY_TYPE_VALUE.JSACTION,
body: "",
meta: {},
dynamicBindingPathList: [],
bindingPaths: {},
reactivePaths: {},
variables: [],
dependencyMap: {},
actionId: "",
};
// @ts-expect-error: meta property not provided
const Select_tree: WidgetEntity = {
ENTITY_TYPE: ENTITY_TYPE_VALUE.WIDGET,
widgetId: "",
type: "",
widgetName: "",
renderMode: "CANVAS",
version: 0,
parentColumnSpace: 0,
parentRowSpace: 0,
leftColumn: 0,
rightColumn: 0,
topRow: 0,
bottomRow: 0,
isLoading: false,
animateLoading: true,
};
const Query_tree: ActionEntity = {
data: {},
actionId: "",
config: {},
run: {},
clear: {},
ENTITY_TYPE: ENTITY_TYPE_VALUE.ACTION,
datasourceUrl: "",
responseMeta: {
isExecutionSuccess: true,
},
isLoading: false,
};
const Api_tree: ActionEntity = {
data: {},
actionId: "",
config: {},
run: {},
clear: {},
ENTITY_TYPE: ENTITY_TYPE_VALUE.ACTION,
datasourceUrl: "",
responseMeta: {
isExecutionSuccess: true,
},
isLoading: false,
};
const Table_tree: WidgetEntity = {
ENTITY_TYPE: ENTITY_TYPE_VALUE.WIDGET,
widgetId: "",
type: "TABLE_WIDGET",
widgetName: "",
renderMode: "CANVAS",
version: 0,
parentColumnSpace: 0,
parentRowSpace: 0,
leftColumn: 0,
rightColumn: 0,
topRow: 0,
bottomRow: 0,
isLoading: false,
animateLoading: true,
meta: {},
};
const baseDataTree = {
JS_file: { ...JS_object_tree, name: "JS_file" },
Select1: { ...Select_tree, name: "Select1" },
Select2: { ...Select_tree, name: "Select2" },
Select3: { ...Select_tree, name: "Select3" },
Table1: { ...Table_tree, name: "Table1" },
Query1: { ...Query_tree, name: "Query1" },
Query2: { ...Query_tree, name: "Query2" },
Query3: { ...Query_tree, name: "Query3" },
Api1: { ...Api_tree, name: "Api1" },
};
describe("Widget loading state utils", () => {
describe("findLoadingEntites", () => {
// Select1.options -> JS_file.func1 -> Query1.data
// Select2.options -> JS_file.func2 -> Query2.data
// JS_file.func3 -> Query3.data
const baseInverseMap = {
"Query1.config": ["Query1"],
"Query1.config.body": ["Query1.config"],
"Query1.data": ["JS_file.func1", "Query1"],
"Query2.config": ["Query2"],
"Query2.config.body": ["Query2.config"],
"Query2.data": ["JS_file.func2", "Query2"],
"Query3.config": ["Query3"],
"Query3.config.body": ["Query3.config"],
"Query3.data": ["JS_file.func3"],
"JS_file.func1": ["Select1.options"],
"JS_file.func2": ["Select2.options"],
"Select1.options": [
"Select1.selectedOptionValue",
"Select1.selectedOptionLabel",
"Select1",
],
"Select2.options": [
"Select2.selectedOptionValue",
"Select2.selectedOptionLabel",
"Select2",
],
"Select3.options": [
"Select3.selectedOptionValue",
"Select3.selectedOptionLabel",
"Select3",
],
};
beforeAll(() => {
// mock WidgetFactory.getLoadingProperties
const loadingPropertiesMap = new Map<string, RegExp[]>();
loadingPropertiesMap.set("TABLE_WIDGET", [/.tableData$/]);
jest
.spyOn(WidgetFactory, "getLoadingProperties")
.mockImplementation((widgetType) =>
loadingPropertiesMap.get(widgetType),
);
});
afterAll(() => {
jest.restoreAllMocks();
});
// Select1.options -> JS_file.func1 -> Query1.data
it("handles linear dependencies", () => {
const loadingEntites = findLoadingEntities(
["Query1"],
baseDataTree,
baseInverseMap,
);
expect(loadingEntites).toStrictEqual(new Set(["Select1"]));
});
// Select1.options -> JS_file.func1 -> Query1.data
// Select2.options -> JS_file.func2 -> Query2.data
// Select3.options -> none
it("handles multiple dependencies", () => {
const loadingEntites = findLoadingEntities(
["Query1", "Query2", "Query3"],
baseDataTree,
baseInverseMap,
);
expect(loadingEntites).toStrictEqual(new Set(["Select1", "Select2"]));
});
// none -> Query3.data
it("handles no dependencies", () => {
const loadingEntites = findLoadingEntities(
["Query3"],
baseDataTree,
baseInverseMap,
);
expect(loadingEntites).toStrictEqual(new Set([]));
});
// JS_file.func1 -> Query1.run
// Select1.options -> Query1.data
it("handles Query.run and Query.data dependency", () => {
const loadingEntites = findLoadingEntities(["Query1"], baseDataTree, {
"Query1.config": ["Query1"],
"Query1.config.body": ["Query1.config"],
"Query1.run": ["JS_file.func1"],
"Query1.data": ["Select1.options", "Query1"],
"JS_file.func1": [],
"Select1.options": [
"Select1.selectedOptionValue",
"Select1.selectedOptionLabel",
"Select1",
],
});
expect(loadingEntites).toStrictEqual(new Set(["Select1"]));
});
// Select1.options -> JS_file.func1 -> JS_file.internalFunc -> Query1.data
it("handles nested JS dependencies within same file", () => {
const loadingEntites = findLoadingEntities(["Query1"], baseDataTree, {
"Query1.config": ["Query1"],
"Query1.config.body": ["Query1.config"],
"Query1.data": ["JS_file.internalFunc", "Query1"],
"JS_file.internalFunc": ["JS_file.func1"],
"JS_file.func1": ["Select1.options"],
"Select1.options": [
"Select1.selectedOptionValue",
"Select1.selectedOptionLabel",
"Select1",
],
});
expect(loadingEntites).toStrictEqual(new Set(["Select1"]));
});
// Select1.options -> JS_file1.func1 -> JS_file2.internalFunc -> Query1.data
it("handles nested JS dependencies between files", () => {
const loadingEntites = findLoadingEntities(
["Query1"],
{
...baseDataTree,
JS_file1: { ...JS_object_tree, name: "JS_file1" },
JS_file2: { ...JS_object_tree, name: "JS_file2" },
},
{
"Query1.config": ["Query1"],
"Query1.config.body": ["Query1.config"],
"Query1.data": ["JS_file2.internalFunc", "Query1"],
"JS_file2.internalFunc": ["JS_file1.func1"],
"JS_file1.func1": ["Select1.options"],
"Select1.options": [
"Select1.selectedOptionValue",
"Select1.selectedOptionLabel",
"Select1",
],
},
);
expect(loadingEntites).toStrictEqual(new Set(["Select1"]));
});
/* Select1.options -> JS.func1 -> Query1.data,
Select2.options -> Query2.data,
JS.func2 -> Query2.run
When Query2 is called.
Only Select2 should be listed, not Select1.
*/
it("handles selective dependencies in same JS file", () => {
const loadingEntites = findLoadingEntities(["Query2"], baseDataTree, {
"Query1.config": ["Query1"],
"Query1.config.body": ["Query1.config"],
"Query1.data": ["JS_file.func1"],
"Query2.config": ["Query2"],
"Query2.config.body": ["Query2.config"],
"Query2.data": ["JS_file.func2"],
"JS_file.func1": ["Select1.options"],
"JS_file.func2": ["Select2.options"],
"Select1.options": [
"Select1.selectedOptionValue",
"Select1.selectedOptionLabel",
"Select1",
],
"Select2.options": [
"Select2.selectedOptionValue",
"Select2.selectedOptionLabel",
"Select2",
],
});
expect(loadingEntites).toStrictEqual(new Set(["Select2"]));
});
it("includes loading properties", () => {
const loadingEntites = findLoadingEntities(["Api1"], baseDataTree, {
"Api1.data": ["Table1.tableData"],
});
expect(loadingEntites).toStrictEqual(new Set(["Table1"]));
});
it("ignores non-loading properties", () => {
const loadingEntites = findLoadingEntities(["Api1"], baseDataTree, {
"Api1.run": ["Table1.primaryColumns.action.onClick"],
});
expect(loadingEntites).toStrictEqual(new Set());
});
});
describe("groupAndFilterDependantsMap", () => {
it("groups entities and filters self-dependencies", () => {
const groupedDependantsMap = groupAndFilterDependantsMap(
{
"Query1.config": ["Query1"],
"Query1.config.body": ["Query1.config"],
"Query1.data": ["JS_file.func1", "Query1"], // dependant
"Query2.config": ["Query2"],
"Query2.config.body": ["Query2.config"],
"Query2.run": ["Query2", "JS_file.func2"], // dependant
"Query2.data": ["Query2", "Select2.options"], // dependant
"Query3.config": ["Query3"],
"Query3.config.body": ["Query3.config"],
"JS_file.func1": ["Select1.options"], // dependant
"Select1.options": [
"Select1.selectedOptionValue",
"Select1.selectedOptionLabel",
"Select1",
],
"Select2.options": [
"Select2.selectedOptionValue",
"Select2.selectedOptionLabel",
"Select2",
],
},
baseDataTree,
);
expect(groupedDependantsMap).toStrictEqual({
Query1: { "Query1.data": ["JS_file.func1"] },
Query2: {
"Query2.run": ["JS_file.func2"],
"Query2.data": ["Select2.options"],
},
JS_file: {
"JS_file.func1": ["Select1.options"],
},
});
});
it("includes JS Object's self dependencies", () => {
const groupedDependantsMap = groupAndFilterDependantsMap(
{
"JS_file.func1": ["Select1.options"], // dependant
"JS_file.internalFunc": ["JS_file.func1"], // self-dependant JsObject
},
baseDataTree,
);
expect(groupedDependantsMap).toStrictEqual({
JS_file: {
"JS_file.func1": ["Select1.options"],
"JS_file.internalFunc": ["JS_file.func1"],
},
});
});
it("includes JS Object's nested self dependencies", () => {
const groupedDependantsMap = groupAndFilterDependantsMap(
{
"JS_file.func1": ["Select1.options"], // dependant
"JS_file.internalFunc2": ["JS_file.func1"], // self-dependant JsObject
"JS_file.internalFunc1": ["JS_file.internalFunc2"], // self-dependant JsObject
},
baseDataTree,
);
expect(groupedDependantsMap).toStrictEqual({
JS_file: {
"JS_file.func1": ["Select1.options"],
"JS_file.internalFunc2": ["JS_file.func1"],
"JS_file.internalFunc1": ["JS_file.internalFunc2"],
},
});
});
});
describe("getEntityDependantPaths", () => {
// Select1.options -> JS_file.func1 -> Query1.data
it("handles simple dependency", () => {
const dependants = getEntityDependantPaths(
["Query1"],
{
Query1: {
"Query1.data": ["JS_file.func1"],
},
JS_file: {
"JS_file.func1": ["Select1.options"],
},
},
new Set<string>(),
);
expect(dependants).toStrictEqual(
new Set(["JS_file.func1", "Select1.options"]),
);
});
// Select1.options -> JS_file.func1 -> Query1.data
// Select2.options -> JS_file.func2 -> Query1.data
it("handles multiple dependencies", () => {
const dependants = getEntityDependantPaths(
["Query1"],
{
Query1: {
"Query1.data": ["JS_file.func1", "JS_file.func2"],
},
JS_file: {
"JS_file.func1": ["Select1.options"],
"JS_file.func2": ["Select2.options"],
},
},
new Set<string>(),
);
expect(dependants).toStrictEqual(
new Set([
"JS_file.func1",
"Select1.options",
"JS_file.func2",
"Select2.options",
]),
);
});
it("handles specific entity paths", () => {
const dependants = getEntityDependantPaths(
["JS_file.func2"], // specific path
{
Query1: {
"Query1.data": ["JS_file.func1"],
},
Query2: {
"Query2.data": ["JS_file.func2"],
},
JS_file: {
"JS_file.func1": ["Select1.options"],
"JS_file.func2": ["Select2.options"],
},
},
new Set<string>(),
);
expect(dependants).toStrictEqual(new Set(["Select2.options"]));
});
// Select1.options -> JS_file.func1 -> JS_file.internalFunc -> Query1.data
it("handles JS self-dependencies", () => {
const dependants = getEntityDependantPaths(
["Query1"],
{
Query1: {
"Query1.data": ["JS_file.internalFunc"],
},
JS_file: {
"JS_file.internalFunc": ["JS_file.func1"],
"JS_file.func1": ["Select1.options"],
},
},
new Set<string>(),
);
expect(dependants).toStrictEqual(
new Set(["JS_file.internalFunc", "JS_file.func1", "Select1.options"]),
);
});
// Select1.options -> JS_file.func -> JS_file.internalFunc1 -> JS_file.internalFunc2 -> Query1.data
it("handles nested JS self-dependencies", () => {
const dependants = getEntityDependantPaths(
["Query1"],
{
Query1: {
"Query1.data": ["JS_file.internalFunc2"],
},
JS_file: {
"JS_file.internalFunc2": ["JS_file.internalFunc1"],
"JS_file.internalFunc1": ["JS_file.func"],
"JS_file.func": ["Select1.options"],
},
},
new Set<string>(),
);
expect(dependants).toStrictEqual(
new Set([
"JS_file.internalFunc1",
"JS_file.internalFunc2",
"JS_file.func",
"Select1.options",
]),
);
});
/* Select1.options -> JS.func1 -> Query1.data,
Select2.options -> Query2.data,
JS.func2 -> Query2.run
When Query2 is called.
Only Select2 should be listed, not Select1.
*/
it("handles selective dependencies in same JS file", () => {
const dependants = getEntityDependantPaths(
["Query2"],
{
Query1: {
"Query1.data": ["JS_file.func1"],
},
Query2: {
"Query2.data": ["JS_file.func2"],
},
JS_file: {
"JS_file.func1": ["Select1.options"],
"JS_file.func2": ["Select2.options"],
},
},
new Set<string>(),
);
expect(dependants).toStrictEqual(
new Set(["JS_file.func2", "Select2.options"]),
);
});
});
});
|
1,345 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/WidgetMigrationUtils.test.ts | import { cloneDeep, noop } from "lodash";
import type { DSLWidget } from "WidgetProvider/constants";
import { traverseDSLAndMigrate } from "./WidgetMigrationUtils";
const dsl = {
children: [
{
name: "widget1",
children: [
{
name: "widget2",
},
{
name: "widget3",
},
],
},
{
name: "widget4",
},
],
};
describe("traverseDSLAndMigrate", () => {
it("should check that migration function is getting called for each widget in the tree", () => {
const migrateFn = jest.fn();
traverseDSLAndMigrate(dsl as any as DSLWidget, migrateFn);
expect(migrateFn).toHaveBeenCalledTimes(4);
});
it("should check that tree structure remain intact", () => {
const copyDSL = cloneDeep(dsl);
traverseDSLAndMigrate(dsl as any as DSLWidget, noop);
expect(dsl).toEqual(copyDSL);
});
it("should check that migration function updates are written in the tree", () => {
traverseDSLAndMigrate(dsl as any as DSLWidget, (widget) => {
widget.type = "widget";
});
expect(dsl).toEqual({
children: [
{
name: "widget1",
type: "widget",
children: [
{
name: "widget2",
type: "widget",
},
{
name: "widget3",
type: "widget",
},
],
},
{
name: "widget4",
type: "widget",
},
],
});
});
});
|
1,347 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/WidgetPropsUtils.test.tsx | import * as generators from "utils/generators";
import { RenderModes } from "constants/WidgetConstants";
import {
migrateChartDataFromArrayToObject,
migrateToNewLayout,
migrateInitialValues,
migrateToNewMultiSelect,
} from "./DSLMigrations";
import {
buildChildren,
widgetCanvasFactory,
buildDslWithChildren,
} from "test/factories/WidgetFactoryUtils";
import { cloneDeep } from "lodash";
import { GRID_DENSITY_MIGRATION_V1 } from "WidgetProvider/constants";
import {
extractCurrentDSL,
getDraggingSpacesFromBlocks,
getMousePositionsOnCanvas,
} from "./WidgetPropsUtils";
import type { WidgetDraggingBlock } from "layoutSystems/common/canvasArenas/ArenaTypes";
import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants";
describe("WidgetProps tests", () => {
it("should convert WidgetDraggingBlocks to occupied Spaces", () => {
const draggingBlocks: WidgetDraggingBlock[] = [
{
left: 100,
top: 100,
width: 210,
height: 220,
widgetId: "1",
isNotColliding: true,
columnWidth: 10,
rowHeight: 10,
type: "",
},
{
left: 310,
top: 120,
width: 70,
height: 80,
widgetId: "2",
isNotColliding: true,
columnWidth: 10,
rowHeight: 10,
type: "",
},
];
const draggingSpaces = [
{
left: 10,
top: 10,
right: 31,
bottom: 32,
id: "1",
},
{
left: 31,
top: 12,
right: 38,
bottom: 20,
id: "2",
},
];
const snapColumnSpace = 10,
snapRowSpace = 10;
expect(
getDraggingSpacesFromBlocks(
draggingBlocks,
snapColumnSpace,
snapRowSpace,
),
).toEqual(draggingSpaces);
});
it("getMousePositionsOnCanvas should Return Mouse Position relative to Canvas", () => {
const gridProps = {
parentColumnSpace: 10,
parentRowSpace: 10,
maxGridColumns: 64,
};
const mouseEvent = {
offsetX: 500,
offsetY: 600,
} as unknown as MouseEvent;
expect(getMousePositionsOnCanvas(mouseEvent, gridProps)).toEqual({
id: "mouse",
top: 59,
left: 49,
bottom: 60,
right: 50,
});
});
it("getMousePositionsOnCanvas should even return negative Mouse Position relative to Canvas", () => {
const gridProps = {
parentColumnSpace: 10,
parentRowSpace: 10,
maxGridColumns: 64,
};
const mouseEvent = {
offsetX: 2,
offsetY: 5,
} as unknown as MouseEvent;
expect(getMousePositionsOnCanvas(mouseEvent, gridProps)).toEqual({
id: "mouse",
top: -1,
left: -1,
bottom: 0,
right: 0,
});
});
it("it checks if array to object migration functions for chart widget ", () => {
const input = {
type: "CANVAS_WIDGET",
widgetId: "0",
widgetName: "canvas",
parentColumnSpace: 1,
parentRowSpace: 1,
leftColumn: 0,
rightColumn: 0,
topRow: 0,
bottomRow: 0,
version: 17,
isLoading: false,
renderMode: RenderModes.CANVAS,
children: [
{
widgetId: "some-random-id",
widgetName: "chart1",
parentColumnSpace: 1,
parentRowSpace: 1,
leftColumn: 0,
rightColumn: 0,
topRow: 0,
bottomRow: 0,
version: 17,
isLoading: false,
renderMode: RenderModes.CANVAS,
type: "CHART_WIDGET",
chartData: [
{
seriesName: "seris1",
data: [{ x: 1, y: 2 }],
},
],
},
],
};
// mocking implementation of our generateReactKey function
const generatorReactKeyMock = jest.spyOn(generators, "generateReactKey");
generatorReactKeyMock.mockImplementation(() => "some-random-key");
const result = migrateChartDataFromArrayToObject(input);
const output = {
type: "CANVAS_WIDGET",
widgetId: "0",
widgetName: "canvas",
parentColumnSpace: 1,
parentRowSpace: 1,
leftColumn: 0,
rightColumn: 0,
topRow: 0,
bottomRow: 0,
version: 17,
isLoading: false,
renderMode: RenderModes.CANVAS,
children: [
{
widgetId: "some-random-id",
widgetName: "chart1",
parentColumnSpace: 1,
parentRowSpace: 1,
leftColumn: 0,
rightColumn: 0,
topRow: 0,
bottomRow: 0,
version: 17,
isLoading: false,
renderMode: RenderModes.CANVAS,
type: "CHART_WIDGET",
dynamicBindingPathList: [],
chartData: {
"some-random-key": {
seriesName: "seris1",
data: [{ x: 1, y: 2 }],
},
},
},
],
};
expect(result).toStrictEqual(output);
});
it("Grid density migration - Main container widgets", () => {
const dsl: any = buildDslWithChildren([{ type: "TABS_WIDGET" }]);
const newMigratedDsl: any = migrateToNewLayout(cloneDeep(dsl));
expect(dsl.children[0].topRow * GRID_DENSITY_MIGRATION_V1).toBe(
newMigratedDsl.children[0].topRow,
);
expect(dsl.children[0].bottomRow * GRID_DENSITY_MIGRATION_V1).toBe(
newMigratedDsl.children[0].bottomRow,
);
expect(dsl.children[0].rightColumn * GRID_DENSITY_MIGRATION_V1).toBe(
newMigratedDsl.children[0].rightColumn,
);
expect(dsl.children[0].leftColumn * GRID_DENSITY_MIGRATION_V1).toBe(
newMigratedDsl.children[0].leftColumn,
);
});
it("Grid density migration - widgets inside a container", () => {
const childrenInsideContainer = buildChildren([
{ type: "SWITCH_WIDGET" },
{ type: "FORM_WIDGET" },
{ type: "CONTAINER_WIDGET" },
]);
const dslWithContainer: any = buildDslWithChildren([
{ type: "CONTAINER_WIDGET", children: childrenInsideContainer },
]);
const newMigratedDsl: any = migrateToNewLayout(cloneDeep(dslWithContainer));
// Container migrated checks
const containerWidget = dslWithContainer.children[0];
const migratedContainer = newMigratedDsl.children[0];
expect(containerWidget.topRow * GRID_DENSITY_MIGRATION_V1).toBe(
migratedContainer.topRow,
);
expect(containerWidget.bottomRow * GRID_DENSITY_MIGRATION_V1).toBe(
migratedContainer.bottomRow,
);
expect(containerWidget.rightColumn * GRID_DENSITY_MIGRATION_V1).toBe(
migratedContainer.rightColumn,
);
expect(containerWidget.leftColumn * GRID_DENSITY_MIGRATION_V1).toBe(
migratedContainer.leftColumn,
);
// Children inside container miragted
containerWidget.children.forEach((eachChild: any, index: any) => {
const migratedChild = migratedContainer.children[index];
expect(eachChild.topRow * GRID_DENSITY_MIGRATION_V1).toBe(
migratedChild.topRow,
);
expect(eachChild.bottomRow * GRID_DENSITY_MIGRATION_V1).toBe(
migratedChild.bottomRow,
);
expect(eachChild.rightColumn * GRID_DENSITY_MIGRATION_V1).toBe(
migratedChild.rightColumn,
);
expect(eachChild.leftColumn * GRID_DENSITY_MIGRATION_V1).toBe(
migratedChild.leftColumn,
);
});
});
});
describe("Initial value migration test", () => {
const containerWidget = {
widgetName: "MainContainer",
backgroundColor: "none",
rightColumn: 1118,
snapColumns: 16,
detachFromLayout: true,
widgetId: "0",
topRow: 0,
bottomRow: 560,
snapRows: 33,
isLoading: false,
parentRowSpace: 1,
type: "CANVAS_WIDGET",
renderMode: RenderModes.CANVAS,
canExtend: true,
version: 18,
minHeight: 600,
parentColumnSpace: 1,
dynamicTriggerPathList: [],
dynamicBindingPathList: [],
leftColumn: 0,
};
it("Input widget", () => {
const input = {
...containerWidget,
children: [
{
widgetName: "Input1",
rightColumn: 8,
widgetId: "ra3vyy3nt2",
topRow: 1,
bottomRow: 2,
parentRowSpace: 40,
isVisible: true,
label: "",
type: "INPUT_WIDGET",
version: 1,
parentId: "0",
isLoading: false,
parentColumnSpace: 67.375,
leftColumn: 3,
inputType: "TEXT",
renderMode: RenderModes.CANVAS,
resetOnSubmit: false,
},
],
};
const output = {
...containerWidget,
children: [
{
widgetName: "Input1",
rightColumn: 8,
widgetId: "ra3vyy3nt2",
topRow: 1,
bottomRow: 2,
parentRowSpace: 40,
isVisible: true,
label: "",
type: "INPUT_WIDGET",
version: 1,
parentId: "0",
isLoading: false,
parentColumnSpace: 67.375,
renderMode: "CANVAS",
leftColumn: 3,
inputType: "TEXT",
// will not override existing property
resetOnSubmit: false,
// following properties get added
isRequired: false,
isDisabled: false,
},
],
};
expect(migrateInitialValues(input)).toEqual(output);
});
it("SELECT_WIDGET", () => {
const input = {
...containerWidget,
children: [
{
widgetName: "Select1",
rightColumn: 6,
selectionType: "SINGLE_SELECT",
widgetId: "1e3ytl2pl9",
topRow: 3,
bottomRow: 4,
parentRowSpace: 40,
isVisible: true,
label: "",
isRequired: false,
isDisabled: false,
type: "SELECT_WIDGET",
version: 1,
parentId: "0",
isLoading: false,
defaultOptionValue: "GREEN",
parentColumnSpace: 67.375,
renderMode: RenderModes.CANVAS,
leftColumn: 1,
options: [
{
label: "Blue",
value: "BLUE",
},
{
label: "Green",
value: "GREEN",
},
{
label: "Red",
value: "RED",
},
],
},
],
};
const output = {
...containerWidget,
children: [
{
widgetName: "Select1",
rightColumn: 6,
widgetId: "1e3ytl2pl9",
topRow: 3,
bottomRow: 4,
parentRowSpace: 40,
isVisible: true,
label: "",
selectionType: "SINGLE_SELECT",
type: "SELECT_WIDGET",
version: 1,
parentId: "0",
isLoading: false,
defaultOptionValue: "GREEN",
parentColumnSpace: 67.375,
renderMode: "CANVAS",
leftColumn: 1,
options: [
{
label: "Blue",
value: "BLUE",
},
{
label: "Green",
value: "GREEN",
},
{
label: "Red",
value: "RED",
},
],
isRequired: false,
isDisabled: false,
},
],
};
expect(migrateInitialValues(input)).toEqual(output);
});
it("MULTI_SELECT_WIDGET", () => {
const input = {
...containerWidget,
children: [
{
widgetName: "Select2",
rightColumn: 59,
isFilterable: true,
widgetId: "zvgz9h4fh4",
topRow: 10,
bottomRow: 14,
parentRowSpace: 10,
isVisible: true,
label: "",
type: "DROP_DOWN_WIDGET",
version: 1,
parentId: "0y8sg136kg",
isLoading: false,
defaultOptionValue: "GREEN",
selectionType: "MULTI_SELECT",
parentColumnSpace: 8.35546875,
dynamicTriggerPathList: [],
leftColumn: 39,
dynamicBindingPathList: [],
renderMode: RenderModes.CANVAS,
options: [
{
label: "Blue",
value: "BLUE",
},
{
label: "Green",
value: "GREEN",
},
{
label: "Red",
value: "RED",
},
],
},
],
};
const output = {
...containerWidget,
children: [
{
renderMode: RenderModes.CANVAS,
type: "MULTI_SELECT_WIDGET",
widgetName: "Select2",
rightColumn: 59,
widgetId: "zvgz9h4fh4",
topRow: 10,
bottomRow: 14,
parentRowSpace: 10,
isVisible: true,
label: "",
version: 1,
parentId: "0y8sg136kg",
isLoading: false,
defaultOptionValue: "GREEN",
parentColumnSpace: 8.35546875,
dynamicTriggerPathList: [],
leftColumn: 39,
dynamicBindingPathList: [],
options: [
{
label: "Blue",
value: "BLUE",
},
{
label: "Green",
value: "GREEN",
},
{
label: "Red",
value: "RED",
},
],
},
],
};
expect(migrateToNewMultiSelect(input)).toEqual(output);
});
it("DATE_PICKER_WIDGET2", () => {
const input = {
...containerWidget,
children: [
{
widgetName: "DatePicker1",
defaultDate: "2021-05-12T06:50:51.743Z",
rightColumn: 7,
dateFormat: "YYYY-MM-DD HH:mm",
widgetId: "5jbfazqnca",
topRow: 2,
bottomRow: 3,
parentRowSpace: 40,
isVisible: true,
datePickerType: "DATE_PICKER",
label: "",
type: "DATE_PICKER_WIDGET2",
renderMode: RenderModes.CANVAS,
version: 2,
parentId: "0",
isLoading: false,
parentColumnSpace: 67.375,
leftColumn: 2,
isDisabled: false,
},
],
};
const output = {
...containerWidget,
children: [
{
widgetName: "DatePicker1",
defaultDate: "2021-05-12T06:50:51.743Z",
rightColumn: 7,
dateFormat: "YYYY-MM-DD HH:mm",
widgetId: "5jbfazqnca",
topRow: 2,
bottomRow: 3,
parentRowSpace: 40,
isVisible: true,
datePickerType: "DATE_PICKER",
label: "",
type: "DATE_PICKER_WIDGET2",
renderMode: RenderModes.CANVAS,
version: 2,
parentId: "0",
isLoading: false,
parentColumnSpace: 67.375,
leftColumn: 2,
isDisabled: false,
// following properties get added
isRequired: false,
minDate: "2001-01-01 00:00",
maxDate: "2041-12-31 23:59",
},
],
};
expect(migrateInitialValues(input)).toEqual(output);
});
it("SWITCH_WIDGET", () => {
const input = {
...containerWidget,
children: [
{
widgetName: "Switch1",
rightColumn: 5,
widgetId: "4ksqurxmwn",
topRow: 2,
bottomRow: 3,
parentRowSpace: 40,
isVisible: true,
label: "Label",
type: "SWITCH_WIDGET",
renderMode: RenderModes.CANVAS,
defaultSwitchState: true,
version: 1,
alignWidget: "LEFT",
parentId: "0",
isLoading: false,
parentColumnSpace: 67.375,
leftColumn: 3,
},
],
};
const output = {
...containerWidget,
children: [
{
widgetName: "Switch1",
rightColumn: 5,
widgetId: "4ksqurxmwn",
topRow: 2,
bottomRow: 3,
parentRowSpace: 40,
isVisible: true,
label: "Label",
type: "SWITCH_WIDGET",
renderMode: RenderModes.CANVAS,
defaultSwitchState: true,
version: 1,
alignWidget: "LEFT",
parentId: "0",
isLoading: false,
parentColumnSpace: 67.375,
leftColumn: 3,
// following properties get added
isDisabled: false,
},
],
};
expect(migrateInitialValues(input)).toEqual(output);
});
it("Video widget", () => {
const input = {
...containerWidget,
children: [
{
widgetName: "Video1",
rightColumn: 9,
dynamicPropertyPathList: [],
widgetId: "ti5b5f5hvq",
topRow: 3,
bottomRow: 10,
parentRowSpace: 40,
isVisible: true,
type: "VIDEO_WIDGET",
renderMode: RenderModes.CANVAS,
version: 1,
onPlay: "",
url: `${ASSETS_CDN_URL}/widgets/bird.mp4`,
parentId: "0",
isLoading: false,
parentColumnSpace: 67.375,
leftColumn: 2,
autoPlay: false,
},
],
};
const output = {
...containerWidget,
children: [
{
widgetName: "Video1",
rightColumn: 9,
dynamicPropertyPathList: [],
widgetId: "ti5b5f5hvq",
topRow: 3,
bottomRow: 10,
parentRowSpace: 40,
isVisible: true,
type: "VIDEO_WIDGET",
renderMode: RenderModes.CANVAS,
version: 1,
onPlay: "",
url: `${ASSETS_CDN_URL}/widgets/bird.mp4`,
parentId: "0",
isLoading: false,
parentColumnSpace: 67.375,
leftColumn: 2,
autoPlay: false,
// following properties get added
isRequired: false,
isDisabled: false,
},
],
};
expect(migrateInitialValues(input)).toEqual(output);
});
it("CHECKBOX_WIDGET", () => {
const input = {
...containerWidget,
children: [
{
widgetName: "Checkbox1",
rightColumn: 8,
widgetId: "djxhhl1p7t",
topRow: 4,
bottomRow: 5,
parentRowSpace: 40,
isVisible: true,
label: "Label",
type: "CHECKBOX_WIDGET",
renderMode: RenderModes.CANVAS,
version: 1,
alignWidget: "LEFT",
parentId: "0",
isLoading: false,
parentColumnSpace: 67.375,
leftColumn: 5,
defaultCheckedState: true,
},
],
};
const output = {
...containerWidget,
children: [
{
widgetName: "Checkbox1",
rightColumn: 8,
widgetId: "djxhhl1p7t",
topRow: 4,
bottomRow: 5,
parentRowSpace: 40,
isVisible: true,
label: "Label",
type: "CHECKBOX_WIDGET",
renderMode: RenderModes.CANVAS,
version: 1,
alignWidget: "LEFT",
parentId: "0",
isLoading: false,
parentColumnSpace: 67.375,
leftColumn: 5,
defaultCheckedState: true,
// following properties get added
isDisabled: false,
isRequired: false,
},
],
};
expect(migrateInitialValues(input)).toEqual(output);
});
it("RADIO_GROUP_WIDGET", () => {
const input = {
...containerWidget,
children: [
{
widgetName: "RadioGroup1",
rightColumn: 5,
widgetId: "4ixyqnw2no",
topRow: 3,
bottomRow: 5,
parentRowSpace: 40,
isVisible: true,
label: "",
type: "RADIO_GROUP_WIDGET",
renderMode: RenderModes.CANVAS,
version: 1,
parentId: "0",
isLoading: false,
defaultOptionValue: "Y",
parentColumnSpace: 67.375,
leftColumn: 2,
options: [
{
label: "Yes",
value: "Y",
},
{
label: "No",
value: "N",
},
],
},
],
};
const output = {
...containerWidget,
children: [
{
widgetName: "RadioGroup1",
rightColumn: 5,
widgetId: "4ixyqnw2no",
topRow: 3,
bottomRow: 5,
parentRowSpace: 40,
isVisible: true,
label: "",
type: "RADIO_GROUP_WIDGET",
renderMode: RenderModes.CANVAS,
version: 1,
parentId: "0",
isLoading: false,
defaultOptionValue: "Y",
parentColumnSpace: 67.375,
leftColumn: 2,
options: [
{
label: "Yes",
value: "Y",
},
{
label: "No",
value: "N",
},
],
// following properties get added
isDisabled: false,
isRequired: false,
},
],
};
expect(migrateInitialValues(input)).toEqual(output);
});
it("FILE_PICKER_WIDGET", () => {
const input = {
...containerWidget,
children: [
{
widgetName: "FilePicker1",
rightColumn: 5,
isDefaultClickDisabled: true,
widgetId: "fzajyy8qft",
topRow: 4,
bottomRow: 5,
parentRowSpace: 40,
isVisible: true,
label: "Select Files",
maxFileSize: 5,
type: "FILE_PICKER_WIDGET",
renderMode: RenderModes.CANVAS,
version: 1,
fileDataType: "Base64",
parentId: "0",
isLoading: false,
parentColumnSpace: 67.375,
leftColumn: 1,
files: [],
maxNumFiles: 1,
},
],
};
const output = {
...containerWidget,
children: [
{
widgetName: "FilePicker1",
rightColumn: 5,
isDefaultClickDisabled: true,
widgetId: "fzajyy8qft",
topRow: 4,
bottomRow: 5,
parentRowSpace: 40,
isVisible: true,
label: "Select Files",
maxFileSize: 5,
type: "FILE_PICKER_WIDGET",
renderMode: RenderModes.CANVAS,
version: 1,
fileDataType: "Base64",
parentId: "0",
isLoading: false,
parentColumnSpace: 67.375,
leftColumn: 1,
files: [],
maxNumFiles: 1,
// following properties get added
isDisabled: false,
isRequired: false,
allowedFileTypes: [],
},
],
};
expect(migrateInitialValues(input)).toEqual(output);
});
it("", () => {
const tabsWidgetDSL: any = (version = 1) => {
const children: any = buildChildren([
{
version,
type: "TABS_WIDGET",
children: [
{
type: "CANVAS_WIDGET",
tabId: "tab1212332",
tabName: "Newly Added Tab",
widgetId: "o9ody00ep7",
parentId: "jd83uvbkmp",
detachFromLayout: true,
children: [],
parentRowSpace: 1,
parentColumnSpace: 1,
// leftColumn: 0,
// rightColumn: 592, // Commenting these coz they are not provided for a newly added tab in the Tabs widget version 2
// bottomRow: 280,
topRow: 0,
isLoading: false,
widgetName: "Canvas1",
renderMode: "CANVAS",
},
],
},
]);
const dsl: any = widgetCanvasFactory.build({
children,
});
return {
data: {
layouts: [{ dsl }],
},
};
};
const migratedDslV2: any = extractCurrentDSL({
response: tabsWidgetDSL(),
}).dsl;
expect(migratedDslV2.children[0].children[0].leftColumn).toBeNaN();
const migratedDslV3: any = extractCurrentDSL({
response: tabsWidgetDSL(2),
}).dsl;
expect(migratedDslV3.children[0].version).toBe(3);
expect(migratedDslV3.children[0].children[0].leftColumn).not.toBeNaN();
expect(migratedDslV3.children[0].children[0].leftColumn).toBe(0);
});
});
|
1,349 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/WidgetQueryGeneratorRegistry.test.ts | import WidgetQueryGeneratorRegistry from "./WidgetQueryGeneratorRegistry";
describe("WidgetQueryGeneratorRegistry", () => {
const somepluginId = "somePluginId";
it("should be able to register a QueryGenerator", () => {
const someQueryGenerator = {};
WidgetQueryGeneratorRegistry.register(somepluginId, someQueryGenerator);
expect(WidgetQueryGeneratorRegistry.get(somepluginId)).toBeTruthy();
});
it("should return a falsey value when searching for an non existing generator", () => {
const nonExistingQueryGeneratopr = "someId";
expect(
WidgetQueryGeneratorRegistry.get(nonExistingQueryGeneratopr),
).toBeFalsy();
});
it("should return the same adaptor reference when querying the same pluginId", () => {
const adaptor = WidgetQueryGeneratorRegistry.get(somepluginId);
expect(adaptor).toBe(WidgetQueryGeneratorRegistry.get(somepluginId));
});
it("should not find the registered plugin after clearing the registry", () => {
WidgetQueryGeneratorRegistry.clear();
expect(WidgetQueryGeneratorRegistry.get(somepluginId)).toBeFalsy();
});
afterAll(() => {
WidgetQueryGeneratorRegistry.clear();
});
});
|
1,351 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/WidgetSizeUtils.test.ts | import { RenderModes } from "constants/WidgetConstants";
import type { WidgetProps } from "widgets/BaseWidget";
import {
getCanvasBottomRow,
getCanvasWidgetHeightsToUpdate,
} from "./WidgetSizeUtils";
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: "",
};
it("Computes the bottomRow of the canvas within a container correctly", () => {
const canvasWidgets = {
x: {
...DUMMY_WIDGET,
widgetId: "x",
bottomRow: 20,
topRow: 10,
type: "CONTAINER_WIDGET",
children: ["m"],
},
m: {
...DUMMY_WIDGET,
widgetId: "m",
parentId: "x",
children: ["n", "o"],
type: "CANVAS_WIDGET",
},
n: {
...DUMMY_WIDGET,
bottomRow: 30,
},
o: {
...DUMMY_WIDGET,
bottomRow: 5,
},
};
const result = getCanvasBottomRow("m", canvasWidgets);
expect(result).toBe(300);
});
it("Computes the bottomRow of the canvas within a Modal correctly", () => {
const canvasWidgets = {
x: {
...DUMMY_WIDGET,
widgetId: "x",
bottomRow: 20,
topRow: 10,
height: 200,
type: "MODAL_WIDGET",
children: ["m"],
},
m: {
...DUMMY_WIDGET,
widgetId: "m",
parentId: "x",
children: ["n", "o"],
type: "CANVAS_WIDGET",
},
n: {
...DUMMY_WIDGET,
parentId: "m",
bottomRow: 30,
},
o: {
...DUMMY_WIDGET,
parentId: "m",
bottomRow: 5,
},
};
const result = getCanvasBottomRow("m", canvasWidgets);
expect(result).toBe(300);
});
it("Ignores the detached children of the canvas correctly", () => {
const canvasWidgets = {
x: {
...DUMMY_WIDGET,
widgetId: "x",
bottomRow: 20,
topRow: 10,
type: "CANVAS_WIDGET",
children: ["m"],
},
m: {
...DUMMY_WIDGET,
widgetId: "m",
parentId: "x",
children: ["n", "o"],
type: "CANVAS_WIDGET",
},
n: {
...DUMMY_WIDGET,
detachFromLayout: true,
parentId: "m",
bottomRow: 30,
},
o: {
...DUMMY_WIDGET,
parentId: "m",
bottomRow: 5,
},
};
const result = getCanvasBottomRow("m", canvasWidgets);
expect(result).toBe(100);
});
it("Computes the bottomRow of the canvas within a Modal correctly", () => {
const canvasWidgets = {
x: {
...DUMMY_WIDGET,
widgetId: "x",
bottomRow: 20,
topRow: 10,
height: 500,
type: "MODAL_WIDGET",
children: ["m"],
},
m: {
...DUMMY_WIDGET,
widgetId: "m",
parentId: "x",
children: ["n", "o"],
type: "CANVAS_WIDGET",
},
n: {
...DUMMY_WIDGET,
bottomRow: 30,
},
o: {
...DUMMY_WIDGET,
bottomRow: 5,
},
};
const result = getCanvasBottomRow("m", canvasWidgets);
expect(result).toBe(500);
});
it("Computes the bottomRow of the canvas within a Container when the container has larger height correctly", () => {
// The Container widget has a height of 10 rows, while the lowest widget is at 6 rows, so, the canvas should take this into account
// and return 10 * Row height == 100
const canvasWidgets = {
x: {
...DUMMY_WIDGET,
widgetId: "x",
bottomRow: 20,
topRow: 10,
type: "CONTAINER_WIDGET",
children: ["m"],
},
m: {
...DUMMY_WIDGET,
widgetId: "m",
parentId: "x",
children: ["n", "o"],
type: "CANVAS_WIDGET",
},
n: {
...DUMMY_WIDGET,
bottomRow: 6,
},
o: {
...DUMMY_WIDGET,
bottomRow: 5,
},
};
const result = getCanvasBottomRow("m", canvasWidgets);
expect(result).toBe(100);
});
it("Computes all the effected canvases for the changed widgets", () => {
const canvasWidgets = {
x: {
...DUMMY_WIDGET,
widgetId: "x",
bottomRow: 20,
topRow: 10,
type: "CONTAINER_WIDGET",
children: ["m"],
},
m: {
...DUMMY_WIDGET,
widgetId: "m",
parentId: "x",
children: ["n", "o", "p"],
type: "CANVAS_WIDGET",
},
n: {
...DUMMY_WIDGET,
bottomRow: 6,
},
o: {
...DUMMY_WIDGET,
bottomRow: 5,
},
p: {
...DUMMY_WIDGET,
widgetId: "p",
bottomRow: 20,
topRow: 10,
type: "CONTAINER_WIDGET",
children: ["q"],
parentId: "m",
},
q: {
...DUMMY_WIDGET,
widgetId: "q",
parentId: "p",
children: [],
type: "CANVAS_WIDGET",
},
};
// Since the container p has changed, it will effect the parent m and the child q
const result = getCanvasWidgetHeightsToUpdate(["p"], canvasWidgets);
expect(result).toStrictEqual({ q: 100, m: 200 });
});
|
1,353 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/WorkerUtil.test.ts | import { GracefulWorkerService } from "./WorkerUtil";
import { runSaga } from "redux-saga";
const MessageType = "message";
interface extraWorkerProperties {
callback: CallableFunction;
noop: CallableFunction;
delayMilliSeconds: number;
running: boolean;
}
type WorkerClass = Worker & extraWorkerProperties;
class MockWorkerClass implements WorkerClass {
// Implement interface
onmessage: any;
onmessageerror: any;
dispatchEvent: any;
onerror: any;
callback: CallableFunction;
noop: CallableFunction;
messages: Array<any>;
delayMilliSeconds: number;
instance: WorkerClass | undefined;
responses: Set<number>;
running: boolean;
resetInstance() {
this.instance = undefined;
}
constructor() {
/* eslint-disable @typescript-eslint/no-empty-function */
this.noop = () => {};
this.callback = this.noop;
this.messages = [];
this.delayMilliSeconds = 0;
this.responses = new Set<number>();
this.instance = this;
this.running = true;
}
addEventListener(msgType: string, callback: any) {
expect(msgType).toEqual(MessageType);
this.callback = callback;
}
removeEventListener(msgType: string, callback: any) {
expect(msgType).toEqual(MessageType);
expect(callback).toEqual(this.callback);
this.callback = this.noop;
}
postMessage(message: any) {
expect(this.running).toEqual(true);
expect(this.callback).not.toEqual(this.noop);
this.messages.push(message);
const counter = setTimeout(() => {
const response = {
messageId: message.messageId,
messageType: "RESPONSE",
body: { data: message.body.data },
};
this.sendEvent({ data: response });
this.responses.delete(counter);
}, this.delayMilliSeconds);
this.responses.add(counter);
}
sendEvent(ev: any) {
expect(this.running).toEqual(true);
expect(this.callback).not.toEqual(this.noop);
this.callback(ev);
}
terminate() {
this.running = false;
expect(this.callback).toEqual(this.noop);
this.responses.forEach((counter) => {
clearTimeout(counter);
});
this.responses = new Set<number>();
}
}
describe("GracefulWorkerService", () => {
test("Worker should start", async () => {
const MockWorker = new MockWorkerClass();
const w = new GracefulWorkerService(MockWorker);
// wait for worker to start
await runSaga({}, w.start);
if (MockWorker.instance === undefined) {
expect(MockWorker.instance).toBeDefined();
return;
}
expect(MockWorker.instance.callback).not.toEqual(MockWorker.instance.noop);
});
test("Independent requests should respond independently irrespective of order", async () => {
const MockWorker = new MockWorkerClass();
const w = new GracefulWorkerService(MockWorker);
await runSaga({}, w.start);
const message1 = { tree: "hello" };
const message2 = { tree: "world" };
// Send requests in order
const result1 = await runSaga({}, w.request, "test", message1);
const result2 = await runSaga({}, w.request, "test", message2);
// wait for responses out of order
const resp2 = await result2.toPromise();
const resp1 = await result1.toPromise();
expect(resp1).toEqual(message1);
expect(resp2).toEqual(message2);
});
test("Request should wait for ready", async () => {
const MockWorker = new MockWorkerClass();
const w = new GracefulWorkerService(MockWorker);
const message = { hello: "world" };
// Send a request before starting
const result = await runSaga({}, w.request, "test", message);
// trigger start after the worker is already waiting
runSaga({}, w.start);
const resp = await result.toPromise();
expect(resp).toEqual(message);
});
test("Worker should wait to drain in-flight requests before shutdown", async () => {
const MockWorker = new MockWorkerClass();
const w = new GracefulWorkerService(MockWorker);
const message = { hello: "world" };
await runSaga({}, w.start);
const start = performance.now();
// Need this to work with eslint
if (MockWorker.instance === undefined) {
expect(MockWorker.instance).toBeDefined();
return;
}
// Typical run takes less than 10ms
// we add a delay of 100ms to check if shutdown waited for pending requests.
MockWorker.instance.delayMilliSeconds = 100;
const result = await runSaga({}, w.request, "test", message);
// wait for shutdown
await (await runSaga({}, w.shutdown)).toPromise();
// Shutdown shouldn't happen till we get a response
expect(performance.now() - start).toBeGreaterThanOrEqual(
MockWorker.instance.delayMilliSeconds,
);
const resp = await result.toPromise();
expect(resp).toEqual(message);
});
test("Worker restart should work", async () => {
const MockWorker = new MockWorkerClass();
let w = new GracefulWorkerService(MockWorker);
const message1 = { tree: "hello" };
await runSaga({}, w.start);
// Need this to work with eslint
if (MockWorker.instance === undefined) {
expect(MockWorker.instance).toBeDefined();
return;
}
// Keep a reference to the old instance to check later
const oldInstance = MockWorker.instance;
const result1 = await runSaga({}, w.request, "test", message1);
expect(await result1.toPromise()).toEqual(message1);
// stop the worker
await (await runSaga({}, w.shutdown)).toPromise();
// Should have called terminate on worker
expect(oldInstance.running).toEqual(false);
// Send a message to the new worker before starting it
const newMockWorker = new MockWorkerClass();
w = new GracefulWorkerService(newMockWorker);
const message2 = { tree: "world" };
const result2 = await runSaga({}, w.request, "test", message2);
await runSaga({}, w.start);
// We should have a new instance of the worker
expect(newMockWorker.instance).not.toEqual(oldInstance);
// The new worker should get the correct message
expect(await result2.toPromise()).toEqual(message2);
});
test("Cancelling saga before starting up should not crash", async () => {
const MockWorker = new MockWorkerClass();
const w = new GracefulWorkerService(MockWorker);
const message = { tree: "hello" };
const task = await runSaga({}, w.request, "cancel_test", message);
// Start shutting down
const shutdown = await runSaga({}, w.shutdown);
task.cancel();
// wait for shutdown
await shutdown.toPromise();
expect(await task.toPromise()).not.toEqual(message);
});
test("Cancelled saga should clean up", async () => {
const MockWorker = new MockWorkerClass();
const w = new GracefulWorkerService(MockWorker);
const message = { tree: "hello" };
await runSaga({}, w.start);
// Need this to work with eslint
if (MockWorker.instance === undefined) {
expect(MockWorker.instance).toBeDefined();
return;
}
// Make sure we get a chance to cancel before the worker can respond
MockWorker.instance.delayMilliSeconds = 100;
const task = await runSaga({}, w.request, "cancel_test", message);
// Start shutting down
const shutdown = await runSaga({}, w.shutdown);
task.cancel();
// wait for shutdown
await shutdown.toPromise();
expect(await task.toPromise()).not.toEqual(message);
});
});
|
1,356 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/boxHelpers.test.ts | import type { Rect } from "./boxHelpers";
import { areIntersecting } from "./boxHelpers";
describe("boxHelpers", () => {
describe("areIntersecting", () => {
it("should return true when rect 1 and rect 2 are intersecting", () => {
const rect1: Rect = {
top: 0,
bottom: 2,
left: 0,
right: 2,
};
const rect2: Rect = {
top: 0,
bottom: 3,
left: 1,
right: 3,
};
const isIntersecting = areIntersecting(rect1, rect2);
expect(isIntersecting).toBe(true);
});
it("should return false when rect 1 and rect 2 are not intersecting", () => {
const rect1: Rect = {
top: 0,
bottom: 2,
left: 0,
right: 2,
};
const rect2: Rect = {
top: 3,
bottom: 6,
left: 3,
right: 6,
};
const isIntersecting = areIntersecting(rect1, rect2);
expect(isIntersecting).toBe(false);
});
});
});
|
1,358 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/canvasStructureHelpers.test.ts | import type { CanvasStructure } from "reducers/uiReducers/pageCanvasStructureReducer";
import { compareAndGenerateImmutableCanvasStructure } from "./canvasStructureHelpers";
const canvasStructure: CanvasStructure = {
widgetId: "x",
widgetName: "x",
type: "CONTAINER_WIDGET",
children: [
{
widgetId: "y",
widgetName: "y",
type: "CONTAINER_WIDGET",
children: [
{
widgetId: "z",
widgetName: "z",
type: "CONTAINER_WIDGET",
},
],
},
{
widgetId: "m",
widgetName: "m",
type: "CONTAINER_WIDGET",
children: [
{
widgetId: "n",
widgetName: "n",
type: "CONTAINER_WIDGET",
children: [
{
widgetId: "o",
widgetName: "o",
type: "CONTAINER_WIDGET",
},
],
},
],
},
],
};
const simpleDSL: any = {
widgetId: "x",
widgetName: "x",
type: "CONTAINER_WIDGET",
children: [
{
widgetId: "y",
widgetName: "y",
type: "CONTAINER_WIDGET",
children: [
{
widgetId: "z",
widgetName: "z",
type: "CONTAINER_WIDGET",
},
],
},
{
widgetId: "m",
widgetName: "m",
type: "CONTAINER_WIDGET",
children: [
{
widgetId: "n",
widgetName: "n",
type: "CONTAINER_WIDGET",
children: [
{
widgetId: "o",
widgetName: "o",
type: "CONTAINER_WIDGET",
},
],
},
],
},
],
};
describe("Immutable Canvas structures", () => {
it("generates the same object if it is run with the same dsl", () => {
const nextState = compareAndGenerateImmutableCanvasStructure(
canvasStructure,
simpleDSL,
);
expect(nextState).toBe(canvasStructure);
});
it("updates the diff appropriately", () => {
const dsl: any = {
widgetId: "x",
widgetName: "x",
children: [
{
widgetId: "y",
widgetName: "y",
children: [
{
widgetId: "z",
widgetName: "z",
},
],
},
{
widgetId: "m",
widgetName: "newName",
children: [
{
widgetId: "n",
widgetName: "n",
children: [
{
widgetId: "o",
widgetName: "o",
},
],
},
],
},
],
};
const expectedCanvasStructure = {
widgetId: "x",
widgetName: "x",
children: [
{
widgetId: "y",
widgetName: "y",
children: [
{
widgetId: "z",
widgetName: "z",
},
],
},
{
widgetId: "m",
widgetName: "newName",
children: [
{
widgetId: "n",
widgetName: "n",
children: [
{
widgetId: "o",
widgetName: "o",
},
],
},
],
},
],
};
const nextState = compareAndGenerateImmutableCanvasStructure(
canvasStructure,
dsl,
);
expect(nextState).not.toBe(expectedCanvasStructure);
expect(JSON.stringify(nextState)).toBe(
JSON.stringify(expectedCanvasStructure),
);
});
});
|
1,364 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/formhelpers.test.ts | import { isEmail } from "./formhelpers";
describe("isEmail test", () => {
it("Check whether the valid emails are recognized as valid", () => {
const validEmails = [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
];
validEmails.forEach((validEmail) => {
expect(isEmail(validEmail)).toBeTruthy();
});
});
it("Check whether the invalid emails are recognized as invalid", () => {
const invalidEmails = [
"appsmith",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"appsmith()*@gmail.com",
"appsmith@%*.com",
"[email protected]",
"[email protected]",
"appsmith@[email protected]",
"[email protected]",
];
invalidEmails.forEach((invalidEmail) => {
expect(isEmail(invalidEmail)).toBeFalsy();
});
});
});
|
1,370 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/helpers.test.ts | import { RenderModes } from "constants/WidgetConstants";
import { ValidationTypes } from "constants/WidgetValidation";
import { EvaluationSubstitutionType } from "entities/DataTree/dataTreeFactory";
import type { CanvasWidgetsReduxState } from "../reducers/entityReducers/canvasWidgetsReducer";
import { AutocompleteDataType } from "./autocomplete/AutocompleteDataType";
import {
flattenObject,
getLocale,
getSubstringBetweenTwoWords,
captureInvalidDynamicBindingPath,
mergeWidgetConfig,
extractColorsFromString,
isNameValid,
pushToArray,
concatWithArray,
} from "./helpers";
import WidgetFactory from "../WidgetProvider/factory";
import * as Sentry from "@sentry/react";
import { Colors } from "constants/Colors";
describe("flattenObject test", () => {
it("Check if non nested object is returned correctly", () => {
const testObject = {
isVisible: true,
isDisabled: false,
tableData: false,
};
expect(flattenObject(testObject)).toStrictEqual(testObject);
});
it("Check if nested objects are returned correctly", () => {
const tests = [
{
input: {
isVisible: true,
isDisabled: false,
tableData: false,
settings: {
color: [
{
headers: {
left: true,
},
},
],
},
},
output: {
isVisible: true,
isDisabled: false,
tableData: false,
"settings.color[0].headers.left": true,
},
},
{
input: {
isVisible: true,
isDisabled: false,
tableData: false,
settings: {
color: true,
},
},
output: {
isVisible: true,
isDisabled: false,
tableData: false,
"settings.color": true,
},
},
{
input: {
numbers: [1, 2, 3],
color: { header: "red" },
},
output: {
"numbers[0]": 1,
"numbers[1]": 2,
"numbers[2]": 3,
"color.header": "red",
},
},
{
input: {
name: null,
color: { header: {} },
users: {
id: undefined,
},
},
output: {
"color.header": {},
name: null,
"users.id": undefined,
},
},
];
tests.map((test) =>
expect(flattenObject(test.input)).toStrictEqual(test.output),
);
});
});
describe("#getSubstringBetweenTwoWords", () => {
it("returns substring between 2 words from a string", () => {
const input: [string, string, string][] = [
["aaa.bbb.ccc", "aaa.", ".ccc"],
["aaa.bbb.bbb.ccc", "aaa.", ".ccc"],
["aaa.aaa.aaa.aaa", "aaa", "aaa"],
["aaa...aaa.aaa.aaa", "aaa", "aaa"],
["aaa..bbb", "aaa.", ".bbb"],
["aaa.bbb", "aaa.", ".bbb"],
["aaabbb", "aaab", "abbb"],
];
const output = ["bbb", "bbb.bbb", ".aaa.aaa.", "...aaa.aaa.", "", "", ""];
input.forEach((inp, index) => {
expect(getSubstringBetweenTwoWords(...inp)).toBe(output[index]);
});
});
});
describe("#mergeWidgetConfig", () => {
it("should merge the widget configs", () => {
const base = [
{
sectionName: "General",
children: [
{
propertyName: "someWidgetConfig",
},
],
},
{
sectionName: "icon",
children: [
{
propertyName: "someWidgetIconConfig",
},
],
},
];
const extended = [
{
sectionName: "General",
children: [
{
propertyName: "someOtherWidgetConfig",
},
],
},
{
sectionName: "style",
children: [
{
propertyName: "someWidgetStyleConfig",
},
],
},
];
const expected = [
{
sectionName: "General",
children: [
{
propertyName: "someOtherWidgetConfig",
},
{
propertyName: "someWidgetConfig",
},
],
},
{
sectionName: "style",
children: [
{
propertyName: "someWidgetStyleConfig",
},
],
},
{
sectionName: "icon",
children: [
{
propertyName: "someWidgetIconConfig",
},
],
},
];
expect(mergeWidgetConfig(extended, base)).toEqual(expected);
});
});
describe("#getLocale", () => {
it("should test that getLocale is returning navigator.languages[0]", () => {
expect(getLocale()).toBe(navigator.languages[0]);
});
});
describe("#captureInvalidDynamicBindingPath", () => {
it("DSL should not be altered", () => {
const baseDSL = {
widgetName: "RadioGroup1",
dynamicPropertyPathList: [],
displayName: "Radio Group",
iconSVG: "/static/media/icon.ba2b2ee0.svg",
topRow: 57,
bottomRow: 65,
parentRowSpace: 10,
type: "RADIO_GROUP_WIDGET",
hideCard: false,
defaultOptionValue: "{{1}}",
animateLoading: true,
parentColumnSpace: 33.375,
dynamicTriggerPathList: [],
leftColumn: 42,
dynamicBindingPathList: [
{
key: "defaultOptionValue",
},
{
key: "options",
},
],
options:
'[\n {\n "label": "Yes",\n "value": {{1 > 0 ? 1 : 0}}\n },\n {\n "label": "No",\n "value": 2\n }\n]',
isDisabled: false,
key: "opzs6suotf",
isRequired: false,
rightColumn: 62,
widgetId: "s195otz2jm",
isVisible: true,
label: "",
version: 1,
parentId: "0",
renderMode: RenderModes.CANVAS,
isLoading: false,
};
const getPropertyConfig = jest.spyOn(
WidgetFactory,
"getWidgetPropertyPaneConfig",
);
getPropertyConfig.mockReturnValueOnce([
{
sectionName: "General",
children: [
{
helpText: "Displays a list of unique options",
propertyName: "options",
label: "Options",
controlType: "OPTION_INPUT",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.FUNCTION,
params: {
expected: {
type: 'Array<{ "label": "string", "value": "string" | number}>',
example: '[{"label": "abc", "value": "abc" | 1}]',
autocompleteDataType: AutocompleteDataType.STRING,
},
fnString:
'function optionsCustomValidation(options, props, _) {\n var validationUtil = (options, _) => {\n var _isValid = true;\n var message = "";\n var valueType = "";\n var uniqueLabels = {};\n\n for (var i = 0; i < options.length; i++) {\n var _options$i = options[i],\n label = _options$i.label,\n value = _options$i.value;\n\n if (!valueType) {\n valueType = typeof value;\n } //Checks the uniqueness all the values in the options\n\n\n if (!uniqueLabels.hasOwnProperty(value)) {\n uniqueLabels[value] = "";\n } else {\n _isValid = false;\n message = "path:value must be unique. Duplicate values found";\n break;\n } //Check if the required field "label" is present:\n\n\n if (!label) {\n _isValid = false;\n message = "Invalid entry at index: " + i + ". Missing required key: label";\n break;\n } //Validation checks for the the label.\n\n\n if (_.isNil(label) || label === "" || typeof label !== "string" && typeof label !== "number") {\n _isValid = false;\n message = "Invalid entry at index: " + i + ". Value of key: label is invalid: This value does not evaluate to type string";\n break;\n } //Check if all the data types for the value prop is the same.\n\n\n if (typeof value !== valueType) {\n _isValid = false;\n message = "All value properties in options must have the same type";\n break;\n } //Check if the each object has value property.\n\n\n if (_.isNil(value)) {\n _isValid = false;\n message = \'This value does not evaluate to type Array<{ "label": "string", "value": "string" | number }>\';\n break;\n }\n }\n\n return {\n isValid: _isValid,\n parsed: _isValid ? options : [],\n messages: [message]\n };\n };\n\n var invalidResponse = {\n isValid: false,\n parsed: [],\n messages: [\'This value does not evaluate to type Array<{ "label": "string", "value": "string" | number }>\']\n };\n\n try {\n if (_.isString(options)) {\n options = JSON.parse(options);\n }\n\n if (Array.isArray(options)) {\n return validationUtil(options, _);\n } else {\n return invalidResponse;\n }\n } catch (e) {\n return invalidResponse;\n }\n}',
},
},
evaluationSubstitutionType:
EvaluationSubstitutionType.SMART_SUBSTITUTE,
id: "6su4u0bwoe",
},
{
helpText: "Sets a default selected option",
propertyName: "defaultOptionValue",
label: "Default selected value",
// placeholderText: "Y",
controlType: "INPUT_TEXT",
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.FUNCTION,
params: {
expected: {
type: "string |\nnumber (only works in mustache syntax)",
example: "abc | {{1}}",
autocompleteDataType: AutocompleteDataType.STRING,
},
fnString:
'function defaultOptionValidation(value, props, _) {\n //Checks if the value is not of object type in {{}}\n if (_.isObject(value)) {\n return {\n isValid: false,\n parsed: JSON.stringify(value, null, 2),\n messages: ["This value does not evaluate to type: string or number"]\n };\n } //Checks if the value is not of boolean type in {{}}\n\n\n if (_.isBoolean(value)) {\n return {\n isValid: false,\n parsed: value,\n messages: ["This value does not evaluate to type: string or number"]\n };\n }\n\n return {\n isValid: true,\n parsed: value\n };\n}',
},
},
id: "8wpzo6szbl",
},
{
propertyName: "isRequired",
label: "Required",
helpText: "Makes input to the widget mandatory",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.BOOLEAN,
},
id: "60kc73ivwp",
},
{
helpText: "Controls the visibility of the widget",
propertyName: "isVisible",
label: "Visible",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.BOOLEAN,
},
id: "w4591dtf5l",
},
{
propertyName: "isDisabled",
label: "Disabled",
helpText: "Disables input to this widget",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.BOOLEAN,
},
id: "6p7181ccec",
},
{
propertyName: "animateLoading",
label: "Animate loading",
controlType: "SWITCH",
helpText: "Controls the loading of the widget",
// defaultValue: true,
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.BOOLEAN,
},
id: "y2gw796t2z",
},
],
id: "jfh7ud39r4",
},
{
sectionName: "Events",
children: [
{
helpText: "when a user changes the selected option",
propertyName: "onSelectionChange",
label: "onSelectionChange",
controlType: "ACTION_SELECTOR",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: true,
id: "wqgudnqu5n",
},
],
id: "b2k5a0t632",
},
]);
const newDsl = captureInvalidDynamicBindingPath(baseDSL);
expect(baseDSL).toEqual(newDsl);
});
it("Checks if dynamicBindingPathList contains a property path that doesn't have a binding", () => {
const baseDSL = {
widgetName: "RadioGroup1",
dynamicPropertyPathList: [],
displayName: "Radio Group",
iconSVG: "/static/media/icon.ba2b2ee0.svg",
topRow: 57,
bottomRow: 65,
parentRowSpace: 10,
type: "RADIO_GROUP_WIDGET",
hideCard: false,
defaultOptionValue: "{{1}}",
animateLoading: true,
parentColumnSpace: 33.375,
dynamicTriggerPathList: [],
leftColumn: 42,
dynamicBindingPathList: [
{
key: "defaultOptionValue",
},
{
key: "options",
},
],
options: [],
isDisabled: false,
key: "opzs6suotf",
isRequired: false,
rightColumn: 62,
widgetId: "s195otz2jm",
isVisible: true,
label: "",
version: 1,
parentId: "0",
renderMode: RenderModes.CANVAS,
isLoading: false,
};
const getPropertyConfig = jest.spyOn(
WidgetFactory,
"getWidgetPropertyPaneConfig",
);
getPropertyConfig.mockReturnValueOnce([
{
sectionName: "General",
children: [
{
helpText: "Displays a list of unique options",
propertyName: "options",
label: "Options",
controlType: "OPTION_INPUT",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.FUNCTION,
params: {
expected: {
type: 'Array<{ "label": "string", "value": "string" | number}>',
example: '[{"label": "abc", "value": "abc" | 1}]',
autocompleteDataType: AutocompleteDataType.STRING,
},
fnString:
'function optionsCustomValidation(options, props, _) {\n var validationUtil = (options, _) => {\n var _isValid = true;\n var message = "";\n var valueType = "";\n var uniqueLabels = {};\n\n for (var i = 0; i < options.length; i++) {\n var _options$i = options[i],\n label = _options$i.label,\n value = _options$i.value;\n\n if (!valueType) {\n valueType = typeof value;\n } //Checks the uniqueness all the values in the options\n\n\n if (!uniqueLabels.hasOwnProperty(value)) {\n uniqueLabels[value] = "";\n } else {\n _isValid = false;\n message = "path:value must be unique. Duplicate values found";\n break;\n } //Check if the required field "label" is present:\n\n\n if (!label) {\n _isValid = false;\n message = "Invalid entry at index: " + i + ". Missing required key: label";\n break;\n } //Validation checks for the the label.\n\n\n if (_.isNil(label) || label === "" || typeof label !== "string" && typeof label !== "number") {\n _isValid = false;\n message = "Invalid entry at index: " + i + ". Value of key: label is invalid: This value does not evaluate to type string";\n break;\n } //Check if all the data types for the value prop is the same.\n\n\n if (typeof value !== valueType) {\n _isValid = false;\n message = "All value properties in options must have the same type";\n break;\n } //Check if the each object has value property.\n\n\n if (_.isNil(value)) {\n _isValid = false;\n message = \'This value does not evaluate to type Array<{ "label": "string", "value": "string" | number }>\';\n break;\n }\n }\n\n return {\n isValid: _isValid,\n parsed: _isValid ? options : [],\n messages: [message]\n };\n };\n\n var invalidResponse = {\n isValid: false,\n parsed: [],\n messages: [\'This value does not evaluate to type Array<{ "label": "string", "value": "string" | number }>\']\n };\n\n try {\n if (_.isString(options)) {\n options = JSON.parse(options);\n }\n\n if (Array.isArray(options)) {\n return validationUtil(options, _);\n } else {\n return invalidResponse;\n }\n } catch (e) {\n return invalidResponse;\n }\n}',
},
},
evaluationSubstitutionType:
EvaluationSubstitutionType.SMART_SUBSTITUTE,
id: "6su4u0bwoe",
},
{
helpText: "Sets a default selected option",
propertyName: "defaultOptionValue",
label: "Default selected value",
// placeholderText: "Y",
controlType: "INPUT_TEXT",
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.FUNCTION,
params: {
expected: {
type: "string |\nnumber (only works in mustache syntax)",
example: "abc | {{1}}",
autocompleteDataType: AutocompleteDataType.STRING,
},
fnString:
'function defaultOptionValidation(value, props, _) {\n //Checks if the value is not of object type in {{}}\n if (_.isObject(value)) {\n return {\n isValid: false,\n parsed: JSON.stringify(value, null, 2),\n messages: ["This value does not evaluate to type: string or number"]\n };\n } //Checks if the value is not of boolean type in {{}}\n\n\n if (_.isBoolean(value)) {\n return {\n isValid: false,\n parsed: value,\n messages: ["This value does not evaluate to type: string or number"]\n };\n }\n\n return {\n isValid: true,\n parsed: value\n };\n}',
},
},
id: "8wpzo6szbl",
},
{
propertyName: "isRequired",
label: "Required",
helpText: "Makes input to the widget mandatory",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.BOOLEAN,
},
id: "60kc73ivwp",
},
{
helpText: "Controls the visibility of the widget",
propertyName: "isVisible",
label: "Visible",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.BOOLEAN,
},
id: "w4591dtf5l",
},
{
propertyName: "isDisabled",
label: "Disabled",
helpText: "Disables input to this widget",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.BOOLEAN,
},
id: "6p7181ccec",
},
{
propertyName: "animateLoading",
label: "Animate loading",
controlType: "SWITCH",
helpText: "Controls the loading of the widget",
// defaultValue: true,
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.BOOLEAN,
},
id: "y2gw796t2z",
},
],
id: "jfh7ud39r4",
},
{
sectionName: "Events",
children: [
{
helpText: "when a user changes the selected option",
propertyName: "onSelectionChange",
label: "onSelectionChange",
controlType: "ACTION_SELECTOR",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: true,
id: "wqgudnqu5n",
},
],
id: "b2k5a0t632",
},
]);
const sentrySpy = jest.spyOn(Sentry, "captureException");
captureInvalidDynamicBindingPath(baseDSL);
expect(sentrySpy).toHaveBeenCalledWith(
new Error(
`INVALID_DynamicPathBinding_CLIENT_ERROR: Invalid dynamic path binding list: RadioGroup1.options`,
),
);
});
});
describe("#extractColorsFromString", () => {
it("Check if the extractColorsFromString returns rgb, rgb, hex color strings", () => {
const widgets = {
0: { color: `${Colors.GREEN}` },
1: { color: "rgb(0,0,0)" },
2: { color: `${Colors.BOX_SHADOW_DEFAULT_VARIANT1}` },
3: { color: `LightGoldenrodYellow` },
4: { color: `lch(54.292% 106.839 40.853)` },
} as unknown as CanvasWidgetsReduxState;
//Check Hex value
expect(extractColorsFromString(widgets)[0]).toEqual("#03B365");
//Check rgb
expect(extractColorsFromString(widgets)[1]).toEqual("rgb(0,0,0)");
//Check rgba value
expect(extractColorsFromString(widgets)[2]).toEqual("rgba(0, 0, 0, 0.25)");
//Check name value
expect(extractColorsFromString(widgets)[3]).toEqual("LightGoldenrodYellow");
//Check lch value
expect(extractColorsFromString(widgets)[4]).toEqual(
"lch(54.292% 106.839 40.853)",
);
});
});
describe("isNameValid()", () => {
it("works properly", () => {
const invalidEntityNames = [
"console",
"Promise",
"appsmith",
"Math",
"yield",
"Boolean",
"ReferenceError",
"clearTimeout",
"parseInt",
"eval",
"performance",
];
// Some window object methods and properties names should be valid entity names since evaluation is done
// in the worker thread, and some of the window methods and properties are not available there.
const validEntityNames = ["history", "parent", "screen"];
for (const invalidName of invalidEntityNames) {
expect(isNameValid(invalidName, {})).toBe(false);
}
for (const validName of validEntityNames) {
expect(isNameValid(validName, {})).toBe(true);
}
});
});
describe("pushToArray", () => {
it("adds to an undefined array", () => {
const item = "something";
const expected = ["something"];
const result = pushToArray(item);
expect(result).toStrictEqual(expected);
});
it("adds to an existing array", () => {
const item = "something";
const arr1 = ["another"];
const expected = ["another", "something"];
const result = pushToArray(item, arr1);
expect(result).toStrictEqual(expected);
});
it("adds to an existing array and make unique", () => {
const item = "something";
const arr1 = ["another", "another"];
const expected = ["another", "something"];
const result = pushToArray(item, arr1, true);
expect(result).toStrictEqual(expected);
});
});
describe("concatWithArray", () => {
it("adds to an undefined array", () => {
const items = ["something"];
const expected = ["something"];
const result = concatWithArray(items);
expect(result).toStrictEqual(expected);
});
it("adds to an existing array", () => {
const items = ["something"];
const arr1 = ["another"];
const expected = ["another", "something"];
const result = concatWithArray(items, arr1);
expect(result).toStrictEqual(expected);
});
it("adds to an existing array and make unique", () => {
const items = ["something"];
const arr1 = ["another", "another"];
const expected = ["another", "something"];
const result = concatWithArray(items, arr1, true);
expect(result).toStrictEqual(expected);
});
});
|
1,374 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/klona.test.ts | import equal from "fast-deep-equal/es6";
import { klona } from "klona/full";
import moment from "moment";
describe("Klona clone test", () => {
it("Strings, Booleans, numbers, null & undefined values", () => {
const input: {
meta: {
stringLiteral: string;
string: string;
boolean: boolean;
number: number;
nan: number;
null: null | string;
undefined: undefined | number;
};
} = {
meta: {
stringLiteral: "abc",
string: String("ABC"),
boolean: true,
number: Number(45),
nan: NaN,
null: null,
undefined: undefined,
},
};
const expected: Record<string, unknown> = {
meta: {
stringLiteral: "abc",
string: String("ABC"),
boolean: true,
number: Number(45),
nan: NaN,
null: null,
undefined: undefined,
},
};
const result = klona(input);
// mutate
input.meta.string = "hello1";
input.meta.boolean = false;
input.meta.number = Number(89);
input.meta.null = "efewf";
input.meta.undefined = NaN;
expect(equal(expected, result)).toEqual(true);
});
it("Dates and regex values", () => {
const currentDate = new Date();
const currentMoment = moment();
const input = {
meta: {
date: currentDate,
moment: currentMoment,
regex: /^abc$/g,
regexExp: new RegExp(/^abc$/),
},
};
const expected = {
meta: {
date: currentDate,
moment: currentMoment,
regex: /^abc$/g,
regexExp: new RegExp(/^abc$/),
},
};
const result = klona(input);
// mutate
input.meta.date = new Date(327392879);
input.meta.moment = moment();
input.meta.regex = /^def$/g;
input.meta.regexExp = new RegExp(/^def$/);
expect(equal(expected, result)).toEqual(true);
});
it("Objects and Arrays values", () => {
function getNestedArray() {
return ["foo", [1, 2, ["hello", "world"], 3], "bar", "baz", {}];
}
function getNestedObject() {
return {
Input: { text: "abc" },
};
}
const objectWithMethod = Object.create({
method() {
return "hello";
},
});
const input = {
meta: {
nestedArray: [...getNestedArray()],
objectWithMethod,
nestedObject: { ...getNestedObject() },
},
};
const expected = {
meta: {
nestedArray: [...getNestedArray()],
objectWithMethod,
nestedObject: { ...getNestedObject() },
},
};
const result = klona(input);
// mutate
input.meta.nestedArray[0] = "abc";
input.meta.nestedArray[1] = { a: "bc" };
input.meta.nestedObject.Input.text = "hello";
expect(
equal(expected.meta.nestedArray[0], result.meta.nestedArray[0]),
).toEqual(true);
expect(
equal(expected.meta.nestedArray[1], result.meta.nestedArray[1]),
).toEqual(true);
expect(
equal(
expected.meta.objectWithMethod.method(),
result.meta.objectWithMethod.method(),
),
).toEqual(true);
expect(
equal(
expected.meta.nestedObject.Input.text,
result.meta.nestedObject.Input.text,
),
).toEqual(true);
});
it("Functions, Pollutions and Classes values", () => {
const fn = async () => {
return "hello";
};
const input = {
fn,
};
const expected = {
fn,
};
const result = klona(input);
expect(expected.fn === result.fn).toEqual(true);
});
it("Maps and Sets values", () => {
const map = new Map();
const set = new Set();
map.set("abc", "value");
set.add("1");
set.add("2");
const input = { map, set };
const result = klona(input);
// changes after clone
input.map.set("1", "value1");
input.map.set("2", "value1");
expect(result.map.get("abc")).toStrictEqual("value");
expect(result.map.get("1")).toStrictEqual(undefined);
expect(result.map.get("2")).toStrictEqual(undefined);
// add new value and verify it is not present in cloned set
set.add("3");
expect(result.set.has("3")).toStrictEqual(false);
// delete a value and verify it is still present in cloned set
set.delete("2");
expect(result.set.has("2")).toStrictEqual(true);
});
it("TypedArrays values", () => {
const int16Array = new Int16Array([42]);
const buf = new ArrayBuffer(8);
const int32Array = new Int32Array(buf);
const resultInt16Array = klona(int16Array);
const resultInt32Array = klona(int32Array);
// add value at 1st index and verify cloned value doesn't contain it.
resultInt16Array[1] = 42;
expect(int16Array[1]).toStrictEqual(undefined);
expect(int16Array[0]).toStrictEqual(42);
expect(resultInt32Array[1]).toStrictEqual(0);
});
it("Symbols and Descriptors values", () => {
// Symbol
const key = Symbol("key");
const input = { foo: 123, [key]: 456 };
const result = klona(input);
expect(result[key]).toStrictEqual(456);
// Descriptor
const inputDesc = { foo: 123 };
Object.defineProperty(inputDesc, "bar", {
enumerable: false,
value: [1, 2, 3],
});
const outputDesc = klona(inputDesc);
expect(Object.getOwnPropertyDescriptor(outputDesc, "bar")).toStrictEqual({
enumerable: false,
configurable: false,
writable: false,
value: [1, 2, 3],
});
});
});
|
1,377 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/localStorage.test.ts | import myLocalStorage, { LocalStorage } from "utils/localStorage";
describe("local storage", () => {
afterEach(() => {
jest.clearAllMocks();
});
it("calls getItem", () => {
jest.spyOn(window.localStorage.__proto__, "getItem");
window.localStorage.__proto__.getItem = jest.fn();
myLocalStorage.getItem("myTestKey");
expect(localStorage.getItem).toBeCalledWith("myTestKey");
});
it("calls setItem", () => {
jest.spyOn(window.localStorage.__proto__, "setItem");
window.localStorage.__proto__.setItem = jest.fn();
myLocalStorage.setItem("myTestKey", "testValue");
expect(localStorage.setItem).toBeCalledWith("myTestKey", "testValue");
});
it("calls removeItem", () => {
jest.spyOn(window.localStorage.__proto__, "removeItem");
window.localStorage.__proto__.removeItem = jest.fn();
myLocalStorage.removeItem("myTestKey");
expect(localStorage.removeItem).toBeCalledWith("myTestKey");
});
it("calls clear", () => {
jest.spyOn(window.localStorage.__proto__, "clear");
window.localStorage.__proto__.clear = jest.fn();
myLocalStorage.clear();
expect(localStorage.clear).toBeCalled();
});
it("shouldn't call getItem if localStorage is not supported", () => {
window.localStorage.__proto__.setItem = jest.fn(() => {
// this makes sure isSupported is set as false within the util
throw new Error();
});
jest.spyOn(window.localStorage.__proto__, "getItem");
const localStorageInstance = new LocalStorage();
localStorageInstance.getItem("myTestKey");
expect(localStorage.getItem).toHaveBeenCalledTimes(0);
});
});
|
1,386 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/testPropertyPaneConfig.test.ts | import type {
PropertyPaneConfig,
PropertyPaneControlConfig,
PropertyPaneSectionConfig,
ValidationConfig,
} from "constants/PropertyControlConstants";
import { ValidationTypes } from "constants/WidgetValidation";
import { isFunction } from "lodash";
import widgets from "widgets";
import WidgetFactory from "WidgetProvider/factory";
import { registerWidgets } from "WidgetProvider/factory/registrationHelper";
function validatePropertyPaneConfig(
config: PropertyPaneConfig[],
isWidgetHidden: boolean,
) {
for (const sectionOrControlConfig of config) {
const sectionConfig = sectionOrControlConfig as PropertyPaneSectionConfig;
if (sectionConfig.sectionName && isFunction(sectionConfig.sectionName)) {
return ` SectionName should be a string and not a function. Search won't work for functions at the moment`;
}
if (sectionOrControlConfig.children) {
for (const propertyControlConfig of sectionOrControlConfig.children) {
const propertyControlValidation = validatePropertyControl(
propertyControlConfig,
isWidgetHidden,
);
if (propertyControlValidation !== true)
return propertyControlValidation;
}
}
}
return true;
}
function validatePropertyControl(
config: PropertyPaneConfig,
isWidgetHidden: boolean,
): boolean | string {
const _config = config as PropertyPaneControlConfig;
const controls = ["INPUT_TEXT"];
if (_config.label && isFunction(_config.label)) {
return `${_config.propertyName}: Label should be a string and not a function. Search won't work for functions at the moment`;
}
if (
!isWidgetHidden &&
_config.label &&
!_config.invisible &&
!(_config.helpText || _config.helperText)
) {
return `${_config.propertyName} (${_config.label}): Help text or Helper text is mandatory for property controls`;
}
if (
(_config.isJSConvertible || controls.includes(_config.controlType)) &&
!_config.isTriggerProperty
) {
if (!_config.isBindProperty)
return `${
_config.propertyName
}: isBindProperty should be true if isJSConvertible is true or when control type is [${controls.join(
" | ",
)}]`;
if (!_config.validation)
return `${
_config.propertyName
}: validation should be defined if isJSConvertible is true or when control type is [${controls.join(
" | ",
)}]`;
}
if (controls.includes(_config.controlType) && _config.isJSConvertible) {
return `${
_config.propertyName
}: No need of setting isJSConvertible since users can write JS inside [${controls.join(
" | ",
)}]`;
}
if (_config.validation !== undefined) {
const res = validateValidationStructure(_config.validation);
if (res !== true) return `${_config.propertyName}: ${res}`;
}
if (_config.children) {
for (const child of _config.children) {
const res = validatePropertyControl(child, isWidgetHidden);
if (res !== true) return `${_config.propertyName}.${res}`;
}
}
if (_config.panelConfig) {
if (_config.panelConfig.children) {
const res = validatePropertyPaneConfig(
_config.panelConfig.children,
isWidgetHidden,
);
if (res !== true) return `${_config.propertyName}.${res}`;
}
if (_config.panelConfig.contentChildren) {
const res = validatePropertyPaneConfig(
_config.panelConfig.contentChildren,
isWidgetHidden,
);
if (res !== true) return `${_config.propertyName}.${res}`;
}
if (_config.panelConfig.styleChildren) {
const res = validatePropertyPaneConfig(
_config.panelConfig.styleChildren,
isWidgetHidden,
);
if (res !== true) return `${_config.propertyName}.${res}`;
}
}
return true;
}
function validateValidationStructure(
config: ValidationConfig,
): boolean | string {
if (
config.type === ValidationTypes.FUNCTION &&
config.params &&
config.params.fn
) {
if (!config.params.expected)
return `For a ${ValidationTypes.FUNCTION} type validation, expected type and example are mandatory`;
}
return true;
}
const isNotFloat = (n: any) => {
return Number(n) === n && n % 1 === 0;
};
describe("Tests all widget's propertyPane config", () => {
beforeAll(() => {
registerWidgets(widgets);
});
widgets.forEach((widget) => {
const config = widget.getConfig();
it(`Checks ${widget.type}'s propertyPaneConfig`, () => {
const propertyPaneConfig = widget.getPropertyPaneConfig();
expect(
validatePropertyPaneConfig(propertyPaneConfig, !!config.hideCard),
).toStrictEqual(true);
const propertyPaneContentConfig = widget.getPropertyPaneContentConfig();
expect(
validatePropertyPaneConfig(
propertyPaneContentConfig,
!!config.isDeprecated,
),
).toStrictEqual(true);
const propertyPaneStyleConfig = widget.getPropertyPaneStyleConfig();
expect(
validatePropertyPaneConfig(
propertyPaneStyleConfig,
!!config.isDeprecated,
),
).toStrictEqual(true);
});
it(`Check if ${widget.type}'s dimensions are always integers`, () => {
const defaults = widget.getDefaults();
expect(isNotFloat(defaults.rows)).toBe(true);
expect(isNotFloat(defaults.columns)).toBe(true);
});
if (config.isDeprecated) {
it(`Check if ${widget.type}'s deprecation config has a proper replacement Widget`, () => {
const widgetType = widget.type;
if (config.replacement === undefined) {
fail(`${widgetType}'s replacement widget is not defined`);
}
const replacementWidgetType = config.replacement;
const replacementWidget = WidgetFactory.get(replacementWidgetType);
const replacementWidgetConfig = replacementWidget?.getConfig();
if (replacementWidgetConfig === undefined) {
fail(
`${widgetType}'s replacement widget ${replacementWidgetType} does not resolve to an actual widget Config`,
);
}
if (replacementWidgetConfig?.isDeprecated) {
fail(
`${widgetType}'s replacement widget ${replacementWidgetType} itself is deprecated. Cannot have a deprecated widget as a replacement for another deprecated widget`,
);
}
if (replacementWidgetConfig?.hideCard) {
fail(
`${widgetType}'s replacement widget ${replacementWidgetType} should be available in the entity Explorer`,
);
}
});
}
it(`Check if ${widget.type}'s setter method are configured correctly`, () => {
const setterConfig = widget.getSetterConfig();
if (setterConfig) {
expect(setterConfig).toHaveProperty("__setters");
const setters = setterConfig.__setters;
for (const [setterName, config] of Object.entries(setters)) {
expect(config).toHaveProperty("type");
expect(config).toHaveProperty("path");
expect(setterName).toContain("set");
const type = config.type;
const path = config.path;
expect(typeof type).toBe("string");
expect(typeof path).toBe("string");
}
}
});
});
});
|
1,389 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/utils/widgetRenderUtils.test.ts | import type {
WidgetEntity,
WidgetEntityConfig,
} from "@appsmith/entities/DataTree/types";
import type { DataTree } from "entities/DataTree/dataTreeTypes";
import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsReducer";
import type { MetaWidgetsReduxState } from "reducers/entityReducers/metaWidgetsReducer";
import { buildChildWidgetTree, createCanvasWidget } from "./widgetRenderUtils";
import type { FlattenedWidgetProps } from "WidgetProvider/constants";
describe("createCanvasWidget functionality", () => {
it("returns an empty errors if no evaluations are present", function () {
const canvasWidget = {} as unknown as FlattenedWidgetProps;
const dataTree = {} as unknown as WidgetEntity;
const response = createCanvasWidget(
canvasWidget,
dataTree,
{} as WidgetEntityConfig,
);
expect(response.errors.length).toEqual(0);
});
it("returns an empty errors if no evaluation errors are present", () => {
const canvasWidget = {} as unknown as FlattenedWidgetProps;
const dataTree = {
__evaluation__: {},
} as unknown as WidgetEntity;
const response = createCanvasWidget(
canvasWidget,
dataTree,
{} as WidgetEntityConfig,
);
expect(response.errors.length).toEqual(0);
});
it("populates __evaluation__ errors inside widget error property", () => {
const canvasWidget = {} as unknown as FlattenedWidgetProps;
const dataTree = {
__evaluation__: {
errors: {
propertyPath: [
{
errorMessage: {
name: "Validation Error",
message: "Error Message",
},
raw: "Error Message Stack",
},
],
},
},
} as unknown as WidgetEntity;
const response = createCanvasWidget(
canvasWidget,
dataTree,
{} as WidgetEntityConfig,
);
expect(response.errors.length).toEqual(1);
expect(response.errors[0].name).toStrictEqual("Validation Error");
expect(response.errors[0].message).toStrictEqual("Error Message");
expect(response.errors[0].stack).toStrictEqual("Error Message Stack");
expect(response.errors[0].type).toStrictEqual("property");
expect(response.errors[0].path).toStrictEqual("propertyPath");
});
});
describe("test EditorUtils methods", () => {
describe("should test buildChildWidgetTree method", () => {
const metaWidgets = {
"1_meta": {
children: ["2_meta"],
type: "CANVAS",
widgetId: "1_meta",
parentId: "2",
topRow: 0,
bottomRow: 100,
widgetName: "meta_one",
},
"2_meta": {
children: [],
type: "INPUT_WIDGET",
widgetId: "2_meta",
parentId: "1_meta",
topRow: 0,
bottomRow: 10,
widgetName: "meta_two",
},
} as unknown as MetaWidgetsReduxState;
const canvasWidgets = {
"1": {
children: ["2"],
type: "FORM_WIDGET",
widgetId: "1",
parentId: "0",
topRow: 0,
bottomRow: 10,
widgetName: "one",
},
"2": {
children: ["3", "4", "1_meta"],
type: "CANVAS",
widgetId: "2",
parentId: "1",
topRow: 0,
bottomRow: 100,
widgetName: "two",
},
"3": {
children: [],
type: "TEXT",
widgetId: "3",
parentId: "2",
topRow: 4,
bottomRow: 5,
widgetName: "three",
},
"4": {
children: [],
type: "BUTTON",
widgetId: "4",
parentId: "2",
topRow: 6,
bottomRow: 18,
widgetName: "four",
},
} as unknown as CanvasWidgetsReduxState;
const dataTree = {
one: {
children: ["2"],
type: "FORM_WIDGET",
widgetId: "1",
parentId: "0",
topRow: 0,
bottomRow: 10,
widgetName: "one",
skipForFormWidget: "test",
value: "test",
isDirty: true,
isValid: true,
},
two: {
children: ["3", "4", "1_meta"],
type: "CANVAS",
widgetId: "2",
parentId: "1",
topRow: 0,
bottomRow: 100,
widgetName: "two",
skipForFormWidget: "test",
value: "test",
isDirty: true,
isValid: true,
},
three: {
children: [],
type: "TEXT",
widgetId: "3",
parentId: "2",
topRow: 4,
bottomRow: 5,
widgetName: "three",
skipForFormWidget: "test",
value: "test",
isDirty: true,
isValid: true,
},
four: {
children: [],
type: "BUTTON",
widgetId: "4",
parentId: "2",
topRow: 6,
bottomRow: 18,
widgetName: "four",
skipForFormWidget: "test",
value: "test",
isDirty: true,
isValid: true,
},
meta_one: {
skipForFormWidget: "test",
children: ["1_meta"],
type: "CANVAS",
widgetId: "1_meta",
parentId: "2",
topRow: 0,
bottomRow: 100,
widgetName: "meta_one",
},
meta_two: {
children: [],
type: "INPUT_WIDGET",
widgetId: "meta_two",
parentId: "meta_1",
topRow: 0,
bottomRow: 10,
widgetName: "two",
skipForFormWidget: "test",
value: "test",
isDirty: true,
isValid: true,
},
} as unknown as DataTree;
it("should return a complete childwidgets Tree", () => {
const childWidgetTree = [
{
bottomRow: 5,
children: [],
skipForFormWidget: "test",
isDirty: true,
isLoading: false,
isValid: true,
parentId: "2",
topRow: 4,
type: "TEXT",
value: "test",
widgetId: "3",
widgetName: "three",
errors: [],
},
{
bottomRow: 18,
children: [],
skipForFormWidget: "test",
isDirty: true,
isLoading: false,
isValid: true,
parentId: "2",
topRow: 6,
type: "BUTTON",
value: "test",
widgetId: "4",
widgetName: "four",
errors: [],
},
{
type: "CANVAS",
isLoading: false,
widgetId: "1_meta",
parentId: "2",
topRow: 0,
bottomRow: 100,
widgetName: "meta_one",
skipForFormWidget: "test",
errors: [],
children: [
{
isDirty: true,
isLoading: false,
isValid: true,
value: "test",
children: [],
type: "INPUT_WIDGET",
widgetId: "2_meta",
parentId: "1_meta",
topRow: 0,
bottomRow: 10,
widgetName: "meta_two",
skipForFormWidget: "test",
errors: [],
},
],
},
];
expect(
buildChildWidgetTree(
canvasWidgets,
metaWidgets,
dataTree,
new Set<string>("one"),
{},
"2",
),
).toEqual(childWidgetTree);
});
it("should return a partial childwidgets Tree with properties specified", () => {
const childWidgetTree = [
{
bottomRow: 100,
children: [
{
bottomRow: 5,
children: [],
isDirty: true,
isLoading: false,
isValid: true,
parentId: "2",
topRow: 4,
type: "TEXT",
value: "test",
widgetId: "3",
widgetName: "three",
errors: [],
},
{
bottomRow: 18,
children: [],
isDirty: true,
isLoading: false,
isValid: true,
parentId: "2",
topRow: 6,
type: "BUTTON",
value: "test",
widgetId: "4",
widgetName: "four",
errors: [],
},
{
isLoading: false,
parentId: "2",
topRow: 0,
type: "CANVAS",
widgetId: "1_meta",
bottomRow: 100,
widgetName: "meta_one",
errors: [],
children: [
{
isDirty: true,
isLoading: false,
isValid: true,
value: "test",
children: [],
type: "INPUT_WIDGET",
widgetId: "2_meta",
parentId: "1_meta",
topRow: 0,
bottomRow: 10,
widgetName: "meta_two",
errors: [],
},
],
},
],
isDirty: true,
isLoading: false,
isValid: true,
parentId: "1",
topRow: 0,
type: "CANVAS",
value: "test",
widgetId: "2",
widgetName: "two",
errors: [],
},
];
expect(
buildChildWidgetTree(
canvasWidgets,
metaWidgets,
dataTree,
new Set<string>("two"),
{},
"1",
),
).toEqual(childWidgetTree);
});
it("should return a partial childwidgets Tree with just loading widgets", () => {
const childWidgetTree = [
{
ENTITY_TYPE: "WIDGET",
bindingPaths: {},
bottomRow: 100,
children: [
{
ENTITY_TYPE: "WIDGET",
bindingPaths: {},
bottomRow: 5,
children: [],
isLoading: false,
logBlackList: {},
meta: {},
overridingPropertyPaths: {},
parentId: "2",
privateWidgets: {},
propertyOverrideDependency: {},
reactivePaths: {},
topRow: 4,
triggerPaths: {},
type: undefined,
validationPaths: {},
widgetId: "3",
widgetName: "three",
},
{
ENTITY_TYPE: "WIDGET",
bindingPaths: {},
bottomRow: 18,
children: [],
isLoading: false,
logBlackList: {},
meta: {},
overridingPropertyPaths: {},
parentId: "2",
privateWidgets: {},
propertyOverrideDependency: {},
reactivePaths: {},
topRow: 6,
triggerPaths: {},
type: undefined,
validationPaths: {},
widgetId: "4",
widgetName: "four",
},
{
ENTITY_TYPE: "WIDGET",
bindingPaths: {},
bottomRow: 100,
isLoading: false,
logBlackList: {},
meta: {},
overridingPropertyPaths: {},
parentId: "2",
privateWidgets: {},
propertyOverrideDependency: {},
reactivePaths: {},
topRow: 0,
triggerPaths: {},
type: undefined,
validationPaths: {},
widgetId: "1_meta",
widgetName: "meta_one",
children: [
{
ENTITY_TYPE: "WIDGET",
bindingPaths: {},
bottomRow: 10,
children: [],
isLoading: false,
logBlackList: {},
meta: {},
overridingPropertyPaths: {},
parentId: "1_meta",
privateWidgets: {},
propertyOverrideDependency: {},
reactivePaths: {},
topRow: 0,
triggerPaths: {},
type: undefined,
validationPaths: {},
widgetId: "2_meta",
widgetName: "meta_two",
},
],
},
],
isLoading: false,
logBlackList: {},
meta: {},
overridingPropertyPaths: {},
parentId: "1",
privateWidgets: {},
propertyOverrideDependency: {},
reactivePaths: {},
topRow: 0,
triggerPaths: {},
type: undefined,
validationPaths: {},
widgetId: "2",
widgetName: "two",
},
];
expect(
buildChildWidgetTree(
canvasWidgets,
metaWidgets,
{},
new Set<string>("one"),
{},
"1",
),
).toEqual(childWidgetTree);
});
});
});
|
1,400 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/utils/FilterInternalProperties | petrpan-code/appsmithorg/appsmith/app/client/src/utils/FilterInternalProperties/__tests__/index.test.ts | import { filterInternalProperties } from "..";
import {
ENTITY_TYPE_VALUE,
EvaluationSubstitutionType,
} from "entities/DataTree/dataTreeFactory";
import type {
DataTreeEntityConfig,
DataTreeEntityObject,
WidgetEntityConfig,
} from "@appsmith/entities/DataTree/types";
import { registerWidgets } from "WidgetProvider/factory/registrationHelper";
import InputWidget from "widgets/InputWidgetV2";
import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer";
describe("filterInternalProperties tests", () => {
beforeAll(() => {
registerWidgets([InputWidget]);
});
it("filter widget properties", () => {
const dataTreeEntity: DataTreeEntityObject = {
widgetId: "yolo",
widgetName: "Input1",
parentId: "123",
renderMode: "CANVAS",
text: "yo",
type: "INPUT_WIDGET_V2",
ENTITY_TYPE: ENTITY_TYPE_VALUE.WIDGET,
parentColumnSpace: 1,
parentRowSpace: 2,
leftColumn: 2,
rightColumn: 3,
topRow: 1,
bottomRow: 2,
isLoading: false,
version: 1,
meta: {},
isVisible: false,
isDisabled: false,
isValid: true,
};
const dataTreeEntityConfig: WidgetEntityConfig = {
bindingPaths: {
defaultText: EvaluationSubstitutionType.TEMPLATE,
},
reactivePaths: {
defaultText: EvaluationSubstitutionType.TEMPLATE,
},
triggerPaths: {
onTextChange: true,
},
validationPaths: {},
logBlackList: {},
propertyOverrideDependency: {},
overridingPropertyPaths: {},
privateWidgets: {},
defaultMetaProps: [],
widgetId: "yolo",
widgetName: "Input1",
type: "INPUT_WIDGET_V2",
ENTITY_TYPE: ENTITY_TYPE_VALUE.WIDGET,
};
const dataTree = {
Input1: dataTreeEntity,
};
const configTree = {
Input1: dataTreeEntityConfig,
};
const peekData = filterInternalProperties(
"Input1",
dataTree["Input1"],
[],
dataTree,
configTree,
);
expect(peekData).toStrictEqual({
isDisabled: false,
isValid: true,
isVisible: false,
text: "yo",
});
});
it("filter jsObject properties", () => {
const jsActions = [
{
isLoading: false,
config: {
id: "655b392ca357d11c50eedc7f",
applicationId: "654b35d925f7f47198610ffb",
workspaceId: "64a561f4a272dc36bd584a6f",
name: "jsObject1",
pageId: "654b35da25f7f47198610fff",
pluginId: "644b84dd80127e0eff78a744",
pluginType: "JS",
actionIds: [],
archivedActionIds: [],
actions: [],
archivedActions: [],
body: "export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\tmyFun1 () {\n\t\tinputs.email11\n\t\t//\twrite code here\n\t\t//\tthis.myVar1 = [1,2,3]\n\t},\n\tasync myFun2 () {\n\t\t//\tuse async-await or promises\n\t\t//\tawait storeValue('varName', 'hello world')\n\t}\n}",
variables: [
{
name: "myVar1",
value: "[]",
},
{
name: "myVar2",
value: "{}",
},
],
userPermissions: [
"read:actions",
"delete:actions",
"execute:actions",
"manage:actions",
],
},
},
] as unknown as JSCollectionData[];
const jsObject1 = {
myVar1: [],
myVar2: {},
body: "export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\tmyFun1 () {\n\t\tinputs.email11\n\t\t//\twrite code here\n\t\t//\tJSObject1.myVar1 = [1,2,3]\n\t},\n\tasync myFun2 () {\n\t\t//\tuse async-await or promises\n\t\t//\tawait storeValue('varName', 'hello world')\n\t}\n}",
ENTITY_TYPE: "JSACTION",
actionId: "655b392ca357d11c50eedc7f",
__evaluation__: {
errors: {
myVar2: [],
myVar1: [],
myFun2: [],
myFun1: [],
body: [],
},
evaluatedValues: {
myVar2: {},
myVar1: [],
},
},
} as unknown as DataTreeEntityObject;
const jsObject1Config = {
actionId: "655b392ca357d11c50eedc7f",
name: "JSObject1",
pluginType: "JS",
ENTITY_TYPE: "JSACTION",
bindingPaths: {
body: "SMART_SUBSTITUTE",
myVar1: "SMART_SUBSTITUTE",
myVar2: "SMART_SUBSTITUTE",
},
reactivePaths: {
body: "SMART_SUBSTITUTE",
myVar1: "SMART_SUBSTITUTE",
myVar2: "SMART_SUBSTITUTE",
},
dynamicBindingPathList: [
{
key: "body",
},
{
key: "myVar1",
},
{
key: "myVar2",
},
],
variables: ["myVar1", "myVar2"],
dependencyMap: {
body: [],
},
} as unknown as DataTreeEntityConfig;
const dataTree = {
jsObject1: jsObject1,
};
const configTree = {
jsObject1: jsObject1Config,
};
const peekData = filterInternalProperties(
"jsObject1",
dataTree["jsObject1"],
jsActions,
dataTree,
configTree,
);
expect(peekData).toStrictEqual({
myVar1: [],
myVar2: {},
});
});
});
|
1,408 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/utils | petrpan-code/appsmithorg/appsmith/app/client/src/utils/autoHeight/generateTree.test.ts | import type { NodeSpace, TreeNode } from "./constants";
import { generateTree } from "./generateTree";
describe("Generate Auto Height Layout tree", () => {
it("Does not conflict when only one horizontal edge is the same", () => {
const input: Record<string, NodeSpace> = {
"1": { left: 0, right: 100, top: 0, bottom: 30, id: "1" },
"2": { left: 100, top: 0, bottom: 30, right: 120, id: "2" },
};
const previousTree: Record<string, TreeNode> = {};
const layoutUpdated = false;
const expected = {
"1": {
aboves: [],
belows: [],
topRow: 0,
bottomRow: 30,
originalBottomRow: 30,
originalTopRow: 0,
distanceToNearestAbove: 0,
},
"2": {
aboves: [],
belows: [],
topRow: 0,
bottomRow: 30,
originalBottomRow: 30,
originalTopRow: 0,
distanceToNearestAbove: 0,
},
};
const result = generateTree(input, layoutUpdated, previousTree);
expect(result).toStrictEqual(expected);
});
it("Does conflict when part of the boxes overlap horizontally", () => {
const input: Record<string, NodeSpace> = {
"1": { left: 0, right: 100, top: 0, bottom: 30, id: "1" },
"2": { left: 80, top: 40, bottom: 80, right: 120, id: "2" },
};
const previousTree: Record<string, TreeNode> = {};
const layoutUpdated = false;
const expected = {
"1": {
aboves: [],
belows: ["2"],
topRow: 0,
bottomRow: 30,
originalBottomRow: 30,
originalTopRow: 0,
distanceToNearestAbove: 0,
},
"2": {
aboves: ["1"],
belows: [],
topRow: 40,
bottomRow: 80,
originalBottomRow: 80,
originalTopRow: 40,
distanceToNearestAbove: 10,
},
};
const result = generateTree(input, layoutUpdated, previousTree);
expect(result).toStrictEqual(expected);
});
it("Uses existing originals if available in prevTree when layout hasn't updated", () => {
const input: Record<string, NodeSpace> = {
"1": { left: 0, right: 100, top: 0, bottom: 30, id: "1" },
"2": { left: 80, top: 30, bottom: 40, right: 120, id: "2" },
};
const previousTree: Record<string, TreeNode> = {
"1": {
aboves: [],
belows: ["2"],
topRow: 0,
bottomRow: 30,
originalBottomRow: 20,
originalTopRow: 0,
distanceToNearestAbove: 0,
},
"2": {
aboves: ["1"],
belows: [],
topRow: 30,
bottomRow: 40,
originalBottomRow: 30,
originalTopRow: 20,
distanceToNearestAbove: 0,
},
};
const layoutUpdated = false;
const expected = {
"1": {
aboves: [],
belows: ["2"],
topRow: 0,
bottomRow: 30,
originalBottomRow: 20,
originalTopRow: 0,
distanceToNearestAbove: 0,
},
"2": {
aboves: ["1"],
belows: [],
topRow: 30,
bottomRow: 40,
originalBottomRow: 30,
originalTopRow: 20,
distanceToNearestAbove: 0,
},
};
const result = generateTree(input, layoutUpdated, previousTree);
expect(result).toStrictEqual(expected);
});
it("Ignores existing originals if available in prevTree when layout has updated", () => {
const input: Record<string, NodeSpace> = {
"1": { left: 0, right: 100, top: 0, bottom: 30, id: "1" },
"2": { left: 80, top: 30, bottom: 40, right: 120, id: "2" },
};
const previousTree: Record<string, TreeNode> = {
"1": {
aboves: [],
belows: ["2"],
topRow: 0,
bottomRow: 30,
originalBottomRow: 20,
originalTopRow: 0,
distanceToNearestAbove: 0,
},
"2": {
aboves: ["1"],
belows: [],
topRow: 30,
bottomRow: 40,
originalBottomRow: 30,
originalTopRow: 20,
distanceToNearestAbove: 0,
},
};
const layoutUpdated = true;
const expected = {
"1": {
aboves: [],
belows: ["2"],
topRow: 0,
bottomRow: 30,
originalBottomRow: 30,
originalTopRow: 0,
distanceToNearestAbove: 0,
},
"2": {
aboves: ["1"],
belows: [],
topRow: 30,
bottomRow: 40,
originalBottomRow: 40,
originalTopRow: 30,
distanceToNearestAbove: 0,
},
};
const result = generateTree(input, layoutUpdated, previousTree);
expect(result).toStrictEqual(expected);
});
});
|
1,411 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/utils | petrpan-code/appsmithorg/appsmith/app/client/src/utils/autoHeight/mutateDOM.test.ts | import { getNodesAndStylesToUpdate } from "./mutateDOM";
describe("DOM mutations", () => {
it("Computes the correct values to update based on widgetsToUpdate", () => {
const widgetsToUpdate = {
m: [
{
propertyValue: 100,
propertyPath: "bottomRow",
},
{
propertyValue: 10,
propertyPath: "topRow",
},
],
n: [
{
propertyValue: 100,
propertyPath: "bottomRow",
},
],
o: [
{
propertyValue: 100,
propertyPath: "bottomRow",
},
{
propertyValue: 0,
propertyPath: "topRow",
},
],
};
const widgetsMeasuredInPixels = ["n", "o"];
const result = getNodesAndStylesToUpdate(
widgetsToUpdate,
widgetsMeasuredInPixels,
);
expect(result).toStrictEqual({
m: { y: 106, height: 900 },
n: { y: 6, height: 100 }, // Since we're absolutely positioning the canvas widges, this y value is correct
o: { y: 6, height: 100 },
});
});
});
|
1,413 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/utils | petrpan-code/appsmithorg/appsmith/app/client/src/utils/autoHeight/reflow.test.ts | import type { TreeNode } from "./constants";
import { computeChangeInPositionBasedOnDelta } from "./reflow";
describe("reflow", () => {
describe("computeChangeInPositionBasedOnDelta (should compute new positions for boxes based on boxes which has changed heights)", () => {
it("simple 2 boxes test where the top grows by 5 rows and should shifts the bottom one by 5 rows", () => {
const box1TopRow = 10;
const box1BottomRow = 20;
const box2TopRow = 30;
const box2BottomRow = 40;
const tree: Record<string, TreeNode> = {
"1": {
aboves: [],
belows: ["2"],
topRow: box1TopRow,
bottomRow: box1BottomRow,
originalTopRow: box1TopRow,
originalBottomRow: box1BottomRow,
distanceToNearestAbove: 0,
},
"2": {
aboves: ["1"],
belows: [],
topRow: box2TopRow,
bottomRow: box2BottomRow,
originalTopRow: box2TopRow,
originalBottomRow: box2BottomRow,
distanceToNearestAbove: 10,
},
};
const box1DeltaHeightIncrease = 5;
const delta: Record<string, number> = {
"1": box1DeltaHeightIncrease,
};
const expectedChanges = {
"1": {
topRow: box1TopRow,
bottomRow: box1BottomRow + box1DeltaHeightIncrease,
},
"2": {
topRow: box2TopRow + box1DeltaHeightIncrease,
bottomRow: box2BottomRow + box1DeltaHeightIncrease,
},
};
const changes = computeChangeInPositionBasedOnDelta(tree, delta);
expect(expectedChanges).toMatchObject(changes);
});
it("When delta is negative, the original spacing is maintained", () => {
const box1TopRow = 10;
const box1BottomRow = 100;
const box1OriginalTopRow = 10;
const box1OriginalBottomRow = 20;
const box2TopRow = 110;
const box2BottomRow = 200;
const box2OriginalTopRow = 30;
const box2OriginalBottomRow = 40;
const tree: Record<string, TreeNode> = {
"1": {
aboves: [],
belows: ["2"],
topRow: box1TopRow,
bottomRow: box1BottomRow,
originalTopRow: box1OriginalTopRow,
originalBottomRow: box1OriginalBottomRow,
distanceToNearestAbove: 0,
},
"2": {
aboves: ["1"],
belows: [],
topRow: box2TopRow,
bottomRow: box2BottomRow,
originalTopRow: box2OriginalTopRow,
originalBottomRow: box2OriginalBottomRow,
distanceToNearestAbove: 10,
},
};
const box1DeltaHeight = -50;
const delta: Record<string, number> = {
"1": box1DeltaHeight,
"2": box1DeltaHeight,
};
const expectedChanges = {
"1": {
topRow: box1TopRow,
bottomRow: box1BottomRow + box1DeltaHeight,
},
"2": {
topRow: 60,
bottomRow: 100,
},
};
const changes = computeChangeInPositionBasedOnDelta(tree, delta);
expect(expectedChanges).toMatchObject(changes);
});
it("When delta is negative, bottom box moves up", () => {
const box1TopRow = 10;
const box1BottomRow = 100;
const box1OriginalTopRow = 10;
const box1OriginalBottomRow = 15;
const box2TopRow = 140;
const box2BottomRow = 230;
const box2OriginalTopRow = 30;
const box2OriginalBottomRow = 40;
const tree: Record<string, TreeNode> = {
"1": {
aboves: [],
belows: ["2"],
topRow: box1TopRow,
bottomRow: box1BottomRow,
originalTopRow: box1OriginalTopRow,
originalBottomRow: box1OriginalBottomRow,
distanceToNearestAbove: 0,
},
"2": {
aboves: ["1"],
belows: [],
topRow: box2TopRow,
bottomRow: box2BottomRow,
originalTopRow: box2OriginalTopRow,
originalBottomRow: box2OriginalBottomRow,
distanceToNearestAbove: 40,
},
};
const box1DeltaHeight = -50;
const delta: Record<string, number> = {
"1": box1DeltaHeight,
"2": box1DeltaHeight,
};
const expectedChanges = {
"1": {
topRow: box1TopRow,
bottomRow: box1BottomRow + box1DeltaHeight,
},
"2": {
topRow: 90,
bottomRow: 130,
},
};
const changes = computeChangeInPositionBasedOnDelta(tree, delta);
expect(expectedChanges).toMatchObject(changes);
});
it("When a widget is blocking and delta is negative, bottom box moves up to the original spacing between the blocking box and the bottom box", () => {
const box1TopRow = 10;
const box1BottomRow = 100;
const box1OriginalTopRow = 10;
const box1OriginalBottomRow = 15;
const box2TopRow = 140;
const box2BottomRow = 230;
const box2OriginalTopRow = 30;
const box2OriginalBottomRow = 40;
const box3 = {
aboves: [],
belows: ["2"],
topRow: 50,
bottomRow: 120,
originalBottomRow: 20,
originalTopRow: 10,
distanceToNearestAbove: 0,
};
const tree: Record<string, TreeNode> = {
"1": {
aboves: [],
belows: ["2"],
topRow: box1TopRow,
bottomRow: box1BottomRow,
originalTopRow: box1OriginalTopRow,
originalBottomRow: box1OriginalBottomRow,
distanceToNearestAbove: 0,
},
"2": {
aboves: ["1", "3"],
belows: [],
topRow: box2TopRow,
bottomRow: box2BottomRow,
originalTopRow: box2OriginalTopRow,
originalBottomRow: box2OriginalBottomRow,
distanceToNearestAbove: 20,
},
"3": box3,
};
const box1DeltaHeight = -50;
const delta: Record<string, number> = {
"1": box1DeltaHeight,
"2": box1DeltaHeight,
};
const expectedChanges = {
"1": {
topRow: box1TopRow,
bottomRow: box1BottomRow + box1DeltaHeight,
},
"2": {
topRow: 140,
bottomRow: 180,
},
};
const changes = computeChangeInPositionBasedOnDelta(tree, delta);
expect(expectedChanges).toMatchObject(changes);
});
});
});
|
Subsets and Splits