level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
9,870
0
petrpan-code/chakra-ui/chakra-ui/packages/legacy/utils
petrpan-code/chakra-ui/chakra-ui/packages/legacy/utils/tests/lazy.test.ts
import { determineLazyBehavior } from "../src" test("determineLazyBehavior", () => { // when not lazy, tab panels are always rendered expect(determineLazyBehavior({ isLazy: false })).toBe(true) expect(determineLazyBehavior({ isLazy: false, isSelected: false })).toBe(true) expect(determineLazyBehavior({ isLazy: false, hasBeenSelected: false })).toBe( true, ) expect( determineLazyBehavior({ isLazy: false, lazyBehavior: "unmount", }), ).toBe(true) // when lazy and unmounting hidden panels, tab panels are only // rendered when selected expect(determineLazyBehavior({ isLazy: true, lazyBehavior: "unmount" })).toBe( false, ) expect( determineLazyBehavior({ isLazy: true, lazyBehavior: "keepMounted", hasBeenSelected: true, isSelected: false, }), ).toBe(true) expect( determineLazyBehavior({ isLazy: true, lazyBehavior: "unmount", isSelected: true, }), ).toBe(true) expect( determineLazyBehavior({ isLazy: true, lazyBehavior: "unmount", isSelected: false, hasBeenSelected: true, }), ).toBe(false) // when lazy and leaving hidden panels mounted, tab panels are only rendered // when selected or if they were previously selected expect(determineLazyBehavior({ isLazy: true, isSelected: true })).toBe(true) expect( determineLazyBehavior({ isLazy: true, isSelected: false, hasBeenSelected: true, lazyBehavior: "keepMounted", }), ).toBe(true) expect(determineLazyBehavior({ isLazy: true })).toBe(false) })
9,871
0
petrpan-code/chakra-ui/chakra-ui/packages/legacy/utils
petrpan-code/chakra-ui/chakra-ui/packages/legacy/utils/tests/number.test.ts
import { toPrecision, countDecimalPlaces, valueToPercent, percentToValue, roundValueToStep, clampValue, } from "../src" test("should round number to specific precision", () => { expect(toPrecision(1.4567, 2)).toStrictEqual("1.46") }) test("should return number of decimal places", () => { expect(countDecimalPlaces(1.4567)).toStrictEqual(4) }) test("should return percent of value in a specific range", () => { expect(valueToPercent(5, 0, 10)).toStrictEqual(50) }) test("should return value of percent in a specific range", () => { expect(percentToValue(50, 0, 10)).toStrictEqual(500) }) describe("should get next value of value after specified step", () => { test("with both even from & step", () => { expect(roundValueToStep(4, 0, 2)).toStrictEqual("4") expect(roundValueToStep(5, 0, 2)).toStrictEqual("6") expect(roundValueToStep(6, 0, 2)).toStrictEqual("6") }) test("with both odd from & step", () => { expect(roundValueToStep(3, 3, 5)).toStrictEqual("3") expect(roundValueToStep(4, 3, 5)).toStrictEqual("3") expect(roundValueToStep(5, 3, 5)).toStrictEqual("3") expect(roundValueToStep(6, 3, 5)).toStrictEqual("8") expect(roundValueToStep(7, 3, 5)).toStrictEqual("8") expect(roundValueToStep(8, 3, 5)).toStrictEqual("8") }) test("with odd from and even step", () => { expect(roundValueToStep(3, 1, 2)).toStrictEqual("3") expect(roundValueToStep(4, 1, 2)).toStrictEqual("5") expect(roundValueToStep(5, 1, 2)).toStrictEqual("5") expect(roundValueToStep(6, 1, 2)).toStrictEqual("7") }) }) test("should clamp value to specified minimum", () => { expect(clampValue(5, 6, 10)).toStrictEqual(6) })
9,872
0
petrpan-code/chakra-ui/chakra-ui/packages/legacy/utils
petrpan-code/chakra-ui/chakra-ui/packages/legacy/utils/tests/object.test.ts
import { omit, pick, split, get, memoize, getWithDefault, filterUndefined, } from "../src/object" const obj = { a: 1, b: 2, c: { d: 3 } } test("should return object with omitted property", () => { expect(omit(obj, ["a"])).toStrictEqual({ b: 2, c: { d: 3 } }) }) test("should return property in object with specified key", () => { expect(pick(obj, ["a"])).toStrictEqual({ a: 1 }) }) test("should split object by key and return array of split objects", () => { expect(split(obj, ["a"])).toStrictEqual([{ a: 1 }, { b: 2, c: { d: 3 } }]) }) test("should get value of specified path in object", () => { expect(get(obj, "c.d")).toStrictEqual(3) }) test("should get value of specified path in object or return path as default if value not found", () => { expect(getWithDefault("c.d", obj)).toStrictEqual(3) expect(getWithDefault("c.e", obj)).toStrictEqual("c.e") }) test("should filter undefined values in object", () => { const result = filterUndefined({ size: null, variant: undefined, colorScheme: "red", }) expect(result).toStrictEqual({ colorScheme: "red" }) }) test("should get memoized value on successive calls", () => { const mockGet = jest.fn(() => true) const memoizedMockGet = memoize(mockGet) // run the memoized get twice expect(memoizedMockGet(obj, "path")).toStrictEqual(true) expect(memoizedMockGet(obj, "path")).toStrictEqual(true) // make sure get was only called once expect(mockGet).toHaveBeenCalledTimes(1) })
9,873
0
petrpan-code/chakra-ui/chakra-ui/packages/legacy/utils
petrpan-code/chakra-ui/chakra-ui/packages/legacy/utils/tests/responsive.test.ts
import { analyzeBreakpoints, arrayToObjectNotation, isResponsiveObjectLike, mapResponsive, objectToArrayNotation, } from "../src" const arr = [2, 3] const obj = { sm: 2, md: 3 } const mapper = (val: number) => `grid-template-columns(${val}, 1fr )` test("should run mapper on array or object and return mapped data", () => { expect(mapResponsive(arr, mapper)).toStrictEqual([ "grid-template-columns(2, 1fr )", "grid-template-columns(3, 1fr )", ]) expect(mapResponsive(obj, mapper)).toStrictEqual({ sm: "grid-template-columns(2, 1fr )", md: "grid-template-columns(3, 1fr )", }) }) test("should convert object to array notation", () => { expect(objectToArrayNotation({ lg: 400, sm: 100, base: 40 })).toEqual([ 40, 100, null, 400, ]) expect(objectToArrayNotation({ sm: 100 })).toEqual([null, 100]) expect(objectToArrayNotation({ md: 100 })).toEqual([null, null, 100]) expect(objectToArrayNotation({ base: 100 })).toEqual([100]) expect(objectToArrayNotation({ base: 100, lg: 1300 })).toEqual([ 100, null, null, 1300, ]) expect(objectToArrayNotation({ base: 100, md: 400 })).toEqual([ 100, null, 400, ]) expect(objectToArrayNotation({})).toEqual([]) }) test("should tell if object is responsive-like", () => { expect(isResponsiveObjectLike({ lg: 400, sm: 100, base: 40 })).toBe(true) expect(isResponsiveObjectLike({ base: 40 })).toBe(true) expect(isResponsiveObjectLike({ sm: 100 })).toBe(true) expect(isResponsiveObjectLike({})).toBe(false) expect(isResponsiveObjectLike({ base: 40, paddingTop: 4 })).toBe(false) expect(isResponsiveObjectLike({ md: 40, paddingTop: 4 })).toBe(false) expect(isResponsiveObjectLike({ paddingTop: 4, paddingLeft: 4 })).toBe(false) }) test("should convert array to object value", () => { expect(arrayToObjectNotation(["20px", null, null, "60px"])).toEqual({ base: "20px", lg: "60px", }) expect(arrayToObjectNotation(["30px"])).toEqual({ base: "30px" }) expect(arrayToObjectNotation(["30px", "50px"])).toEqual({ base: "30px", sm: "50px", }) expect(arrayToObjectNotation([])).toEqual({}) }) test("should work correctly", () => { expect( analyzeBreakpoints({ sm: "320px", md: "640px", lg: "1000px", xl: "4000px", })?.details, ).toMatchInlineSnapshot(` [ { "_minW": "-0.02px", "breakpoint": "base", "maxW": "319.98px", "maxWQuery": "@media screen and (max-width: 319.98px)", "minMaxQuery": "@media screen and (min-width: 0px) and (max-width: 319.98px)", "minW": "0px", "minWQuery": "@media screen and (min-width: 0px)", }, { "_minW": "319.98px", "breakpoint": "sm", "maxW": "639.98px", "maxWQuery": "@media screen and (max-width: 639.98px)", "minMaxQuery": "@media screen and (min-width: 320px) and (max-width: 639.98px)", "minW": "320px", "minWQuery": "@media screen and (min-width: 320px)", }, { "_minW": "639.98px", "breakpoint": "md", "maxW": "999.98px", "maxWQuery": "@media screen and (max-width: 999.98px)", "minMaxQuery": "@media screen and (min-width: 640px) and (max-width: 999.98px)", "minW": "640px", "minWQuery": "@media screen and (min-width: 640px)", }, { "_minW": "999.98px", "breakpoint": "lg", "maxW": "3999.98px", "maxWQuery": "@media screen and (max-width: 3999.98px)", "minMaxQuery": "@media screen and (min-width: 1000px) and (max-width: 3999.98px)", "minW": "1000px", "minWQuery": "@media screen and (min-width: 1000px)", }, { "_minW": "3999.98px", "breakpoint": "xl", "maxW": undefined, "maxWQuery": "@media screen", "minMaxQuery": "@media screen and (min-width: 4000px)", "minW": "4000px", "minWQuery": "@media screen and (min-width: 4000px)", }, ] `) }) // Ensures no breaking change test("should work with createBreakpoint output", () => { expect( analyzeBreakpoints({ base: "0em", sm: "320px", md: "640px", lg: "1000px", xl: "4000px", })?.details, ).toMatchInlineSnapshot(` [ { "_minW": "-0.01em", "breakpoint": "base", "maxW": "319.98px", "maxWQuery": "@media screen and (max-width: 319.98px)", "minMaxQuery": "@media screen and (min-width: 0em) and (max-width: 319.98px)", "minW": "0em", "minWQuery": "@media screen and (min-width: 0em)", }, { "_minW": "319.98px", "breakpoint": "sm", "maxW": "639.98px", "maxWQuery": "@media screen and (max-width: 639.98px)", "minMaxQuery": "@media screen and (min-width: 320px) and (max-width: 639.98px)", "minW": "320px", "minWQuery": "@media screen and (min-width: 320px)", }, { "_minW": "639.98px", "breakpoint": "md", "maxW": "999.98px", "maxWQuery": "@media screen and (max-width: 999.98px)", "minMaxQuery": "@media screen and (min-width: 640px) and (max-width: 999.98px)", "minW": "640px", "minWQuery": "@media screen and (min-width: 640px)", }, { "_minW": "999.98px", "breakpoint": "lg", "maxW": "3999.98px", "maxWQuery": "@media screen and (max-width: 3999.98px)", "minMaxQuery": "@media screen and (min-width: 1000px) and (max-width: 3999.98px)", "minW": "1000px", "minWQuery": "@media screen and (min-width: 1000px)", }, { "_minW": "3999.98px", "breakpoint": "xl", "maxW": undefined, "maxWQuery": "@media screen", "minMaxQuery": "@media screen and (min-width: 4000px)", "minW": "4000px", "minWQuery": "@media screen and (min-width: 4000px)", }, ] `) })
9,874
0
petrpan-code/chakra-ui/chakra-ui/packages/legacy/utils
petrpan-code/chakra-ui/chakra-ui/packages/legacy/utils/tests/walk-object.test.ts
import { walkObject } from "../src" describe("walkObject", () => { it("should handle an object", () => { const target = { key: "original", nested: { nestedKey: "nestedOriginal", }, } const replaceWith = "It's me" const result = walkObject(target, () => replaceWith) expect(result).toEqual({ key: replaceWith, nested: { nestedKey: replaceWith, }, }) }) it("should handle an array", () => { const target = [ "very", "original", { nested: { nestedKey: "nestedOriginal", }, }, ] const replaceWith = "It's me" const result = walkObject(target, () => replaceWith) expect(result).toEqual([ replaceWith, replaceWith, { nested: { nestedKey: replaceWith, }, }, ]) }) it("should handle a string", () => { const target = "original" const replaceWith = "It's me" const result = walkObject(target, () => replaceWith) expect(result).toBe(replaceWith) }) it("should handle a number", () => { const target = 1 const replaceWith = "It's me" const result = walkObject(target, () => replaceWith) expect(result).toBe(replaceWith) }) })
9,905
0
petrpan-code/chakra-ui/chakra-ui/packages/utilities/lazy-utils
petrpan-code/chakra-ui/chakra-ui/packages/utilities/lazy-utils/tests/index.test.tsx
import { lazyDisclosure } from "../src" test("lazyDisclosure", () => { // when not lazy, tab panels are always rendered expect(lazyDisclosure({ enabled: false })).toBe(true) expect(lazyDisclosure({ enabled: false, isSelected: false })).toBe(true) expect(lazyDisclosure({ enabled: false, wasSelected: false })).toBe(true) expect( lazyDisclosure({ enabled: false, mode: "unmount", }), ).toBe(true) // when lazy and unmounting hidden panels, tab panels are only // rendered when selected expect(lazyDisclosure({ enabled: true, mode: "unmount" })).toBe(false) expect( lazyDisclosure({ enabled: true, mode: "keepMounted", wasSelected: true, isSelected: false, }), ).toBe(true) expect( lazyDisclosure({ enabled: true, mode: "unmount", isSelected: true, }), ).toBe(true) expect( lazyDisclosure({ enabled: true, mode: "unmount", isSelected: false, wasSelected: true, }), ).toBe(false) // when lazy and leaving hidden panels mounted, tab panels are only rendered // when selected or if they were previously selected expect(lazyDisclosure({ enabled: true, isSelected: true })).toBe(true) expect( lazyDisclosure({ enabled: true, isSelected: false, wasSelected: true, mode: "keepMounted", }), ).toBe(true) expect(lazyDisclosure({ enabled: true })).toBe(false) })
9,911
0
petrpan-code/chakra-ui/chakra-ui/packages/utilities/merge-utils
petrpan-code/chakra-ui/chakra-ui/packages/utilities/merge-utils/tests/index.test.ts
import { mergeWith } from "../src" describe("merge utils", () => { test("should work", () => { const result = mergeWith( { parts: ["a"], baseStyle: () => ({ bg: "red.200" }) }, { parts: ["b"], baseStyle: () => ({ color: "pink", bg: "red.500" }) }, ) expect(result.baseStyle({})).toMatchInlineSnapshot(` { "bg": "red.500", "color": "pink", } `) expect(result.parts).toMatchInlineSnapshot(` [ "a", "b", ] `) }) })
9,955
0
petrpan-code/chakra-ui/chakra-ui/packages/utilities/theme-utils
petrpan-code/chakra-ui/chakra-ui/packages/utilities/theme-utils/tests/extend-theme.test.tsx
import { extendTheme, ThemeOverride } from "../src/extend-theme" describe("extendTheme", () => { it("should override a color", () => { const testColor = "papayawhip" const override = { colors: { blue: { 50: testColor, }, }, } const customTheme = extendTheme(override) expect(customTheme.colors.blue[50]).toBe(testColor) }) it("should override component variant with a function result", () => { const testColor = "papayawhip" const override = { components: { Button: { variants: { solid: () => ({ bg: testColor, }), }, }, }, } const customTheme = extendTheme(override) const { variants, defaultProps } = customTheme.components.Button const solidStyles = variants.solid(defaultProps) expect(solidStyles.bg).toBe(testColor) // should have more properties from the default theme expect(Object.keys(solidStyles).length).toBeGreaterThan(1) }) it("should merge component baseStyle object with a function result", () => { const testColor = "papayawhip" const override = { components: { Button: { baseStyle: () => ({ bg: testColor, }), }, }, } const customTheme = extendTheme(override) const { baseStyle } = customTheme.components.Button const baseStyles = baseStyle() expect(baseStyles.bg).toBe(testColor) // should have more properties from the default theme expect(Object.keys(baseStyles).length).toBeGreaterThan(1) }) it("should override component variant with an object", () => { const testColor = "papayawhip" const override = { components: { Button: { variants: { solid: { bg: testColor, }, }, }, }, } const customTheme = extendTheme(override) const { variants, defaultProps } = customTheme.components.Button const solidStyles = variants.solid(defaultProps) expect(solidStyles.bg).toBe(testColor) // should have more properties from the default theme expect(Object.keys(solidStyles).length).toBeGreaterThan(1) }) it("should be able to extend a multipart component", () => { const override: ThemeOverride = { components: { Textarea: { defaultProps: { focusBorderColor: "green.200", }, }, }, } extendTheme(override) }) it("should pass typescript lint with random custom theme", () => { const override = { shadows: { outline: "0 0 0 3px rgb(0, 255, 0)", }, colors: { gray: { "300": "red", }, myCustomColor: { "50": "papayawhip", }, }, textStyles: { dl: { lineHeight: "tall", "dd + dt": { marginTop: "4", }, }, dt: { color: "gray.600", fontSize: "sm", fontWeight: "bold", }, dd: { color: "gray.800", }, }, config: { useSystemColorMode: false, initialColorMode: "dark" as const, }, styles: { global: { body: { color: "green.500", }, }, }, components: { Button: { variants: { ghost: { fontFamily: "mono", _active: { bg: "red", }, }, }, }, Input: { baseStyle: { field: { outline: "1px solid black", }, }, variants: { outline: () => ({ field: { bg: "green.500", }, }), myCustomVariant: { field: { bg: "red.500", }, }, }, }, }, } extendTheme(override) }) it("should pass typescript lint with non color hue properties", () => { const override: ThemeOverride = { colors: { grey: { 100: "#e3e3e3", 200: "#edf2f7", 300: "#e2e8f0", 400: "#cbd5e0", light: "#D4D4D4", medium: "#929292", dark: "#1D1D1B", navSubMenu: "#9F9F9F", special: { nestedColor: "#111", verySpecial: { 50: "#fff", deepNestedColor: "#111", }, }, }, white: "#fff", black: { 25: "rgba(0, 0, 0, 0.25)", 50: "rgba(0, 0, 0, 0.5)", 100: "#000", 150: "#1D1D1B", }, pink: { dark: "#FF8FA2", base: "#f6ced6", light: "#FAA4B3", lighter: "#F6CED6", }, }, } extendTheme(override) }) it("should have proper typings for ThemeProps callbacks", () => { const override: ThemeOverride = { components: { Button: { variants: { solid: ({ colorScheme }) => ({ borderColor: `${colorScheme}.600`, }), }, }, }, } extendTheme(override) }) it("should have proper typings for CSS Objects in sizes", () => { const override: ThemeOverride = { components: { Button: { sizes: { lg: { padding: "1.25rem 2rem", }, }, }, }, } extendTheme(override) }) it("should not extend with function that is inherited", () => { //@ts-ignore eslint-disable-next-line no-extend-native Array.prototype["customFunction"] = () => {} const override = { breakpoints: { sm: "1", md: "1", lg: "1", xl: "1", }, } const customTheme = extendTheme(override) // @ts-ignore delete Array.prototype["customFunction"] expect((customTheme.breakpoints as any).customFunction).toBeUndefined() }) it("should allow custom breakpoints", () => { const override = { breakpoints: { sm: "1px", md: "2px", lg: "3px", xl: "4px", phone: "5px", }, } const customTheme = extendTheme(override) expect(customTheme.breakpoints).toHaveProperty("sm") expect(customTheme.breakpoints).toHaveProperty("md") expect(customTheme.breakpoints).toHaveProperty("lg") expect(customTheme.breakpoints).toHaveProperty("xl") expect(customTheme.breakpoints).toHaveProperty("phone") }) })
9,956
0
petrpan-code/chakra-ui/chakra-ui/packages/utilities/theme-utils
petrpan-code/chakra-ui/chakra-ui/packages/utilities/theme-utils/tests/theme-extension.test.tsx
import { extendTheme, mergeThemeOverride, ThemeOverride } from "../src" describe("Theme Extension", () => { it("should be backwards compatible", () => { const theme = extendTheme({ colors: { brand: { 500: "#b4d455", }, }, }) expect(Object.keys(theme.components).length).toBeGreaterThan(1) expect(theme.colors.brand[500]).toBe("#b4d455") }) it("should allow userland extensions", () => { function withBrandColorExtension(colorName: string) { return (theme: ThemeOverride) => mergeThemeOverride(theme, { colors: { brand: theme.colors![colorName], }, }) } const customTheme = extendTheme(withBrandColorExtension("red")) expect(customTheme.colors.brand).toHaveProperty("500") }) it("should use a custom base theme", () => { const customBaseTheme = { borders: {}, breakpoints: { base: "0em" as const, }, colors: {}, components: {}, config: {}, direction: "ltr" as const, fonts: {}, fontSizes: {}, fontWeights: {}, letterSpacings: {}, lineHeights: {}, radii: {}, shadows: {}, sizes: {}, space: {}, styles: {}, transition: { duration: {}, easing: {}, property: {}, }, zIndices: {}, } const customTheme = extendTheme( { colors: { brand: { 500: "#b4d455", }, }, }, customBaseTheme, ) expect(customTheme.colors.brand).toHaveProperty("500") expect(Object.keys(customTheme.components)).toHaveLength(0) }) })
9,957
0
petrpan-code/chakra-ui/chakra-ui/packages/utilities/theme-utils
petrpan-code/chakra-ui/chakra-ui/packages/utilities/theme-utils/tests/with-default-color-scheme.test.tsx
import { theme as defaultTheme } from "@chakra-ui/theme" import { extendTheme, mergeThemeOverride, withDefaultColorScheme } from "../src" describe("Theme extension: withDefaultColorScheme", () => { it("should compose all extensions", () => { const theme = extendTheme( { colors: { brand: { 500: "#b4d455", }, }, }, withDefaultColorScheme({ colorScheme: "brand" }), ) expect(theme.components.Alert.defaultProps.colorScheme).toBe("brand") expect(Object.keys(theme.components).length).toBeGreaterThan(1) expect(theme.colors.brand[500]).toBe("#b4d455") }) it("should override from left to right", () => { const customTheme = extendTheme( withDefaultColorScheme({ colorScheme: "banana" }), withDefaultColorScheme({ colorScheme: "brand" }), { colors: { brand: { 500: "papayawhip", }, }, }, { colors: { brand: { 500: "#b4d455", }, }, components: { Alert: { defaultProps: { size: "lg", }, }, }, }, ) expect(customTheme.components.Alert.defaultProps.colorScheme).toBe("brand") expect(customTheme.components.Alert.defaultProps.size).toBe("lg") expect(Object.keys(customTheme.components).length).toBeGreaterThan(1) expect(customTheme.colors.brand[500]).toBe("#b4d455") }) it("should pass on the computed value", () => { const customTheme = extendTheme( (theme) => ({ ...theme, step1: "completed" }), (theme) => ({ ...theme, step1: "overridden", step2: theme.step1 }), ) expect(customTheme.step1).toBe("overridden") expect(customTheme.step2).toBe("completed") }) it("should allow overrides of default color scheme with extension", () => { const customTheme = extendTheme( withDefaultColorScheme({ colorScheme: "brand" }), (theme: typeof defaultTheme) => mergeThemeOverride(theme, { colors: { brand: theme.colors.red, }, components: { Alert: { defaultProps: { colorScheme: "blue", }, }, }, }), ) expect(customTheme.colors.brand).toHaveProperty("500") expect(customTheme.components.Badge.defaultProps.colorScheme).toBe("brand") expect(customTheme.components.Alert.defaultProps.colorScheme).toBe("blue") }) it("should allow overrides of default color scheme with override", () => { const customTheme = extendTheme( withDefaultColorScheme({ colorScheme: "brand" }), { colors: { brand: defaultTheme.colors.red, }, components: { Alert: { defaultProps: { colorScheme: "blue", }, }, }, }, ) expect(customTheme.colors.brand).toHaveProperty("500") expect(customTheme.components.Badge.defaultProps.colorScheme).toBe("brand") expect(customTheme.components.Alert.defaultProps.colorScheme).toBe("blue") }) it("should allow overrides only mentioned components", () => { const customTheme = extendTheme( withDefaultColorScheme({ colorScheme: "red", components: ["Button", "Badge"], }), withDefaultColorScheme({ colorScheme: "blue", components: ["Alert", "Table"], }), withDefaultColorScheme({ colorScheme: "blue", components: ["Container"], }), ) expect(customTheme.components.Button.defaultProps.colorScheme).toBe("red") expect(customTheme.components.Badge.defaultProps.colorScheme).toBe("red") expect(customTheme.components.Alert.defaultProps.colorScheme).toBe("blue") expect(customTheme.components.Table.defaultProps.colorScheme).toBe("blue") }) it("should override colorScheme of custom components", () => { const themeWithCustomComponent = { components: { MyCustomComponent: { defaultProps: { colorScheme: "purple", }, }, }, } const theme = extendTheme( themeWithCustomComponent, withDefaultColorScheme({ colorScheme: "brand" }), ) expect(theme.components.MyCustomComponent.defaultProps.colorScheme).toBe( "brand", ) }) })
9,958
0
petrpan-code/chakra-ui/chakra-ui/packages/utilities/theme-utils
petrpan-code/chakra-ui/chakra-ui/packages/utilities/theme-utils/tests/with-default-props.test.tsx
import { extendTheme, withDefaultProps } from "../src" describe("Theme extension: withDefaultProps", () => { it("should set a defaultProps", () => { const customTheme = extendTheme( withDefaultProps({ defaultProps: { colorScheme: "brand", size: "veryBig", variant: "my-custom-variant", }, }), ) expect(customTheme.components.Button.defaultProps.colorScheme).toBe("brand") expect(customTheme.components.Button.defaultProps.size).toBe("veryBig") expect(customTheme.components.Button.defaultProps.variant).toBe( "my-custom-variant", ) }) it("should allow overrides only mentioned components", () => { const customTheme = extendTheme( withDefaultProps({ defaultProps: { colorScheme: "brand", size: "veryBig", variant: "my-custom-variant", }, components: ["Button", "Badge"], }), ) expect(customTheme.components.Button.defaultProps.colorScheme).toBe("brand") expect(customTheme.components.Button.defaultProps.size).toBe("veryBig") expect(customTheme.components.Button.defaultProps.variant).toBe( "my-custom-variant", ) expect(customTheme.components.Tabs.defaultProps.colorScheme).not.toBe( "brand", ) expect(customTheme.components.Tabs.defaultProps.size).not.toBe("veryBig") expect(customTheme.components.Tabs.defaultProps.variant).not.toBe( "my-custom-variant", ) }) })
9,959
0
petrpan-code/chakra-ui/chakra-ui/packages/utilities/theme-utils
petrpan-code/chakra-ui/chakra-ui/packages/utilities/theme-utils/tests/with-default-size.test.tsx
import { extendTheme, withDefaultSize } from "../src" describe("Theme extension: withDefaultSize", () => { it("should set a defaultSize", () => { const customTheme = extendTheme(withDefaultSize({ size: "veryBig" })) expect(customTheme.components.Button.defaultProps.size).toBe("veryBig") }) it("should allow overrides only mentioned components", () => { const customTheme = extendTheme( withDefaultSize({ size: "veryBig", components: ["Button", "Badge"], }), ) expect(customTheme.components.Button.defaultProps.size).toBe("veryBig") expect(customTheme.components.Badge.defaultProps.size).toBe("veryBig") expect(customTheme.components.Alert.defaultProps.size).not.toBe("veryBig") }) })
9,960
0
petrpan-code/chakra-ui/chakra-ui/packages/utilities/theme-utils
petrpan-code/chakra-ui/chakra-ui/packages/utilities/theme-utils/tests/with-default-variant.test.tsx
import { extendTheme, withDefaultVariant } from "../src" describe("Theme extension: withDefaultVariant", () => { it("should set a defaultVariant", () => { const customTheme = extendTheme( withDefaultVariant({ variant: "my-custom-variant" }), ) expect(customTheme.components.Button.defaultProps.variant).toBe( "my-custom-variant", ) }) it("should allow overrides only mentioned components", () => { const customTheme = extendTheme( withDefaultVariant({ variant: "my-custom-variant", components: ["Button", "Badge"], }), ) expect(customTheme.components.Button.defaultProps.variant).toBe( "my-custom-variant", ) expect(customTheme.components.Badge.defaultProps.variant).toBe( "my-custom-variant", ) expect(customTheme.components.Alert.defaultProps.variant).not.toBe( "my-custom-variant", ) }) })
9,966
0
petrpan-code/chakra-ui/chakra-ui/plop/component
petrpan-code/chakra-ui/chakra-ui/plop/component/tests/{{componentName}}.test.tsx.hbs
/** * 📝 Notes for Contributors: * * - Ensure you write tests for component behavior defined in the hook. * - Ensure you write tests for the accessibility and interactions. * - No snapshot tests for components please! 🙂 * * @see Testing-Guide https://chakra-ui.com/guides/component-guide#4-build-and-test */ import { renderHook } from "@chakra-ui/test-utils"; import * as React from "react"; import { use{{capitalize componentName}} } from "../src"; describe("use{{capitalize componentName}}", () => { test("it works", () => { expect(true).toBeTruthy(); }); });
9,973
0
petrpan-code/chakra-ui/chakra-ui
petrpan-code/chakra-ui/chakra-ui/scripts/setup-test.ts
import "@testing-library/jest-dom" import React from "react" global.React = React const { getComputedStyle } = window window.getComputedStyle = (elt) => getComputedStyle(elt) window.Element.prototype.scrollTo = () => {} window.scrollTo = () => {} if (typeof window.matchMedia !== "function") { Object.defineProperty(window, "matchMedia", { enumerable: true, configurable: true, writable: true, value: jest.fn().mockImplementation((query) => ({ matches: false, media: query, onchange: null, addListener: jest.fn(), // Deprecated removeListener: jest.fn(), // Deprecated addEventListener: jest.fn(), removeEventListener: jest.fn(), dispatchEvent: jest.fn(), })), }) } // Workaround https://github.com/jsdom/jsdom/issues/2524#issuecomment-897707183 global.TextEncoder = require("util").TextEncoder global.ResizeObserver = jest.fn().mockImplementation(() => ({ observe: jest.fn(), unobserve: jest.fn(), disconnect: jest.fn(), }))
6
0
petrpan-code/chakra-ui/chakra-ui/tooling/cli
petrpan-code/chakra-ui/chakra-ui/tooling/cli/test/extract-component-types.test.ts
import { extractComponentTypes } from "../src/command/tokens/extract-component-types" describe("Extract Component Types", () => { it("should extract all component types", () => { const theme = { components: { TestComponent: { variants: { outline: {}, unstyled: {}, }, }, }, } const componentTypes = extractComponentTypes(theme) expect(componentTypes).toMatchInlineSnapshot(` { "TestComponent": { "sizes": [], "variants": [ "outline", "unstyled", ], }, } `) }) it("should handle empty variants or sizes", () => { const theme = { components: { TestComponent: {}, }, } const componentTypes = extractComponentTypes(theme) expect(componentTypes).toMatchInlineSnapshot(` { "TestComponent": { "sizes": [], "variants": [], }, } `) }) it("should handle arbitrary component names", () => { const theme = { components: { "design-system/Button": {}, "design-system_Button": {}, }, } const componentTypes = extractComponentTypes(theme) expect(componentTypes).toMatchInlineSnapshot(` { "design-system/Button": { "sizes": [], "variants": [], }, "design-system_Button": { "sizes": [], "variants": [], }, } `) }) })
7
0
petrpan-code/chakra-ui/chakra-ui/tooling/cli
petrpan-code/chakra-ui/chakra-ui/tooling/cli/test/extract-property-keys.test.ts
import { extractPropertyKeys } from "../src/command/tokens/extract-property-keys" describe("Extract Property Keys", () => { it("should extract top-level keys from the given property", () => { const theme = { textStyles: { styleOne: { fontSize: 16, fontWeight: "bold", }, styleTwo: { fontSize: 64, }, }, } const textStyles = extractPropertyKeys(theme, "textStyles") expect(textStyles).toMatchInlineSnapshot(` [ "styleOne", "styleTwo", ] `) }) it("should handle empty entries", () => { const theme = { textStyles: { emptyStyle: {}, }, } const componentTypes = extractPropertyKeys(theme, "textStyles") expect(componentTypes).toMatchInlineSnapshot(` [ "emptyStyle", ] `) }) it("should handle missing properties", () => { const theme = {} const textStyles = extractPropertyKeys(theme, "textStyles") expect(textStyles).toMatchInlineSnapshot(`[]`) }) })
8
0
petrpan-code/chakra-ui/chakra-ui/tooling/cli
petrpan-code/chakra-ui/chakra-ui/tooling/cli/test/extract-property-paths.test.ts
import { extractPropertyPaths, printUnionMap, } from "../src/command/tokens/extract-property-paths" describe("Extract Property Paths", () => { const target = { 1: { 11: { 111: "", 112: "", }, 12: { 121: "", 122: "", 123: { 231: "", 232: "", }, }, }, 2: { 21: "", 22: "", }, } it("should extract all property paths", () => { const maxDepth = 4 const propertyPaths = extractPropertyPaths(target, maxDepth) expect(propertyPaths).toMatchInlineSnapshot(` [ "1.11.111", "1.11.112", "1.12.121", "1.12.122", "1.12.123.231", "1.12.123.232", "2.21", "2.22", ] `) }) it("should omit too deep keys", () => { const maxDepth = 3 const propertyPaths = extractPropertyPaths(target, maxDepth) expect(propertyPaths).toMatchInlineSnapshot(` [ "1.11.111", "1.11.112", "1.12.121", "1.12.122", "2.21", "2.22", ] `) }) it("should print TS union", () => { const union = { key: ["value1", "value2"] } const strict = false const interfacePartial = printUnionMap(union, strict) expect(interfacePartial).toMatchInlineSnapshot( `"key: "value1" | "value2" | (string & {});"`, ) }) it("should print strict TS union", () => { const union = { key: ["value1", "value2"] } const strict = true const interfacePartial = printUnionMap(union, strict) expect(interfacePartial).toMatchInlineSnapshot( `"key: "value1" | "value2";"`, ) }) it("should print type (string & {}) for empty array", () => { const union = { key: [] } const strict = false const interfacePartial = printUnionMap(union, strict) expect(interfacePartial).toMatchInlineSnapshot(`"key: (string & {});"`) }) it("should print type never for empty array in strict mode", () => { const union = { key: [] } const strict = true const interfacePartial = printUnionMap(union, strict) expect(interfacePartial).toMatchInlineSnapshot(`"key: never;"`) }) })
9
0
petrpan-code/chakra-ui/chakra-ui/tooling/cli
petrpan-code/chakra-ui/chakra-ui/tooling/cli/test/extract-semantic-token-keys.test.ts
import { extractSemanticTokenKeys } from "../src/command/tokens/extract-semantic-token-keys" describe("Extract Semantic Token Keys", () => { it("should extract semantic token keys from the given property", () => { const theme = { colors: { green: { 500: "#38A169", }, red: { 100: "#ff0010", 400: "#ff0040", 500: "#ff0050", 700: "#ff0070", 800: "#ff0080", }, }, semanticTokens: { colors: { primary: { default: "red.500", _dark: "red.400", }, secondary: { default: "red.800", _dark: "red.700", }, error: "red.500", success: "green.500", background: { green: { normal: "green.500", }, }, text: { green: { default: "green.500", }, red: { bold: { default: "red.800", _dark: "red.700", }, subtle: { default: "red.500", _dark: "red.400", }, }, }, }, }, } const semanticTokenKeys = extractSemanticTokenKeys(theme, "colors") expect(semanticTokenKeys).toMatchInlineSnapshot(` [ "primary", "secondary", "error", "success", "background.green.normal", "text.green", "text.red.bold", "text.red.subtle", ] `) }) it("should handle empty entries", () => { const theme = { semanticTokens: { colors: { emptyColors: {}, }, }, } const semanticTokenKeys = extractSemanticTokenKeys(theme, "colors") expect(semanticTokenKeys).toMatchInlineSnapshot(`[]`) }) it("should handle missing properties", () => { const theme = {} const semanticTokenKeys = extractSemanticTokenKeys(theme, "colors") expect(semanticTokenKeys).toMatchInlineSnapshot(`[]`) }) })
10
0
petrpan-code/chakra-ui/chakra-ui/tooling/cli
petrpan-code/chakra-ui/chakra-ui/tooling/cli/test/format-with-prettier.test.ts
import { formatWithPrettier } from "../src/utils/format-with-prettier" describe("Format With Prettier", () => { it("should format with prettier", async () => { const content = "export interface ThemeTypings { fonts: 'test1'|'test2'|'test3'}" const pretty = await formatWithPrettier(content) expect(pretty).toMatchInlineSnapshot(` "export interface ThemeTypings { fonts: "test1" | "test2" | "test3" } " `) }) })
11
0
petrpan-code/chakra-ui/chakra-ui/tooling/cli
petrpan-code/chakra-ui/chakra-ui/tooling/cli/test/theme-typings.test.ts
import { createThemeTypingsInterface } from "../src/command/tokens/create-theme-typings-interface" import { themeKeyConfiguration } from "../src/command/tokens/config" const defaultRecord = { sm: "", md: "", } const smallTheme: Record<string, unknown> = { colors: { niceColor: "", suchWowColor: "", onlyColorSchemeColor: { 50: "", 100: "", 200: "", 300: "", 400: "", 500: "", 600: "", 700: "", 800: "", 900: "", }, such: { deep: { color: "", }, }, }, components: { Button: { variants: { extraordinary: {}, awesome: {}, unused: {}, }, sizes: { sm: "", }, }, }, textStyles: { small: { fontSize: 16, }, large: { fontSize: 64, fontWeight: "bold", }, }, layerStyles: { red: { background: "#ff0000", }, blue: { background: "#0000ff", }, }, letterSpacings: defaultRecord, lineHeights: defaultRecord, fontWeights: defaultRecord, fonts: defaultRecord, fontSizes: defaultRecord, breakpoints: defaultRecord, zIndices: defaultRecord, radii: defaultRecord, sizes: defaultRecord, shadows: defaultRecord, space: defaultRecord, borders: defaultRecord, transition: defaultRecord, styles: {}, config: {}, } describe("Theme typings", () => { it("should create typings for a theme", async () => { const themeInterface = await createThemeTypingsInterface(smallTheme, { config: themeKeyConfiguration, }) expect(themeInterface).toMatchInlineSnapshot(` "// regenerate by running // npx @chakra-ui/cli tokens path/to/your/theme.(js|ts) import { BaseThemeTypings } from "./shared.types.js" export interface ThemeTypings extends BaseThemeTypings { blur: string & {} borders: "sm" | "md" | (string & {}) borderStyles: string & {} borderWidths: string & {} breakpoints: "sm" | "md" | (string & {}) colors: | "niceColor" | "suchWowColor" | "onlyColorSchemeColor.50" | "onlyColorSchemeColor.100" | "onlyColorSchemeColor.200" | "onlyColorSchemeColor.300" | "onlyColorSchemeColor.400" | "onlyColorSchemeColor.500" | "onlyColorSchemeColor.600" | "onlyColorSchemeColor.700" | "onlyColorSchemeColor.800" | "onlyColorSchemeColor.900" | "such.deep.color" | (string & {}) colorSchemes: "onlyColorSchemeColor" | (string & {}) fonts: "sm" | "md" | (string & {}) fontSizes: "sm" | "md" | (string & {}) fontWeights: "sm" | "md" | (string & {}) layerStyles: "red" | "blue" | (string & {}) letterSpacings: "sm" | "md" | (string & {}) lineHeights: "sm" | "md" | (string & {}) radii: "sm" | "md" | (string & {}) shadows: "sm" | "md" | (string & {}) sizes: "sm" | "md" | (string & {}) space: "sm" | "-sm" | "md" | "-md" | (string & {}) textStyles: "small" | "large" | (string & {}) transition: "sm" | "md" | (string & {}) zIndices: "sm" | "md" | (string & {}) components: { Button: { sizes: "sm" | (string & {}) variants: "extraordinary" | "awesome" | "unused" | (string & {}) } } } " `) }) it("should emit empty scales as loose type", async () => { const themeInterface = await createThemeTypingsInterface( {}, { config: themeKeyConfiguration, }, ) expect(themeInterface).toMatchInlineSnapshot(` "// regenerate by running // npx @chakra-ui/cli tokens path/to/your/theme.(js|ts) import { BaseThemeTypings } from "./shared.types.js" export interface ThemeTypings extends BaseThemeTypings { blur: string & {} borders: string & {} borderStyles: string & {} borderWidths: string & {} breakpoints: string & {} colors: string & {} colorSchemes: string & {} fonts: string & {} fontSizes: string & {} fontWeights: string & {} layerStyles: string & {} letterSpacings: string & {} lineHeights: string & {} radii: string & {} shadows: string & {} sizes: string & {} space: string & {} textStyles: string & {} transition: string & {} zIndices: string & {} components: {} } " `) }) it("should emit strict component types", async () => { const themeInterface = await createThemeTypingsInterface(smallTheme, { config: themeKeyConfiguration, strictComponentTypes: true, }) expect(themeInterface).toMatchInlineSnapshot(` "// regenerate by running // npx @chakra-ui/cli tokens path/to/your/theme.(js|ts) import { BaseThemeTypings } from "./shared.types.js" export interface ThemeTypings extends BaseThemeTypings { blur: string & {} borders: "sm" | "md" | (string & {}) borderStyles: string & {} borderWidths: string & {} breakpoints: "sm" | "md" | (string & {}) colors: | "niceColor" | "suchWowColor" | "onlyColorSchemeColor.50" | "onlyColorSchemeColor.100" | "onlyColorSchemeColor.200" | "onlyColorSchemeColor.300" | "onlyColorSchemeColor.400" | "onlyColorSchemeColor.500" | "onlyColorSchemeColor.600" | "onlyColorSchemeColor.700" | "onlyColorSchemeColor.800" | "onlyColorSchemeColor.900" | "such.deep.color" | (string & {}) colorSchemes: "onlyColorSchemeColor" | (string & {}) fonts: "sm" | "md" | (string & {}) fontSizes: "sm" | "md" | (string & {}) fontWeights: "sm" | "md" | (string & {}) layerStyles: "red" | "blue" | (string & {}) letterSpacings: "sm" | "md" | (string & {}) lineHeights: "sm" | "md" | (string & {}) radii: "sm" | "md" | (string & {}) shadows: "sm" | "md" | (string & {}) sizes: "sm" | "md" | (string & {}) space: "sm" | "-sm" | "md" | "-md" | (string & {}) textStyles: "small" | "large" | (string & {}) transition: "sm" | "md" | (string & {}) zIndices: "sm" | "md" | (string & {}) components: { Button: { sizes: "sm" variants: "extraordinary" | "awesome" | "unused" } } } " `) }) it("should create unformatted types", async () => { const themeInterface = await createThemeTypingsInterface(smallTheme, { config: themeKeyConfiguration, format: false, }) expect(themeInterface).toMatchInlineSnapshot(` "// regenerate by running // npx @chakra-ui/cli tokens path/to/your/theme.(js|ts) import { BaseThemeTypings } from "./shared.types.js" export interface ThemeTypings extends BaseThemeTypings { blur: (string & {}); borders: "sm" | "md" | (string & {}); borderStyles: (string & {}); borderWidths: (string & {}); breakpoints: "sm" | "md" | (string & {}); colors: "niceColor" | "suchWowColor" | "onlyColorSchemeColor.50" | "onlyColorSchemeColor.100" | "onlyColorSchemeColor.200" | "onlyColorSchemeColor.300" | "onlyColorSchemeColor.400" | "onlyColorSchemeColor.500" | "onlyColorSchemeColor.600" | "onlyColorSchemeColor.700" | "onlyColorSchemeColor.800" | "onlyColorSchemeColor.900" | "such.deep.color" | (string & {}); colorSchemes: "onlyColorSchemeColor" | (string & {}); fonts: "sm" | "md" | (string & {}); fontSizes: "sm" | "md" | (string & {}); fontWeights: "sm" | "md" | (string & {}); layerStyles: "red" | "blue" | (string & {}); letterSpacings: "sm" | "md" | (string & {}); lineHeights: "sm" | "md" | (string & {}); radii: "sm" | "md" | (string & {}); shadows: "sm" | "md" | (string & {}); sizes: "sm" | "md" | (string & {}); space: "sm" | "-sm" | "md" | "-md" | (string & {}); textStyles: "small" | "large" | (string & {}); transition: "sm" | "md" | (string & {}); zIndices: "sm" | "md" | (string & {}); components: { Button: { sizes: "sm" | (string & {}); variants: "extraordinary" | "awesome" | "unused" | (string & {}); } } } " `) }) it("should include semantic tokens", async () => { const themeInterface = await createThemeTypingsInterface( { colors: { gray: { 50: "lightgray", 500: "gray", 900: "darkgray", }, red: { 400: "lightred", 500: "red", }, }, semanticTokens: { colors: { text: { default: "gray.900", _dark: "gray.50", }, background: { red: { default: "red.500", _dark: "red.400", }, gray: { default: "gray.500", _light: "gray.900", }, }, "feedback.error": { default: "red.500", _dark: "red.400", }, }, }, }, { config: themeKeyConfiguration, }, ) expect(themeInterface).toMatchInlineSnapshot(` "// regenerate by running // npx @chakra-ui/cli tokens path/to/your/theme.(js|ts) import { BaseThemeTypings } from "./shared.types.js" export interface ThemeTypings extends BaseThemeTypings { blur: string & {} borders: string & {} borderStyles: string & {} borderWidths: string & {} breakpoints: string & {} colors: | "gray.50" | "gray.500" | "gray.900" | "red.400" | "red.500" | "text" | "background.red" | "background.gray" | "feedback.error" | (string & {}) colorSchemes: string & {} fonts: string & {} fontSizes: string & {} fontWeights: string & {} layerStyles: string & {} letterSpacings: string & {} lineHeights: string & {} radii: string & {} shadows: string & {} sizes: string & {} space: string & {} textStyles: string & {} transition: string & {} zIndices: string & {} components: {} } " `) }) it("should emit strict token types", async () => { const themeInterface = await createThemeTypingsInterface(smallTheme, { config: themeKeyConfiguration, strictTokenTypes: true, }) expect(themeInterface).toMatchInlineSnapshot(` "// regenerate by running // npx @chakra-ui/cli tokens path/to/your/theme.(js|ts) import { BaseThemeTypings } from "./shared.types.js" export interface ThemeTypings extends BaseThemeTypings { blur: never borders: "sm" | "md" borderStyles: never borderWidths: never breakpoints: "sm" | "md" colors: | "niceColor" | "suchWowColor" | "onlyColorSchemeColor.50" | "onlyColorSchemeColor.100" | "onlyColorSchemeColor.200" | "onlyColorSchemeColor.300" | "onlyColorSchemeColor.400" | "onlyColorSchemeColor.500" | "onlyColorSchemeColor.600" | "onlyColorSchemeColor.700" | "onlyColorSchemeColor.800" | "onlyColorSchemeColor.900" | "such.deep.color" colorSchemes: "onlyColorSchemeColor" fonts: "sm" | "md" fontSizes: "sm" | "md" fontWeights: "sm" | "md" layerStyles: "red" | "blue" letterSpacings: "sm" | "md" lineHeights: "sm" | "md" radii: "sm" | "md" shadows: "sm" | "md" sizes: "sm" | "md" space: "sm" | "-sm" | "md" | "-md" textStyles: "small" | "large" transition: "sm" | "md" zIndices: "sm" | "md" components: { Button: { sizes: "sm" | (string & {}) variants: "extraordinary" | "awesome" | "unused" | (string & {}) } } } " `) }) it("should emit strict component and token types", async () => { const themeInterface = await createThemeTypingsInterface(smallTheme, { config: themeKeyConfiguration, strictComponentTypes: true, strictTokenTypes: true, }) expect(themeInterface).toMatchInlineSnapshot(` "// regenerate by running // npx @chakra-ui/cli tokens path/to/your/theme.(js|ts) import { BaseThemeTypings } from "./shared.types.js" export interface ThemeTypings extends BaseThemeTypings { blur: never borders: "sm" | "md" borderStyles: never borderWidths: never breakpoints: "sm" | "md" colors: | "niceColor" | "suchWowColor" | "onlyColorSchemeColor.50" | "onlyColorSchemeColor.100" | "onlyColorSchemeColor.200" | "onlyColorSchemeColor.300" | "onlyColorSchemeColor.400" | "onlyColorSchemeColor.500" | "onlyColorSchemeColor.600" | "onlyColorSchemeColor.700" | "onlyColorSchemeColor.800" | "onlyColorSchemeColor.900" | "such.deep.color" colorSchemes: "onlyColorSchemeColor" fonts: "sm" | "md" fontSizes: "sm" | "md" fontWeights: "sm" | "md" layerStyles: "red" | "blue" letterSpacings: "sm" | "md" lineHeights: "sm" | "md" radii: "sm" | "md" shadows: "sm" | "md" sizes: "sm" | "md" space: "sm" | "-sm" | "md" | "-md" textStyles: "small" | "large" transition: "sm" | "md" zIndices: "sm" | "md" components: { Button: { sizes: "sm" variants: "extraordinary" | "awesome" | "unused" } } } " `) }) it("should create typings for a theme for interface augmentation", async () => { const themeInterface = await createThemeTypingsInterface(smallTheme, { config: themeKeyConfiguration, template: "augmentation", }) expect(themeInterface).toMatchInlineSnapshot(` "// regenerate by running // npx @chakra-ui/cli tokens path/to/your/theme.(js|ts) --template augmentation --out path/to/this/file import { BaseThemeTypings } from "@chakra-ui/styled-system" declare module "@chakra-ui/styled-system" { export interface CustomThemeTypings extends BaseThemeTypings { blur: string & {} borders: "sm" | "md" | (string & {}) borderStyles: string & {} borderWidths: string & {} breakpoints: "sm" | "md" | (string & {}) colors: | "niceColor" | "suchWowColor" | "onlyColorSchemeColor.50" | "onlyColorSchemeColor.100" | "onlyColorSchemeColor.200" | "onlyColorSchemeColor.300" | "onlyColorSchemeColor.400" | "onlyColorSchemeColor.500" | "onlyColorSchemeColor.600" | "onlyColorSchemeColor.700" | "onlyColorSchemeColor.800" | "onlyColorSchemeColor.900" | "such.deep.color" | (string & {}) colorSchemes: "onlyColorSchemeColor" | (string & {}) fonts: "sm" | "md" | (string & {}) fontSizes: "sm" | "md" | (string & {}) fontWeights: "sm" | "md" | (string & {}) layerStyles: "red" | "blue" | (string & {}) letterSpacings: "sm" | "md" | (string & {}) lineHeights: "sm" | "md" | (string & {}) radii: "sm" | "md" | (string & {}) shadows: "sm" | "md" | (string & {}) sizes: "sm" | "md" | (string & {}) space: "sm" | "-sm" | "md" | "-md" | (string & {}) textStyles: "small" | "large" | (string & {}) transition: "sm" | "md" | (string & {}) zIndices: "sm" | "md" | (string & {}) components: { Button: { sizes: "sm" | (string & {}) variants: "extraordinary" | "awesome" | "unused" | (string & {}) } } } } " `) }) })
25
0
petrpan-code/chakra-ui/chakra-ui/tooling/cra-template-typescript/template
petrpan-code/chakra-ui/chakra-ui/tooling/cra-template-typescript/template/src/App.test.tsx
import React from "react" import { screen } from "@testing-library/react" import { render } from "./test-utils" import { App } from "./App" test("renders learn react link", () => { render(<App />) const linkElement = screen.getByText(/learn chakra/i) expect(linkElement).toBeInTheDocument() })
1,147
0
petrpan-code/jaredpalmer/formik
petrpan-code/jaredpalmer/formik/e2e/basic.test.ts
import { test, expect } from '@playwright/test'; test('should validate before submit', async ({ page }) => { await page.goto('/basic'); // Submit the form await page.click('button[type=submit]'); // Check that all fields are touched and error messages work expect(await page.textContent('input[name="firstName"] + p')).toContain( 'Required' ); expect(await page.textContent('input[name="lastName"] + p')).toContain( 'Required' ); expect(await page.textContent('input[name="email"] + p')).toContain( 'Required' ); expect(await page.textContent('#renderCounter')).toContain('0'); }); test('should validate show errors on change and blur', async ({ page }) => { await page.goto('/sign-in'); await page.fill('input[name="username"]', 'john'); await page.locator('input[name="username"]').blur(); expect( await page.locator('input[name="username"] + p').textContent.length ).toEqual(1); await page.fill('input[name="password"]', '123'); await page.locator('input[name="password"]').blur(); expect( await page.locator('input[name="password"] + p').textContent.length ).toEqual(1); expect(await page.textContent('#error-log')).toContain('[]'); }); test('should validate show errors on blur only', async ({ page }) => { await page.goto('/sign-in?validateOnMount=false&validateOnChange=false'); await page.fill('input[name="username"]', 'john'); await page.locator('input[name="username"]').blur(); expect( await page.locator('input[name="username"] + p').textContent.length ).toEqual(1); await page.fill('input[name="password"]', '123'); await page.locator('input[name="password"]').blur(); expect( await page.locator('input[name="password"] + p').textContent.length ).toEqual(1); expect(await page.textContent('#error-log')).toContain( JSON.stringify( [ // It will quickly flash after `password` blur because `yup` schema // validation is async. { name: 'password', value: '123', error: 'Required' }, ], null, 2 ) ); }); test('should validate autofill', async ({ page }) => { // React overrides `input.value` setters, so we have to call // native input setter // See: https://stackoverflow.com/a/46012210/1709679 const setInputValue = async (selector, value) => { await page.$eval(selector, (el, value) => (el.value = value), value); await page.dispatchEvent(selector, 'change'); }; await page.goto('/sign-in'); await setInputValue('input[name="username"]', '123'); await setInputValue('input[name="password"]', '123'); const buttonIsDisabled = await page.$eval( 'button', button => button.disabled ); expect(buttonIsDisabled).toBe(false); });
1,206
0
petrpan-code/jaredpalmer/formik/packages/formik-native
petrpan-code/jaredpalmer/formik/packages/formik-native/test/blah.test.ts
describe('blah', () => { it('works', () => { expect(1).toEqual(1); }); });
1,224
0
petrpan-code/jaredpalmer/formik/packages/formik
petrpan-code/jaredpalmer/formik/packages/formik/test/ErrorMessage.test.tsx
import * as React from 'react'; import { act, render } from '@testing-library/react'; import { Formik, FormikProps, ErrorMessage } from '../src'; import { noop } from './testHelpers'; interface TestFormValues { name: string; email: string; } const TestForm: React.FC<any> = p => ( <Formik onSubmit={noop} initialValues={{ name: 'jared', email: '[email protected]' }} {...p} /> ); fdescribe('<ErrorMessage />', () => { it('renders with children as a function', async () => { let actual: any; /** ErrorMessage ;) */ let actualFProps: any; let message = 'Wrong'; render( <TestForm render={(fProps: FormikProps<TestFormValues>) => { actualFProps = fProps; return ( <div> <ErrorMessage name="email"> {props => (actual = props) || <div>{props}</div>} </ErrorMessage> </div> ); }} /> ); await act(async () => { await actualFProps.setFieldError('email', message); }); // Only renders if Field has been visited. expect(actual).toEqual(undefined); await act(async () => { await actualFProps.setFieldTouched('email'); await actualFProps.setFieldError('email', message); }); // Renders after being visited with an error. expect(actual).toEqual(message); }); });
1,225
0
petrpan-code/jaredpalmer/formik/packages/formik
petrpan-code/jaredpalmer/formik/packages/formik/test/Field.test.tsx
import * as React from 'react'; import { act, cleanup, render, waitFor, fireEvent, } from '@testing-library/react'; import * as Yup from 'yup'; import { Formik, Field, FastField, FieldProps, FieldConfig, FormikProps, FormikConfig, } from '../src'; import { noop } from './testHelpers'; const initialValues = { name: 'jared', email: '[email protected]' }; type Values = typeof initialValues; type FastFieldConfig = FieldConfig; type $FixMe = any; function renderForm( ui?: React.ReactNode, props?: Partial<FormikConfig<Values>> ) { let injected: FormikProps<Values>; const { rerender, ...rest } = render( <Formik onSubmit={noop} initialValues={initialValues} {...props}> {(formikProps: FormikProps<Values>) => (injected = formikProps) && ui ? ui : null } </Formik> ); return { getFormProps(): FormikProps<Values> { return injected; }, ...rest, rerender: () => rerender( <Formik onSubmit={noop} initialValues={initialValues} {...props}> {(formikProps: FormikProps<Values>) => (injected = formikProps) && ui ? ui : null } </Formik> ), }; } const createRenderField = ( FieldComponent: React.ComponentType<FieldConfig> ) => ( props: Partial<FieldConfig> | Partial<FastFieldConfig> = {}, formProps?: Partial<FormikConfig<Values>> ) => { let injected: FieldProps; if (!props.children && !props.render && !props.component && !props.as) { props.children = (fieldProps: FieldProps) => (injected = fieldProps) && ( <input {...fieldProps.field} name="name" data-testid="name-input" /> ); } return { getProps() { return injected; }, ...renderForm( <FieldComponent name="name" data-testid="name-input" {...props} />, formProps ), }; }; const renderField = createRenderField(Field); const renderFastField = createRenderField(FastField); function cases( title: string, tester: (arg: typeof renderField | typeof renderFastField) => void ) { describe(title, () => { it('<FastField />', async () => await tester(renderFastField)); it('<Field />', async () => await tester(renderField)); }); } const TEXT = 'Mrs. Kato'; describe('Field / FastField', () => { afterEach(cleanup); describe('renders an <input /> by default', () => { it('<Field />', () => { const className = 'field-custom' const { container } = renderForm(<Field name="name" className={className} />); expect(container.querySelectorAll('input')).toHaveLength(1); expect(container.querySelector(`.${className}`)?.getAttribute('value')).toEqual('jared') }); it('<FastField />', () => { const { container } = renderForm(<FastField name="name" />); expect(container.querySelectorAll('input')).toHaveLength(1); }); }); describe('renders an <input /> with className', () => { it('<Field />', () => { const className = 'field-custom' const { container } = renderForm(<Field name="name" className={className} />); expect(container.querySelectorAll(`.${className}`)).toHaveLength(1) expect(container.querySelector(`.${className}`)?.getAttribute('value')).toEqual('jared') }); it('<FastField />', () => { const className = 'field-custom' const { container } = renderForm(<FastField name="name" className={className} />); expect(container.querySelectorAll(`.${className}`)).toHaveLength(1) expect(container.querySelector(`.${className}`)?.getAttribute('value')).toEqual('jared') }); }); describe('receives { field, form, meta } props and renders element', () => { it('<Field />', () => { let injected: FieldProps[] = []; let asInjectedProps: FieldProps['field'] = {} as any; const Component = (props: FieldProps) => injected.push(props) && <div data-testid="child">{TEXT}</div>; const AsComponent = (props: FieldProps['field']) => (asInjectedProps = props) && <div data-testid="child">{TEXT}</div>; const { getFormProps, queryAllByText } = renderForm( <> <Field name="name" children={Component} /> <Field name="name" render={Component} /> <Field name="name" component={Component} /> <Field name="name" as={AsComponent} /> </> ); const { handleBlur, handleChange } = getFormProps(); injected.forEach((props, idx) => { expect(props.field.name).toBe('name'); expect(props.field.value).toBe('jared'); expect(props.field.onChange).toBe(handleChange); expect(props.field.onBlur).toBe(handleBlur); expect(props.form).toEqual(getFormProps()); if (idx !== 2) { expect(props.meta.value).toBe('jared'); expect(props.meta.error).toBeUndefined(); expect(props.meta.touched).toBe(false); expect(props.meta.initialValue).toEqual('jared'); } else { // Ensure that we do not pass through `meta` to // <Field component> or <Field render> expect(props.meta).toBeUndefined(); } }); expect(asInjectedProps.name).toBe('name'); expect(asInjectedProps.value).toBe('jared'); expect(asInjectedProps.onChange).toBe(handleChange); expect(asInjectedProps.onBlur).toBe(handleBlur); expect(queryAllByText(TEXT)).toHaveLength(4); }); it('<FastField />', () => { let injected: FieldProps[] = []; let asInjectedProps: FieldProps['field'] = {} as any; const Component = (props: FieldProps) => injected.push(props) && <div>{TEXT}</div>; const AsComponent = (props: FieldProps['field']) => (asInjectedProps = props) && <div data-testid="child">{TEXT}</div>; const { getFormProps, queryAllByText } = renderForm( <> <FastField name="name" children={Component} /> <FastField name="name" render={Component} /> {/* @todo fix the types here?? #shipit */} <FastField name="name" component={Component as $FixMe} /> <FastField name="name" as={AsComponent} /> </> ); const { handleBlur, handleChange } = getFormProps(); injected.forEach((props, idx) => { expect(props.field.name).toBe('name'); expect(props.field.value).toBe('jared'); expect(props.field.onChange).toBe(handleChange); expect(props.field.onBlur).toBe(handleBlur); expect(props.form).toEqual(getFormProps()); if (idx !== 2) { expect(props.meta.value).toBe('jared'); expect(props.meta.error).toBeUndefined(); expect(props.meta.touched).toBe(false); expect(props.meta.initialValue).toEqual('jared'); } else { // Ensure that we do not pass through `meta` to // <Field component> or <Field render> expect(props.meta).toBeUndefined(); } }); expect(asInjectedProps.name).toBe('name'); expect(asInjectedProps.value).toBe('jared'); expect(asInjectedProps.onChange).toBe(handleChange); expect(asInjectedProps.onBlur).toBe(handleBlur); expect(queryAllByText(TEXT)).toHaveLength(4); }); }); describe('children', () => { cases('renders a child element with component', () => { const { container } = renderForm( <Field name="name" component="select"> <option value="Jared" label={TEXT} /> <option value="Brent" label={TEXT} /> </Field> ); expect(container.querySelectorAll('option')).toHaveLength(2); }); cases('renders a child element with as', () => { const { container } = renderForm( <Field name="name" as="select"> <option value="Jared" label={TEXT} /> <option value="Brent" label={TEXT} /> </Field> ); expect(container.querySelectorAll('option')).toHaveLength(2); }); }); describe('component', () => { cases('renders string components', renderField => { const { container } = renderField({ component: 'textarea', }); expect((container.firstChild as $FixMe).type).toBe('textarea'); }); cases('assigns innerRef as a ref to string components', renderField => { const innerRef = jest.fn(); const { container } = renderField({ innerRef, component: 'input', }); expect(innerRef).toHaveBeenCalledWith(container.firstChild); }); cases('forwards innerRef to React component', renderField => { let injected: any; /** FieldProps ;) */ const Component = (props: FieldProps) => (injected = props) && null; const innerRef = jest.fn(); renderField({ component: Component, innerRef }); expect(injected.innerRef).toBe(innerRef); }); }); describe('as', () => { cases('renders string components', renderField => { const { container } = renderField({ as: 'textarea', }); expect((container.firstChild as $FixMe).type).toBe('textarea'); }); cases('assigns innerRef as a ref to string components', renderField => { const innerRef = jest.fn(); const { container } = renderField({ innerRef, as: 'input', }); expect(innerRef).toHaveBeenCalledWith(container.firstChild); }); cases('forwards innerRef to React component', renderField => { let injected: any; /** FieldProps ;) */ const Component = (props: FieldProps['field']) => (injected = props) && null; const innerRef = jest.fn(); renderField({ as: Component, innerRef }); expect(injected.innerRef).toBe(innerRef); }); }); describe('validate', () => { cases('calls validate during onChange if present', async renderField => { const validate = jest.fn(); const { getByTestId, rerender } = renderField({ validate, component: 'input', }); rerender(); fireEvent.change(getByTestId('name-input'), { target: { name: 'name', value: 'hello' }, }); rerender(); await waitFor(() => { expect(validate).toHaveBeenCalled(); }); }); cases( 'does NOT call validate during onChange if validateOnChange is set to false', async renderField => { const validate = jest.fn(); const { getByTestId, rerender } = renderField( { validate, component: 'input' }, { validateOnChange: false } ); rerender(); fireEvent.change(getByTestId('name-input'), { target: { name: 'name', value: 'hello' }, }); rerender(); await waitFor(() => { expect(validate).not.toHaveBeenCalled(); }); } ); cases('calls validate during onBlur if present', async renderField => { const validate = jest.fn(); const { getByTestId, rerender } = renderField({ validate, component: 'input', }); rerender(); fireEvent.blur(getByTestId('name-input'), { target: { name: 'name' }, }); rerender(); await waitFor(() => { expect(validate).toHaveBeenCalled(); }); }); cases( 'does NOT call validate during onBlur if validateOnBlur is set to false', async renderField => { const validate = jest.fn(); const { getByTestId, rerender } = renderField( { validate, component: 'input' }, { validateOnBlur: false } ); rerender(); fireEvent.blur(getByTestId('name-input'), { target: { name: 'name' }, }); rerender(); await waitFor(() => expect(validate).not.toHaveBeenCalled()); } ); cases( 'runs validation when validateField is called (SYNC)', async renderField => { const validate = jest.fn(() => 'Error!'); const { getFormProps, rerender } = renderField({ validate, component: 'input', }); rerender(); act(() => { getFormProps().validateField('name'); }); rerender(); await waitFor(() => { expect(validate).toHaveBeenCalled(); expect(getFormProps().errors.name).toBe('Error!'); }); } ); cases( 'runs validation when validateField is called (ASYNC)', async renderField => { const validate = jest.fn(() => Promise.resolve('Error!')); const { getFormProps, rerender } = renderField({ validate }); // workaround for `useEffect` to run: https://github.com/facebook/react/issues/14050 rerender(); act(() => { getFormProps().validateField('name'); }); expect(validate).toHaveBeenCalled(); await waitFor(() => expect(getFormProps().errors.name).toBe('Error!')); } ); cases( 'runs validationSchema validation when validateField is called', async renderField => { const errorMessage = 'Name must be 100 characters in length'; const validationSchema = Yup.object({ name: Yup.string().min(100, errorMessage), }); const { getFormProps, rerender } = renderField( {}, { validationSchema } ); rerender(); act(() => { getFormProps().validateField('name'); }); await waitFor(() => expect(getFormProps().errors).toEqual({ name: errorMessage, }) ); } ); cases( 'constructs error for a nested field when validateField is called', async renderField => { const validationSchema = Yup.object({ user: Yup.object().shape({ name: Yup.string().required('required'), }), }); const { getFormProps, rerender } = renderField( {}, { validationSchema } ); rerender(); act(() => { getFormProps().validateField('user.name'); }); await waitFor(() => expect(getFormProps().errors).toEqual({ user: { name: 'required' } }) ); } ); }); describe('warnings', () => { cases('warns about render prop deprecation', renderField => { global.console.warn = jest.fn(); const { rerender } = renderField({ render: () => null, }); rerender(); expect((global.console.warn as jest.Mock).mock.calls[0][0]).toContain( 'deprecated' ); }); cases( 'warns if both string component and children as a function', renderField => { global.console.warn = jest.fn(); const { rerender } = renderField({ component: 'select', children: () => <option value="Jared">{TEXT}</option>, }); rerender(); expect((global.console.warn as jest.Mock).mock.calls[0][0]).toContain( 'Warning:' ); } ); cases( 'warns if both string as prop and children as a function', renderField => { global.console.warn = jest.fn(); const { rerender } = renderField({ as: 'select', children: () => <option value="Jared">{TEXT}</option>, }); rerender(); expect((global.console.warn as jest.Mock).mock.calls[0][0]).toContain( 'Warning:' ); } ); cases( 'warns if both non-string component and children children as a function', renderField => { global.console.warn = jest.fn(); const { rerender } = renderField({ component: () => null, children: () => <option value="Jared">{TEXT}</option>, }); rerender(); expect((global.console.warn as jest.Mock).mock.calls[0][0]).toContain( 'Warning:' ); } ); cases('warns if both string component and render', renderField => { global.console.warn = jest.fn(); const { rerender } = renderField({ component: 'textarea', render: () => <option value="Jared">{TEXT}</option>, }); rerender(); expect((global.console.warn as jest.Mock).mock.calls[0][0]).toContain( 'Warning:' ); }); cases('warns if both non-string component and render', renderField => { global.console.warn = jest.fn(); const { rerender } = renderField({ component: () => null, render: () => <option value="Jared">{TEXT}</option>, }); rerender(); expect((global.console.warn as jest.Mock).mock.calls[0][0]).toContain( 'Warning:' ); }); cases('warns if both children and render', renderField => { global.console.warn = jest.fn(); const { rerender } = renderField({ children: <div>{TEXT}</div>, render: () => <div>{TEXT}</div>, }); rerender(); expect((global.console.warn as jest.Mock).mock.calls[0][0]).toContain( 'Warning:' ); }); }); cases('can resolve bracket paths', renderField => { const { getProps } = renderField( { name: 'user[superPowers][0]' }, { initialValues: { user: { superPowers: ['Surging', 'Binding'] } } as any, } // TODO: fix generic type ); expect(getProps().field.value).toBe('Surging'); }); cases('can resolve mixed dot and bracket paths', renderField => { const { getProps } = renderField( { name: 'user.superPowers[1]' }, { initialValues: { user: { superPowers: ['Surging', 'Binding'] } } as any, } // TODO: fix generic type ); expect(getProps().field.value).toBe('Binding'); }); cases('can resolve mixed dot and bracket paths II', renderField => { const { getProps } = renderField( // tslint:disable-next-line:quotemark { name: "user['superPowers'].1" }, { initialValues: { user: { superPowers: ['Surging', 'Binding'] } } as any, } // TODO: fix generic type ); expect(getProps().field.value).toBe('Binding'); }); }); // @todo Deprecated // describe('<FastField />', () => { // it('does NOT forward shouldUpdate to React component', () => { // let injected: any; // const Component = (props: FieldProps) => (injected = props) && null; // const shouldUpdate = () => true; // renderFastField({ component: Component, shouldUpdate }); // expect(injected.shouldUpdate).toBe(undefined); // }); // });
1,226
0
petrpan-code/jaredpalmer/formik/packages/formik
petrpan-code/jaredpalmer/formik/packages/formik/test/FieldArray.test.tsx
import { act, fireEvent, render, screen } from '@testing-library/react'; import * as React from 'react'; import * as Yup from 'yup'; import { FieldArray, FieldArrayRenderProps, Formik, isFunction } from '../src'; const noop = () => {}; const TestForm: React.FC<any> = p => ( <Formik onSubmit={noop} initialValues={{ friends: ['jared', 'andrea', 'brent'] }} {...p} /> ); describe('<FieldArray />', () => { it('renders component with array helpers as props', () => { const TestComponent = (arrayProps: any) => { expect(isFunction(arrayProps.push)).toBeTruthy(); return null; }; render( <TestForm component={() => ( <FieldArray name="friends" component={TestComponent} /> )} /> ); }); it('renders with render callback with array helpers as props', () => { render( <TestForm> {() => ( <FieldArray name="friends" render={arrayProps => { expect(isFunction(arrayProps.push)).toBeTruthy(); return null; }} /> )} </TestForm> ); }); it('renders with "children as a function" with array helpers as props', () => { render( <TestForm> {() => ( <FieldArray name="friends"> {arrayProps => { expect(isFunction(arrayProps.push)).toBeTruthy(); return null; }} </FieldArray> )} </TestForm> ); }); it('renders with name as props', () => { render( <TestForm> {() => ( <FieldArray name="friends" render={arrayProps => { expect(arrayProps.name).toBe('friends'); return null; }} /> )} </TestForm> ); }); describe('props.push()', () => { it('should add a value to the end of the field array', () => { let formikBag: any; let arrayHelpers: FieldArrayRenderProps; render( <TestForm> {(props: any) => { formikBag = props; return ( <FieldArray name="friends" render={arrayProps => { arrayHelpers = arrayProps; return null; }} /> ); }} </TestForm> ); act(() => { arrayHelpers.push('jared'); }); const expected = ['jared', 'andrea', 'brent', 'jared']; expect(formikBag.values.friends).toEqual(expected); }); it('should add multiple values to the end of the field array', () => { let formikBag: any; const AddFriendsButton = (arrayProps: any) => { const addFriends = () => { arrayProps.push('john'); arrayProps.push('paul'); arrayProps.push('george'); arrayProps.push('ringo'); }; return ( <button data-testid="add-friends-button" type="button" onClick={addFriends} /> ); }; render( <TestForm> {(props: any) => { formikBag = props; return <FieldArray name="friends" render={AddFriendsButton} />; }} </TestForm> ); act(() => { const btn = screen.getByTestId('add-friends-button'); fireEvent.click(btn); }); const expected = [ 'jared', 'andrea', 'brent', 'john', 'paul', 'george', 'ringo', ]; expect(formikBag.values.friends).toEqual(expected); }); it('should push clone not actual reference', () => { let personTemplate = { firstName: '', lastName: '' }; let formikBag: any; let arrayHelpers: FieldArrayRenderProps; render( <TestForm initialValues={{ people: [] }}> {(props: any) => { formikBag = props; return ( <FieldArray name="people" render={arrayProps => { arrayHelpers = arrayProps; return null; }} /> ); }} </TestForm> ); act(() => { arrayHelpers.push(personTemplate); }); expect( formikBag.values.people[formikBag.values.people.length - 1] ).not.toBe(personTemplate); expect( formikBag.values.people[formikBag.values.people.length - 1] ).toMatchObject(personTemplate); }); }); describe('props.pop()', () => { it('should remove and return the last value from the field array', () => { let formikBag: any; let arrayHelpers: FieldArrayRenderProps; render( <TestForm> {(props: any) => { formikBag = props; return ( <FieldArray name="friends" render={arrayProps => { arrayHelpers = arrayProps; return null; }} /> ); }} </TestForm> ); act(() => { const el = arrayHelpers.pop(); expect(el).toEqual('brent'); }); const expected = ['jared', 'andrea']; expect(formikBag.values.friends).toEqual(expected); }); }); describe('props.swap()', () => { it('should swap two values in field array', () => { let formikBag: any; let arrayHelpers: FieldArrayRenderProps; render( <TestForm> {(props: any) => { formikBag = props; return ( <FieldArray name="friends" render={arrayProps => { arrayHelpers = arrayProps; return null; }} /> ); }} </TestForm> ); act(() => { arrayHelpers.swap(0, 2); }); const expected = ['brent', 'andrea', 'jared']; expect(formikBag.values.friends).toEqual(expected); }); }); describe('props.insert()', () => { it('should insert a value at given index of field array', () => { let formikBag: any; let arrayHelpers: FieldArrayRenderProps; render( <TestForm> {(props: any) => { formikBag = props; return ( <FieldArray name="friends" render={arrayProps => { arrayHelpers = arrayProps; return null; }} /> ); }} </TestForm> ); act(() => { arrayHelpers.insert(1, 'brian'); }); const expected = ['jared', 'brian', 'andrea', 'brent']; expect(formikBag.values.friends).toEqual(expected); }); }); describe('props.replace()', () => { it('should replace a value at given index of field array', () => { let formikBag: any; let arrayHelpers: FieldArrayRenderProps; render( <TestForm> {(props: any) => { formikBag = props; return ( <FieldArray name="friends" render={arrayProps => { arrayHelpers = arrayProps; return null; }} /> ); }} </TestForm> ); act(() => { arrayHelpers.replace(1, 'brian'); }); const expected = ['jared', 'brian', 'brent']; expect(formikBag.values.friends).toEqual(expected); }); }); describe('props.unshift()', () => { it('should add a value to start of field array and return its length', () => { let formikBag: any; let arrayHelpers: FieldArrayRenderProps; render( <TestForm> {(props: any) => { formikBag = props; return ( <FieldArray name="friends" render={arrayProps => { arrayHelpers = arrayProps; return null; }} /> ); }} </TestForm> ); let el: any; act(() => { el = arrayHelpers.unshift('brian'); }); const expected = ['brian', 'jared', 'andrea', 'brent']; expect(formikBag.values.friends).toEqual(expected); expect(el).toEqual(4); }); }); describe('props.remove()', () => { let formikBag: any; let arrayHelpers: FieldArrayRenderProps; beforeEach(() => { render( <TestForm> {(props: any) => { formikBag = props; return ( <FieldArray name="friends" render={arrayProps => { arrayHelpers = arrayProps; return null; }} /> ); }} </TestForm> ); }); it('should remove a value at given index of field array', () => { act(() => { arrayHelpers.remove(1); }); const expected = ['jared', 'brent']; expect(formikBag.values.friends).toEqual(expected); }); it('should be an empty array when removing all values', () => { act(() => { arrayHelpers.remove(0); arrayHelpers.remove(0); arrayHelpers.remove(0); }); const expected: any[] = []; expect(formikBag.values.friends).toEqual(expected); }); it('should clean field from errors and touched', () => { act(() => { // seems weird calling 0 multiple times, but every time we call remove, the indexes get updated. arrayHelpers.remove(0); arrayHelpers.remove(0); arrayHelpers.remove(0); }); expect(formikBag.errors.friends).toEqual(undefined); expect(formikBag.touched.friends).toEqual(undefined); }); it('should clean up errors', () => { act(() => { formikBag.setFieldError('friends.1', 'Field error'); arrayHelpers.remove(1); }); expect(formikBag.errors.friends).toEqual(undefined); }); }); describe('given array-like object representing errors', () => { it('should run arrayHelpers successfully', async () => { let formikBag: any; let arrayHelpers: FieldArrayRenderProps; render( <TestForm> {(props: any) => { formikBag = props; return ( <FieldArray name="friends"> {arrayProps => { arrayHelpers = arrayProps; return null; }} </FieldArray> ); }} </TestForm> ); act(() => { formikBag.setErrors({ friends: { 2: ['Field error'] } }); }); let el: any; await act(async () => { await arrayHelpers.push('michael'); el = arrayHelpers.pop(); arrayHelpers.swap(0, 2); arrayHelpers.insert(1, 'michael'); arrayHelpers.replace(1, 'brian'); arrayHelpers.unshift('michael'); arrayHelpers.remove(1); }); expect(el).toEqual('michael'); const finalExpected = ['michael', 'brian', 'andrea', 'jared']; expect(formikBag.values.friends).toEqual(finalExpected); }); }); describe('schema validation', () => { const schema = Yup.object({ friends: Yup.array(Yup.string().required()).required().min(3), }); let formikBag: any; let arrayHelpers: FieldArrayRenderProps; beforeEach(() => { render( <Formik initialValues={{ friends: [] }} onSubmit={noop} validationSchema={schema} validateOnMount > {(props: any) => { formikBag = props; return ( <FieldArray name="friends"> {arrayProps => { arrayHelpers = arrayProps; return null; }} </FieldArray> ); }} </Formik> ); }); describe('props.push()', () => { it('should return error string with top level violation', async () => { await act(async () => { await arrayHelpers.push('michael'); }); expect(formikBag.errors.friends).toBe( 'friends field must have at least 3 items' ); }); it('should return errors array with nested value violation', async () => { await act(async () => { await arrayHelpers.push('michael'); arrayHelpers.push('brian'); arrayHelpers.push(''); arrayHelpers.push('andrea'); }); expect(formikBag.errors.friends).toHaveLength(3); expect(formikBag.errors.friends[0]).toBeUndefined(); expect(formikBag.errors.friends[1]).toBeUndefined(); expect(formikBag.errors.friends[2]).toBe( 'friends[2] is a required field' ); }); }); describe('props.swap()', () => { it('should return error string with top level violation', async () => { await act(async () => { await arrayHelpers.push('michael'); arrayHelpers.push('brian'); arrayHelpers.swap(0, 1); }); expect(formikBag.errors.friends).toBe( 'friends field must have at least 3 items' ); }); it('should return errors array with nested value violation', async () => { await act(async () => { await arrayHelpers.push('michael'); arrayHelpers.push('brian'); arrayHelpers.push(''); arrayHelpers.push('andrea'); arrayHelpers.swap(1, 2); }); expect(formikBag.errors.friends).toHaveLength(2); expect(formikBag.errors.friends[0]).toBeUndefined(); expect(formikBag.errors.friends[1]).toBe( 'friends[1] is a required field' ); }); }); describe('props.move()', () => { it('should return error string with top level violation', async () => { await act(async () => { await arrayHelpers.push('michael'); arrayHelpers.push('brian'); arrayHelpers.move(0, 1); }); expect(formikBag.errors.friends).toBe( 'friends field must have at least 3 items' ); }); it('should return errors array with nested value violation', async () => { await act(async () => { await arrayHelpers.push('michael'); arrayHelpers.push('brian'); arrayHelpers.push(''); arrayHelpers.push('andrea'); arrayHelpers.move(1, 2); }); expect(formikBag.errors.friends).toHaveLength(2); expect(formikBag.errors.friends[0]).toBeUndefined(); expect(formikBag.errors.friends[1]).toBe( 'friends[1] is a required field' ); }); }); describe('props.insert()', () => { it('should return error string with top level violation', async () => { await act(async () => { await arrayHelpers.push('michael'); arrayHelpers.insert(1, 'brian'); }); expect(formikBag.errors.friends).toBe( 'friends field must have at least 3 items' ); }); it('should return errors array with nested value violation', async () => { await act(async () => { await arrayHelpers.push('michael'); arrayHelpers.push('brian'); arrayHelpers.push('andrea'); arrayHelpers.insert(1, ''); }); expect(formikBag.errors.friends).toHaveLength(2); expect(formikBag.errors.friends[0]).toBeUndefined(); expect(formikBag.errors.friends[1]).toBe( 'friends[1] is a required field' ); }); }); describe('props.unshift()', () => { it('should return error string with top level violation', async () => { await act(async () => { await arrayHelpers.push('michael'); arrayHelpers.unshift('brian'); }); expect(formikBag.errors.friends).toBe( 'friends field must have at least 3 items' ); }); it('should return errors array with nested value violation', async () => { await act(async () => { await arrayHelpers.push(''); arrayHelpers.push('brian'); arrayHelpers.push('andrea'); arrayHelpers.unshift('michael'); }); expect(formikBag.errors.friends).toHaveLength(2); expect(formikBag.errors.friends[0]).toBeUndefined(); expect(formikBag.errors.friends[1]).toBe( 'friends[1] is a required field' ); }); }); describe('props.remove()', () => { it('should return error string with top level violation ', async () => { await act(async () => { await arrayHelpers.push('michael'); arrayHelpers.push('brian'); arrayHelpers.push('andrea'); arrayHelpers.remove(0); arrayHelpers.remove(0); }); expect(formikBag.errors.friends).toBe( 'friends field must have at least 3 items' ); }); it('should return errors array with nested value violation', async () => { await act(async () => { await arrayHelpers.push('michael'); arrayHelpers.push('brian'); arrayHelpers.push(''); // index specific violation arrayHelpers.push('andrea'); arrayHelpers.remove(0); }); expect(formikBag.errors.friends).toHaveLength(2); expect(formikBag.errors.friends[0]).toBeUndefined(); expect(formikBag.errors.friends[1]).toBe( 'friends[1] is a required field' ); expect(formikBag.errors.friends[2]).toBeUndefined(); expect(formikBag.errors.friends[4]).toBeUndefined(); }); }); describe('props.pop()', () => { it('should return error string with top level violation', async () => { await act(async () => { await arrayHelpers.push('michael'); arrayHelpers.push('brian'); arrayHelpers.push('andrea'); arrayHelpers.pop(); }); expect(formikBag.errors.friends).toBe( 'friends field must have at least 3 items' ); }); it('should return errors array with nested value violation', async () => { await act(async () => { await arrayHelpers.push('michael'); arrayHelpers.push('brian'); arrayHelpers.push(''); arrayHelpers.push('andrea'); arrayHelpers.pop(); }); expect(formikBag.errors.friends).toHaveLength(3); expect(formikBag.errors.friends[0]).toBeUndefined(); expect(formikBag.errors.friends[1]).toBeUndefined(); expect(formikBag.errors.friends[2]).toBe( 'friends[2] is a required field' ); }); }); describe('props.replace()', () => { it('should return error string with top level violation', async () => { await act(async () => { await arrayHelpers.push('michael'); arrayHelpers.replace(0, 'brian'); }); expect(formikBag.errors.friends).toBe( 'friends field must have at least 3 items' ); }); it('should return errors array with nested value violation', async () => { await act(async () => { arrayHelpers.unshift('michael'); await arrayHelpers.push('brian'); arrayHelpers.push('andrea'); arrayHelpers.push('jared'); await arrayHelpers.replace(1, ''); }); expect(formikBag.errors.friends).toHaveLength(2); expect(formikBag.errors.friends[0]).toBeUndefined(); expect(formikBag.errors.friends[1]).toBe( 'friends[1] is a required field' ); }); }); }); });
1,227
0
petrpan-code/jaredpalmer/formik/packages/formik
petrpan-code/jaredpalmer/formik/packages/formik/test/Formik.test.tsx
import * as React from 'react'; import { act, fireEvent, render, screen, waitFor, } from '@testing-library/react'; import * as Yup from 'yup'; import { Formik, FormikConfig, FormikProps, FormikValues, prepareDataForValidation, } from '../src'; import { noop } from './testHelpers'; jest.spyOn(global.console, 'warn'); interface Values { name: string; age?: number; } function Form({ values, touched, handleSubmit, handleChange, handleBlur, status, errors, isSubmitting, }: FormikProps<Values>) { return ( <form onSubmit={handleSubmit} data-testid="form"> <input type="text" onChange={handleChange} onBlur={handleBlur} value={values.name} name="name" data-testid="name-input" /> {touched.name && errors.name && <div id="feedback">{errors.name}</div>} {isSubmitting && <div id="submitting">Submitting</div>} {status && !!status.myStatusMessage && ( <div id="statusMessage">{status.myStatusMessage}</div> )} <button type="submit" data-testid="submit-button"> Submit </button> </form> ); } const InitialValues = { name: 'jared', age: 30, }; function renderFormik<V extends FormikValues = Values>( props?: Partial<FormikConfig<V>> ) { let injected: FormikProps<V>; const { rerender, ...rest } = render( <Formik<V> onSubmit={noop as any} initialValues={InitialValues as any} {...props} > {formikProps => (injected = formikProps) && ( <Form {...((formikProps as unknown) as FormikProps<Values>)} /> ) } </Formik> ); return { getProps(): FormikProps<V> { return injected; }, ...rest, rerender: () => rerender( <Formik onSubmit={noop as any} initialValues={InitialValues as any} {...props} > {formikProps => (injected = formikProps) && ( <Form {...((formikProps as unknown) as FormikProps<Values>)} /> ) } </Formik> ), }; } describe('<Formik>', () => { it('should initialize Formik state and pass down props', () => { const { getProps } = renderFormik(); const props = getProps(); expect(props.isSubmitting).toBe(false); expect(props.touched).toEqual({}); expect(props.values).toEqual(InitialValues); expect(props.errors).toEqual({}); expect(props.dirty).toBe(false); expect(props.isValid).toBe(true); expect(props.submitCount).toBe(0); }); describe('handleChange', () => { it('updates values based on name attribute', () => { const { getProps, getByTestId } = renderFormik<Values>(); expect(getProps().values.name).toEqual(InitialValues.name); const input = getByTestId('name-input'); fireEvent.change(input, { persist: noop, target: { name: 'name', value: 'ian', }, }); expect(getProps().values.name).toEqual('ian'); }); it('updates values when passed a string (overloaded)', () => { let injected: any; const { getByTestId } = render( <Formik initialValues={InitialValues} onSubmit={noop}> {formikProps => (injected = formikProps) && ( <input onChange={formikProps.handleChange('name')} data-testid="name-input" /> ) } </Formik> ); const input = getByTestId('name-input'); expect(injected.values.name).toEqual(InitialValues.name); fireEvent.change(input, { persist: noop, target: { name: 'name', value: 'ian', }, }); expect(injected.values.name).toEqual('ian'); }); it('updates values via `name` instead of `id` attribute when both are present', () => { const { getProps, getByTestId } = renderFormik<Values>(); expect(getProps().values.name).toEqual(InitialValues.name); const input = getByTestId('name-input'); fireEvent.change(input, { persist: noop, target: { id: 'person-1-thinger', name: 'name', value: 'ian', }, }); expect(getProps().values.name).toEqual('ian'); }); it('updates values when passed a string (overloaded)', () => { let injected: any; render( <Formik initialValues={InitialValues} onSubmit={noop}> {formikProps => (injected = formikProps) && ( <input onChange={formikProps.handleChange('name')} data-testid="name-input" /> ) } </Formik> ); const input = screen.getByTestId('name-input'); expect(injected.values.name).toEqual('jared'); fireEvent.change(input, { target: { name: 'name', value: 'ian', }, }); expect(injected.values.name).toEqual('ian'); }); it('runs validations by default', async () => { const validate = jest.fn(() => Promise.resolve()); const validationSchema = { validate, }; const { rerender } = renderFormik({ validate, validationSchema, }); fireEvent.change(screen.getByTestId('name-input'), { persist: noop, target: { name: 'name', value: 'ian', }, }); rerender(); await waitFor(() => { expect(validate).toHaveBeenCalledTimes(2); }); }); it('does NOT run validations if validateOnChange is false', async () => { const validate = jest.fn(() => Promise.resolve()); const validationSchema = { validate, }; const { rerender } = renderFormik({ validate, validationSchema, validateOnChange: false, }); fireEvent.change(screen.getByTestId('name-input'), { persist: noop, target: { name: 'name', value: 'ian', }, }); rerender(); await waitFor(() => { expect(validate).not.toHaveBeenCalled(); }); }); }); describe('handleBlur', () => { it('sets touched state', () => { const { getProps } = renderFormik<Values>(); expect(getProps().touched.name).toEqual(undefined); const input = screen.getByTestId('name-input'); fireEvent.blur(input, { target: { name: 'name', }, }); expect(getProps().touched.name).toEqual(true); }); it('updates touched state via `name` instead of `id` attribute when both are present', () => { const { getProps } = renderFormik<Values>(); expect(getProps().touched.name).toEqual(undefined); const input = screen.getByTestId('name-input'); fireEvent.blur(input, { target: { id: 'blah', name: 'name', }, }); expect(getProps().touched.name).toEqual(true); }); it('updates touched when passed a string (overloaded)', () => { let injected: any; render( <Formik initialValues={InitialValues} onSubmit={noop}> {formikProps => (injected = formikProps) && ( <input onBlur={formikProps.handleBlur('name')} data-testid="name-input" /> ) } </Formik> ); const input = screen.getByTestId('name-input'); expect(injected.touched.name).toEqual(undefined); fireEvent.blur(input, { target: { name: 'name', value: 'ian', }, }); expect(injected.touched.name).toEqual(true); }); it('runs validate by default', async () => { const validate = jest.fn(noop); const { rerender } = renderFormik({ validate }); fireEvent.blur(screen.getByTestId('name-input'), { target: { name: 'name', }, }); rerender(); await waitFor(() => { expect(validate).toHaveBeenCalled(); }); }); it('runs validations by default', async () => { const validate = jest.fn(() => Promise.resolve()); const validationSchema = { validate, }; const { rerender } = renderFormik({ validate, validationSchema, }); fireEvent.blur(screen.getByTestId('name-input'), { target: { name: 'name', }, }); rerender(); await waitFor(() => { expect(validate).toHaveBeenCalledTimes(2); }); }); it('runs validations if validateOnBlur is true (default)', async () => { const validate = jest.fn(() => Promise.resolve()); const validationSchema = { validate, }; const { rerender } = renderFormik({ validate, validationSchema, }); fireEvent.blur(screen.getByTestId('name-input'), { target: { name: 'name', }, }); rerender(); await waitFor(() => { expect(validate).toHaveBeenCalledTimes(2); }); }); it('dost NOT run validations if validateOnBlur is false', async () => { const validate = jest.fn(() => Promise.resolve()); const validationSchema = { validate, }; const { rerender } = renderFormik({ validate, validationSchema, validateOnBlur: false, }); rerender(); await waitFor(() => expect(validate).not.toHaveBeenCalled()); }); }); describe('handleSubmit', () => { it('should call preventDefault()', () => { const preventDefault = jest.fn(); const FormPreventDefault = ( <Formik initialValues={{ name: 'jared' }} onSubmit={noop}> {({ handleSubmit }) => ( <button data-testid="submit-button" onClick={() => handleSubmit({ preventDefault } as any)} /> )} </Formik> ); render(FormPreventDefault); fireEvent.click(screen.getByTestId('submit-button')); expect(preventDefault).toHaveBeenCalled(); }); it('should not error if called without an event', () => { const FormNoEvent = ( <Formik initialValues={{ name: 'jared' }} onSubmit={noop}> {({ handleSubmit }) => ( <button data-testid="submit-button" onClick={() => handleSubmit(undefined as any /* undefined event */) } /> )} </Formik> ); render(FormNoEvent); expect(() => { fireEvent.click(screen.getByTestId('submit-button')); }).not.toThrow(); }); it('should not error if called without preventDefault property', () => { const FormNoPreventDefault = ( <Formik initialValues={{ name: 'jared' }} onSubmit={noop}> {({ handleSubmit }) => ( <button data-testid="submit-button" onClick={() => handleSubmit({} as any /* undefined event */)} /> )} </Formik> ); render(FormNoPreventDefault); expect(() => { fireEvent.click(screen.getByTestId('submit-button')); }).not.toThrow(); }); it('should not error if onSubmit throws an error', () => { const FormNoPreventDefault = ( <Formik initialValues={{ name: 'jared' }} onSubmit={() => Promise.reject('oops')} > {({ handleSubmit }) => ( <button data-testid="submit-button" onClick={() => handleSubmit(undefined as any /* undefined event */) } /> )} </Formik> ); render(FormNoPreventDefault); expect(() => { fireEvent.click(screen.getByTestId('submit-button')); }).not.toThrow(); }); it('should touch all fields', () => { const { getProps } = renderFormik(); expect(getProps().touched).toEqual({}); fireEvent.submit(screen.getByTestId('form')); expect(getProps().touched).toEqual({ name: true, age: true }); }); it('should push submission state changes to child component', () => { const { getProps, getByTestId } = renderFormik(); expect(getProps().isSubmitting).toBeFalsy(); fireEvent.submit(getByTestId('form')); expect(getProps().isSubmitting).toBeTruthy(); }); describe('with validate (SYNC)', () => { it('should call validate if present', () => { const validate = jest.fn(() => ({})); const { getByTestId } = renderFormik({ validate }); fireEvent.submit(getByTestId('form')); expect(validate).toHaveBeenCalled(); }); it('should submit the form if valid', async () => { const onSubmit = jest.fn(); const validate = jest.fn(() => ({})); const { getByTestId } = renderFormik({ onSubmit, validate }); fireEvent.submit(getByTestId('form')); await waitFor(() => expect(onSubmit).toBeCalled()); }); it('should not submit the form if invalid', () => { const onSubmit = jest.fn(); const validate = jest.fn(() => ({ name: 'Error!' })); const { getByTestId } = renderFormik({ onSubmit, validate }); fireEvent.submit(getByTestId('form')); expect(onSubmit).not.toBeCalled(); }); it('should not submit the form if validate function throws an error', async () => { const onSubmit = jest.fn(); const err = new Error('Async Error'); const validate = jest.fn().mockRejectedValue(err); const { getProps } = renderFormik({ onSubmit, validate, }); await act(async () => { await expect(getProps().submitForm()).rejects.toThrow('Async Error'); }); await waitFor(() => { expect(onSubmit).not.toBeCalled(); expect(global.console.warn).toHaveBeenCalledWith( expect.stringMatching( /Warning: An unhandled error was caught during validation in <Formik validate ./ ), err ); }); }); describe('submitForm helper should not break promise chain if handleSubmit has returned rejected Promise', () => { it('submitForm helper should not break promise chain if handleSubmit has returned rejected Promise', async () => { const error = new Error('This Error is typeof Error'); const handleSubmit = () => { return Promise.reject(error); }; const { getProps } = renderFormik({ onSubmit: handleSubmit }); const { submitForm } = getProps(); await act(async () => { await expect(submitForm()).rejects.toEqual(error); }); }); }); }); describe('with validate (ASYNC)', () => { it('should call validate if present', () => { const validate = jest.fn(() => Promise.resolve({})); const { getByTestId } = renderFormik({ validate }); fireEvent.submit(getByTestId('form')); expect(validate).toHaveBeenCalled(); }); it('should submit the form if valid', async () => { const onSubmit = jest.fn(); const validate = jest.fn(() => Promise.resolve({})); const { getByTestId } = renderFormik({ onSubmit, validate }); fireEvent.submit(getByTestId('form')); await waitFor(() => expect(onSubmit).toBeCalled()); }); it('should not submit the form if invalid', () => { const onSubmit = jest.fn(); const validate = jest.fn(() => Promise.resolve({ name: 'Error!' })); const { getByTestId } = renderFormik({ onSubmit, validate }); fireEvent.submit(getByTestId('form')); expect(onSubmit).not.toBeCalled(); }); it('should not submit the form if validate function rejects with an error', async () => { const onSubmit = jest.fn(); const err = new Error('Async Error'); const validate = jest.fn().mockRejectedValue(err); const { getProps } = renderFormik({ onSubmit, validate }); await act(async () => { await expect(getProps().submitForm()).rejects.toThrow('Async Error'); }); await waitFor(() => { expect(onSubmit).not.toBeCalled(); expect(global.console.warn).toHaveBeenCalledWith( expect.stringMatching( /Warning: An unhandled error was caught during validation in <Formik validate ./ ), err ); }); }); }); describe('with validationSchema (ASYNC)', () => { it('should run validationSchema if present', async () => { const validate = jest.fn(() => Promise.resolve({})); const validationSchema = { validate, }; renderFormik({ validate, validationSchema, }); await act(async () => { await fireEvent.submit(screen.getByTestId('form')); }); expect(validate).toHaveBeenCalled(); }); it('should call validationSchema if it is a function and present', async () => { const validate = jest.fn(() => Promise.resolve({})); const validationSchema = () => ({ validate, }); renderFormik({ validate, validationSchema, }); await act(async () => { await fireEvent.submit(screen.getByTestId('form')); }); expect(validate).toHaveBeenCalled(); }); }); describe('FormikHelpers', () => { it('setValues sets values', () => { const { getProps } = renderFormik<Values>(); act(() => { getProps().setValues({ name: 'ian', age: 25 }); }); expect(getProps().values.name).toEqual('ian'); expect(getProps().values.age).toEqual(25); }); it('setValues takes a function which can patch values', () => { const { getProps } = renderFormik<Values>(); act(() => { getProps().setValues((values: Values) => ({ ...values, age: 80, })); }); expect(getProps().values.name).toEqual('jared'); expect(getProps().values.age).toEqual(80); }); it('setValues should run validations when validateOnChange is true (default)', async () => { const newValue: Values = { name: 'ian' }; const validate = jest.fn(_values => ({})); const { getProps } = renderFormik({ validate }); act(() => { getProps().setValues(newValue); }); // rerender(); await waitFor(() => { expect(validate).toHaveBeenCalledWith(newValue, undefined); }); }); it('setValues should NOT run validations when validateOnChange is false', async () => { const validate = jest.fn(); const { getProps, rerender } = renderFormik<Values>({ validate, validateOnChange: false, }); act(() => { getProps().setValues({ name: 'ian' }); }); rerender(); await waitFor(() => { expect(validate).not.toHaveBeenCalled(); }); }); it('setFieldValue sets value by key', async () => { const { getProps, rerender } = renderFormik<Values>(); act(() => { getProps().setFieldValue('name', 'ian'); }); rerender(); await waitFor(() => { expect(getProps().values.name).toEqual('ian'); }); }); it('setFieldValue should run validations when validateOnChange is true (default)', async () => { const validate = jest.fn(() => ({})); const { getProps, rerender } = renderFormik({ validate }); act(() => { getProps().setFieldValue('name', 'ian'); }); rerender(); await waitFor(() => { expect(validate).toHaveBeenCalled(); }); }); it('setFieldValue should NOT run validations when validateOnChange is false', async () => { const validate = jest.fn(); const { getProps, rerender } = renderFormik({ validate, validateOnChange: false, }); act(() => { getProps().setFieldValue('name', 'ian'); }); rerender(); await waitFor(() => { expect(validate).not.toHaveBeenCalled(); }); }); it('setTouched sets touched', () => { const { getProps } = renderFormik(); act(() => { getProps().setTouched({ name: true }); }); expect(getProps().touched).toEqual({ name: true }); }); it('setTouched should NOT run validations when validateOnChange is true (default)', async () => { const validate = jest.fn(() => ({})); const { getProps, rerender } = renderFormik({ validate }); act(() => { getProps().setTouched({ name: true }); }); rerender(); await waitFor(() => expect(validate).toHaveBeenCalled()); }); it('setTouched should run validations when validateOnBlur is false', async () => { const validate = jest.fn(() => ({})); const { getProps, rerender } = renderFormik({ validate, validateOnBlur: false, }); act(() => { getProps().setTouched({ name: true }); }); rerender(); await waitFor(() => expect(validate).not.toHaveBeenCalled()); }); it('setFieldTouched sets touched by key', () => { const { getProps } = renderFormik<Values>(); act(() => { getProps().setFieldTouched('name', true); }); expect(getProps().touched).toEqual({ name: true }); expect(getProps().dirty).toBe(false); act(() => { getProps().setFieldTouched('name', false); }); expect(getProps().touched).toEqual({ name: false }); expect(getProps().dirty).toBe(false); }); it('setFieldTouched should run validations when validateOnBlur is true (default)', async () => { const validate = jest.fn(() => ({})); const { getProps, rerender } = renderFormik({ validate }); act(() => { getProps().setFieldTouched('name', true); }); rerender(); await waitFor(() => expect(validate).toHaveBeenCalled()); }); it('setFieldTouched should NOT run validations when validateOnBlur is false', async () => { const validate = jest.fn(() => ({})); const { getProps, rerender } = renderFormik({ validate, validateOnBlur: false, }); act(() => { getProps().setFieldTouched('name', true); }); rerender(); await waitFor(() => expect(validate).not.toHaveBeenCalled()); }); it('setErrors sets error object', () => { const { getProps } = renderFormik<Values>(); act(() => { getProps().setErrors({ name: 'Required' }); }); expect(getProps().errors.name).toEqual('Required'); }); it('setFieldError sets error by key', () => { const { getProps } = renderFormik<Values>(); act(() => { getProps().setFieldError('name', 'Required'); }); expect(getProps().errors.name).toEqual('Required'); }); it('setStatus sets status object', () => { const { getProps } = renderFormik(); const status = 'status'; act(() => { getProps().setStatus(status); }); expect(getProps().status).toEqual(status); }); }); }); describe('FormikComputedProps', () => { it('should compute dirty as soon as any input is touched', () => { const { getProps } = renderFormik(); expect(getProps().dirty).toBeFalsy(); act(() => { getProps().setValues({ name: 'ian', age: 27 }); }); expect(getProps().dirty).toBeTruthy(); }); it('should compute isValid if isInitialValid is present and returns true', () => { const { getProps } = renderFormik({ isInitialValid: () => true }); expect(getProps().dirty).toBeFalsy(); expect(getProps().isValid).toBeTruthy(); }); it('should compute isValid if isInitialValid is present and returns false', () => { const { getProps } = renderFormik({ isInitialValid: () => false }); expect(getProps().dirty).toBeFalsy(); expect(getProps().isValid).toBeFalsy(); }); it('should compute isValid if isInitialValid boolean is present and set to true', () => { const { getProps } = renderFormik({ isInitialValid: true }); expect(getProps().dirty).toBeFalsy(); expect(getProps().isValid).toBeTruthy(); }); it('should compute isValid if isInitialValid is present and set to false', () => { const { getProps } = renderFormik({ isInitialValid: false }); expect(getProps().dirty).toBeFalsy(); expect(getProps().isValid).toBeFalsy(); }); it('should compute isValid if the form is dirty and there are errors', () => { const { getProps } = renderFormik(); act(() => { getProps().setValues({ name: 'ian' }); getProps().setErrors({ name: 'Required!' }); }); expect(getProps().dirty).toBeTruthy(); expect(getProps().isValid).toBeFalsy(); }); it('should compute isValid if the form is dirty and there are not errors', () => { const { getProps } = renderFormik(); act(() => { getProps().setValues({ name: 'ian' }); }); expect(getProps().dirty).toBeTruthy(); expect(getProps().isValid).toBeTruthy(); }); it('should increase submitCount after submitting the form', () => { const { getProps, getByTestId } = renderFormik(); expect(getProps().submitCount).toBe(0); fireEvent.submit(getByTestId('form')); expect(getProps().submitCount).toBe(1); }); }); describe('handleReset', () => { it('should call onReset if onReset prop is set', () => { const onReset = jest.fn(); const { getProps } = renderFormik({ initialValues: InitialValues, onReset: onReset, onSubmit: noop, }); const { handleReset } = getProps(); act(() => { handleReset(); }); expect(onReset).toHaveBeenCalled(); }); }); describe('resetForm', () => { it('should call onReset with values and actions when form is reset', () => { const onReset = jest.fn(); const { getProps } = renderFormik({ initialValues: InitialValues, onSubmit: noop, onReset, }); act(() => { getProps().resetForm(); }); expect(onReset).toHaveBeenCalledWith( InitialValues, expect.objectContaining({ resetForm: expect.any(Function), setErrors: expect.any(Function), setFieldError: expect.any(Function), setFieldTouched: expect.any(Function), setFieldValue: expect.any(Function), setStatus: expect.any(Function), setSubmitting: expect.any(Function), setTouched: expect.any(Function), setValues: expect.any(Function), }) ); }); it('should not error resetting form if onReset is not a prop', () => { const { getProps } = renderFormik(); act(() => { getProps().resetForm(); }); expect(true); }); it('should reset dirty flag even if initialValues has changed', () => { const { getProps, getByTestId } = renderFormik(); expect(getProps().dirty).toBeFalsy(); const input = getByTestId('name-input'); fireEvent.change(input, { persist: noop, target: { name: 'name', value: 'Pavel', }, }); expect(getProps().dirty).toBeTruthy(); act(() => { getProps().resetForm(); }); expect(getProps().dirty).toBeFalsy(); }); it('should reset submitCount', () => { const { getProps } = renderFormik(); act(() => { getProps().handleSubmit(); }); expect(getProps().submitCount).toEqual(1); act(() => { getProps().resetForm(); }); expect(getProps().submitCount).toEqual(0); }); it('should reset dirty when resetting to same values', () => { const { getProps } = renderFormik(); expect(getProps().dirty).toBe(false); act(() => { getProps().setFieldValue('name', 'jared-next'); }); expect(getProps().dirty).toBe(true); act(() => { getProps().resetForm({ values: getProps().values }); }); expect(getProps().dirty).toBe(false); }); }); describe('prepareDataForValidation', () => { it('should work correctly with instances', () => { class SomeClass {} const expected = { string: 'string', date: new Date(), someInstance: new SomeClass(), }; const dataForValidation = prepareDataForValidation(expected); expect(dataForValidation).toEqual(expected); }); it('should work correctly with instances in arrays', () => { class SomeClass {} const expected = { string: 'string', dateArr: [new Date(), new Date()], someInstanceArr: [new SomeClass(), new SomeClass()], }; const dataForValidation = prepareDataForValidation(expected); expect(dataForValidation).toEqual(expected); }); it('should work correctly with instances in objects', () => { class SomeClass {} const expected = { string: 'string', object: { date: new Date(), someInstance: new SomeClass(), }, }; const dataForValidation = prepareDataForValidation(expected); expect(dataForValidation).toEqual(expected); }); it('should work correctly with mixed data', () => { const date = new Date(); const dataForValidation = prepareDataForValidation({ string: 'string', empty: '', arr: [], date, }); expect(dataForValidation).toEqual({ string: 'string', empty: undefined, arr: [], date, }); }); it('should work correctly for nested arrays', () => { const expected = { content: [ ['a1', 'a2'], ['b1', 'b2'], ], }; const dataForValidation = prepareDataForValidation(expected); expect(dataForValidation).toEqual(expected); }); }); // describe('componentDidUpdate', () => { // let formik: any, initialValues: any; // beforeEach(() => { // initialValues = { // name: 'formik', // github: { repoUrl: 'https://github.com/jaredpalmer/formik' }, // watchers: ['ian', 'sam'], // }; // const { getRef } = renderFormik({ // initialValues, // enableReinitialize: true, // }); // formik = getRef(); // formik.current.resetForm = jest.fn(); // }); // it('should not resetForm if new initialValues are the same as previous', () => { // const newInitialValues = Object.assign({}, initialValues); // formik.current.componentDidUpdate({ // initialValues: newInitialValues, // onSubmit: noop, // }); // expect(formik.current.resetForm).not.toHaveBeenCalled(); // }); // it('should resetForm if new initialValues are different than previous', () => { // const newInitialValues = { // ...initialValues, // watchers: ['jared', 'ian', 'sam'], // }; // formik.current.componentDidUpdate({ // initialValues: newInitialValues, // onSubmit: noop, // }); // expect(formik.current.resetForm).toHaveBeenCalled(); // }); // it('should resetForm if new initialValues are deeply different than previous', () => { // const newInitialValues = { // ...initialValues, // github: { repoUrl: 'different' }, // }; // formik.current.componentDidUpdate({ // initialValues: newInitialValues, // onSubmit: noop, // }); // expect(formik.current.resetForm).toHaveBeenCalled(); // }); // it('should NOT resetForm without enableReinitialize flag', () => { // const { getRef } = renderFormik({ // initialValues, // }); // formik = getRef(); // formik.current.resetForm = jest.fn(); // const newInitialValues = { // ...initialValues, // watchers: ['jared', 'ian', 'sam'], // }; // formik.current.componentDidUpdate({ // initialValues: newInitialValues, // onSubmit: noop, // }); // expect(formik.current.resetForm).not.toHaveBeenCalled(); // }); // }); it('should warn against buttons with unspecified type', () => { const { getByText, getByTestId } = render( <Formik onSubmit={noop} initialValues={{ opensource: 'yay' }}> {({ handleSubmit, handleChange, values }) => ( <form onSubmit={handleSubmit} data-testid="form"> <input type="text" onChange={handleChange} value={values.opensource} name="name" /> <button>Submit</button> </form> )} </Formik> ); const button = getByText('Submit'); button.focus(); // sets activeElement fireEvent.submit(getByTestId('form')); expect(global.console.warn).toHaveBeenCalledWith( expect.stringMatching( /Warning: You submitted a Formik form using a button with an unspecified `type./ ) ); button.blur(); // unsets activeElement (global.console.warn as jest.Mock<{}>).mockClear(); }); it('should not warn when button has type submit', () => { const { getByText, getByTestId } = render( <Formik onSubmit={noop} initialValues={{ opensource: 'yay' }}> {({ handleSubmit, handleChange, values }) => ( <form onSubmit={handleSubmit} data-testid="form"> <input type="text" onChange={handleChange} value={values.opensource} name="name" /> <button type="submit">Submit</button> </form> )} </Formik> ); const button = getByText('Submit'); button.focus(); // sets activeElement fireEvent.submit(getByTestId('form')); expect(global.console.warn).not.toHaveBeenCalledWith( expect.stringMatching( /Warning: You submitted a Formik form using a button with an unspecified type./ ) ); button.blur(); // unsets activeElement (global.console.warn as jest.Mock<{}>).mockClear(); }); it('should not warn when activeElement is not a button', () => { render( <Formik onSubmit={noop} initialValues={{ opensource: 'yay' }}> {({ handleSubmit, handleChange, values }) => ( <form onSubmit={handleSubmit} data-testid="form"> <input type="text" onChange={handleChange} value={values.opensource} name="name" data-testid="name-input" /> <button type="submit">Submit</button> </form> )} </Formik> ); const input = screen.getByTestId('name-input'); input.focus(); // sets activeElement fireEvent.submit(screen.getByTestId('form')); expect(global.console.warn).not.toHaveBeenCalledWith( expect.stringMatching( /Warning: You submitted a Formik form using a button with an unspecified type./ ) ); input.blur(); // unsets activeElement (global.console.warn as jest.Mock<{}>).mockClear(); }); it('submit count increments', async () => { const onSubmit = jest.fn(); const { getProps } = renderFormik({ onSubmit, }); expect(getProps().submitCount).toEqual(0); await act(async () => { await getProps().submitForm(); }); expect(onSubmit).toHaveBeenCalled(); expect(getProps().submitCount).toEqual(1); }); it('isValidating is fired when submit is attempted', async () => { const onSubmit = jest.fn(); const validate = jest.fn(() => ({ name: 'no', })); const { getProps } = renderFormik({ onSubmit, validate, }); expect(getProps().submitCount).toEqual(0); expect(getProps().isSubmitting).toBe(false); expect(getProps().isValidating).toBe(false); let submitFormPromise: Promise<any>; act(() => { // we call set isValidating synchronously submitFormPromise = getProps().submitForm(); }); // so it should change expect(getProps().isSubmitting).toBe(true); expect(getProps().isValidating).toBe(true); try { await act(async () => { // resolve the promise to check final state. await submitFormPromise; }); } catch (err) {} // now both should be false because validation failed expect(getProps().isSubmitting).toBe(false); expect(getProps().isValidating).toBe(false); expect(validate).toHaveBeenCalled(); expect(onSubmit).not.toHaveBeenCalled(); expect(getProps().submitCount).toEqual(1); }); it('isSubmitting is fired when submit is attempted (v1)', async () => { const onSubmit = jest.fn(); const validate = jest.fn(() => Promise.resolve({})); const { getProps } = renderFormik({ onSubmit, validate, }); expect(getProps().submitCount).toEqual(0); expect(getProps().isSubmitting).toBe(false); expect(getProps().isValidating).toBe(false); let submitFormPromise: Promise<any>; act(() => { // we call set isValidating synchronously submitFormPromise = getProps().submitForm(); }); // so it should change expect(getProps().isSubmitting).toBe(true); expect(getProps().isValidating).toBe(true); await act(async () => { // resolve the promise to check final state. await submitFormPromise; }); // done validating and submitting expect(getProps().isSubmitting).toBe(true); expect(getProps().isValidating).toBe(false); expect(validate).toHaveBeenCalled(); expect(onSubmit).toHaveBeenCalled(); expect(getProps().submitCount).toEqual(1); }); it('isSubmitting is fired when submit is attempted (v2, promise)', async () => { const onSubmit = jest.fn().mockResolvedValue(undefined); const validate = jest.fn(() => Promise.resolve({})); const { getProps } = renderFormik({ onSubmit, validate, }); expect(getProps().submitCount).toEqual(0); expect(getProps().isSubmitting).toBe(false); expect(getProps().isValidating).toBe(false); let submitFormPromise: Promise<any>; act(() => { // we call set isValidating synchronously submitFormPromise = getProps().submitForm(); }); // so it should change expect(getProps().isSubmitting).toBe(true); expect(getProps().isValidating).toBe(true); await act(async () => { // resolve the promise to check final state. await submitFormPromise; }); // done validating and submitting expect(getProps().isSubmitting).toBe(false); expect(getProps().isValidating).toBe(false); expect(validate).toHaveBeenCalled(); expect(onSubmit).toHaveBeenCalled(); expect(getProps().submitCount).toEqual(1); }); it('isValidating is fired validation is run', async () => { const validate = jest.fn(() => ({ name: 'no' })); const { getProps } = renderFormik({ validate, }); expect(getProps().isValidating).toBe(false); let validatePromise: Promise<any>; act(() => { // we call set isValidating synchronously validatePromise = getProps().validateForm(); }); expect(getProps().isValidating).toBe(true); await act(async () => { await validatePromise; }); expect(validate).toHaveBeenCalled(); expect(getProps().isValidating).toBe(false); }); it('should merge validation errors', async () => { const validate = () => ({ users: [{ firstName: 'required' }], }); const validationSchema = Yup.object({ users: Yup.array().of( Yup.object({ lastName: Yup.string().required('required'), }) ), }); const { getProps } = renderFormik({ initialValues: { users: [{ firstName: '', lastName: '' }] }, validate, validationSchema, }); await act(async () => { await getProps().validateForm(); }); expect(getProps().errors).toEqual({ users: [{ firstName: 'required', lastName: 'required' }], }); }); it('should not eat an error thrown by the validationSchema', async () => { const validationSchema = () => { throw new Error('broken validations'); }; const { getProps } = renderFormik({ initialValues: { users: [{ firstName: '', lastName: '' }] }, validationSchema, }); let caughtError: string = ''; await act(async () => { try { await getProps().validateForm(); } catch (err) { caughtError = (err as Yup.ValidationError).message; } }); expect(caughtError).toEqual('broken validations'); }); it('exposes formikbag as imperative methods', () => { const innerRef: any = React.createRef(); const { getProps } = renderFormik({ innerRef }); expect(innerRef.current).toEqual(getProps()); }); });
1,230
0
petrpan-code/jaredpalmer/formik/packages/formik
petrpan-code/jaredpalmer/formik/packages/formik/test/tsconfig.json
{ // Hack to fix https://github.com/formium/tsdx/issues/84#issuecomment-489690504 "extends": "../../../tsconfig.json", "include": ["."] }
1,231
0
petrpan-code/jaredpalmer/formik/packages/formik
petrpan-code/jaredpalmer/formik/packages/formik/test/types.test.tsx
import { FormikTouched, FormikErrors } from '../src'; describe('Formik Types', () => { describe('FormikTouched', () => { type Values = { id: string; social: { facebook: string; }; }; it('it should infer nested object structure of touched property from Values', () => { const touched: FormikTouched<Values> = { id: true, social: { facebook: true }, }; // type touched = { // id?: boolean | undefined; // social?: { // facebook?: boolean | undefined; // } | undefined; // } const id: boolean | undefined = touched.id; expect(id).toBe(true); const facebook: boolean | undefined = touched.social!.facebook; expect(facebook).toBe(true); }); it('it should infer nested object structure of error property from Values', () => { const errors: FormikErrors<Values> = { id: 'error', social: { facebook: 'error' }, }; // type touched = { // id?: {} | undefined; // social?: { // facebook?: {} | undefined; // } | undefined; // } const id: {} | undefined = errors.id; expect(id).toBe('error'); const facebook: {} | undefined = errors.social!.facebook; expect(facebook).toBe('error'); }); }); });
1,232
0
petrpan-code/jaredpalmer/formik/packages/formik
petrpan-code/jaredpalmer/formik/packages/formik/test/utils.test.tsx
import { isEmptyArray, setIn, getIn, setNestedObjectValues, isPromise, getActiveElement, isNaN, } from '../src/utils'; describe('utils', () => { describe('isEmptyArray', () => { it('returns true when an empty array is passed in', () => { expect(isEmptyArray([])).toBe(true); }); it('returns false when anything other than empty array is passed in', () => { expect(isEmptyArray()).toBe(false); expect(isEmptyArray(null)).toBe(false); expect(isEmptyArray(123)).toBe(false); expect(isEmptyArray('abc')).toBe(false); expect(isEmptyArray({})).toBe(false); expect(isEmptyArray({ a: 1 })).toBe(false); expect(isEmptyArray(['abc'])).toBe(false); }); }); describe('setNestedObjectValues', () => { it('sets value flat object', () => { const obj = { x: 'y' }; expect(setNestedObjectValues(obj, true)).toEqual({ x: true }); }); it('sets value of nested object', () => { const obj = { x: { nestedObject: { z: 'thing', }, }, }; const newObj = { x: { nestedObject: { z: true, }, }, }; expect(setNestedObjectValues(obj, true)).toEqual(newObj); }); it('sets value of nested flat array items', () => { const obj = { x: { nestedObject: { z: 'thing', }, nestedFlatArray: ['jared', 'ian'], }, }; const newObj = { x: { nestedObject: { z: true, }, nestedFlatArray: [true, true], }, }; expect(setNestedObjectValues(obj, true)).toEqual(newObj); }); it('sets value of nested complex array items', () => { const obj = { x: { nestedObject: { z: 'thing', }, nestedFlatArray: [ { nestedObject: { z: 'thing', }, }, { nestedObject: { z: 'thing', }, }, ], }, }; const newObj = { x: { nestedObject: { z: true, }, nestedFlatArray: [ { nestedObject: { z: true, }, }, { nestedObject: { z: true, }, }, ], }, }; expect(setNestedObjectValues(obj, true)).toEqual(newObj); }); it('sets value of nested mixed array items', () => { const obj = { x: { nestedObject: { z: 'thing', }, nestedFlatArray: [ { nestedObject: { z: 'thing', }, }, 'jared', ], }, }; const newObj = { x: { nestedObject: { z: true, }, nestedFlatArray: [ { nestedObject: { z: true, }, }, true, ], }, }; expect(setNestedObjectValues(obj, true)).toEqual(newObj); }); }); describe('getIn', () => { const obj = { a: { b: 2, c: false, d: null, }, t: true, s: 'a random string', }; it('gets a value by array path', () => { expect(getIn(obj, ['a', 'b'])).toBe(2); }); it('gets a value by string path', () => { expect(getIn(obj, 'a.b')).toBe(2); }); it('return "undefined" if value was not found using given path', () => { expect(getIn(obj, 'a.z')).toBeUndefined(); }); it('return "undefined" if value was not found using given path and an intermediate value is "false"', () => { expect(getIn(obj, 'a.c.z')).toBeUndefined(); }); it('return "undefined" if value was not found using given path and an intermediate value is "null"', () => { expect(getIn(obj, 'a.d.z')).toBeUndefined(); }); it('return "undefined" if value was not found using given path and an intermediate value is "true"', () => { expect(getIn(obj, 't.z')).toBeUndefined(); }); it('return "undefined" if value was not found using given path and an intermediate value is a string', () => { expect(getIn(obj, 's.z')).toBeUndefined(); }); }); describe('setIn', () => { it('sets flat value', () => { const obj = { x: 'y' }; const newObj = setIn(obj, 'flat', 'value'); expect(obj).toEqual({ x: 'y' }); expect(newObj).toEqual({ x: 'y', flat: 'value' }); }); it('keep the same object if nothing is changed', () => { const obj = { x: 'y' }; const newObj = setIn(obj, 'x', 'y'); expect(obj).toBe(newObj); }); it('removes flat value', () => { const obj = { x: 'y' }; const newObj = setIn(obj, 'x', undefined); expect(obj).toEqual({ x: 'y' }); expect(newObj).toEqual({}); expect(newObj).not.toHaveProperty('x'); }); it('sets nested value', () => { const obj = { x: 'y' }; const newObj = setIn(obj, 'nested.value', 'nested value'); expect(obj).toEqual({ x: 'y' }); expect(newObj).toEqual({ x: 'y', nested: { value: 'nested value' } }); }); it('updates nested value', () => { const obj = { x: 'y', nested: { value: 'a' } }; const newObj = setIn(obj, 'nested.value', 'b'); expect(obj).toEqual({ x: 'y', nested: { value: 'a' } }); expect(newObj).toEqual({ x: 'y', nested: { value: 'b' } }); }); it('removes nested value', () => { const obj = { x: 'y', nested: { value: 'a' } }; const newObj = setIn(obj, 'nested.value', undefined); expect(obj).toEqual({ x: 'y', nested: { value: 'a' } }); expect(newObj).toEqual({ x: 'y', nested: {} }); expect(newObj.nested).not.toHaveProperty('value'); }); it('updates deep nested value', () => { const obj = { x: 'y', twofoldly: { nested: { value: 'a' } } }; const newObj = setIn(obj, 'twofoldly.nested.value', 'b'); expect(obj.twofoldly.nested === newObj.twofoldly.nested).toEqual(false); // fails, same object still expect(obj).toEqual({ x: 'y', twofoldly: { nested: { value: 'a' } } }); // fails, it's b here, too expect(newObj).toEqual({ x: 'y', twofoldly: { nested: { value: 'b' } } }); // works ofc }); it('removes deep nested value', () => { const obj = { x: 'y', twofoldly: { nested: { value: 'a' } } }; const newObj = setIn(obj, 'twofoldly.nested.value', undefined); expect(obj.twofoldly.nested === newObj.twofoldly.nested).toEqual(false); expect(obj).toEqual({ x: 'y', twofoldly: { nested: { value: 'a' } } }); expect(newObj).toEqual({ x: 'y', twofoldly: { nested: {} } }); expect(newObj.twofoldly.nested).not.toHaveProperty('value'); }); it('shallow clone data along the update path', () => { const obj = { x: 'y', twofoldly: { nested: ['a', { c: 'd' }] }, other: { nestedOther: 'o' }, }; const newObj = setIn(obj, 'twofoldly.nested.0', 'b'); // All new objects/arrays created along the update path. expect(obj).not.toBe(newObj); expect(obj.twofoldly).not.toBe(newObj.twofoldly); expect(obj.twofoldly.nested).not.toBe(newObj.twofoldly.nested); // All other objects/arrays copied, not cloned (retain same memory // location). expect(obj.other).toBe(newObj.other); expect(obj.twofoldly.nested[1]).toBe(newObj.twofoldly.nested[1]); }); it('sets new array', () => { const obj = { x: 'y' }; const newObj = setIn(obj, 'nested.0', 'value'); expect(obj).toEqual({ x: 'y' }); expect(newObj).toEqual({ x: 'y', nested: ['value'] }); }); it('updates nested array value', () => { const obj = { x: 'y', nested: ['a'] }; const newObj = setIn(obj, 'nested[0]', 'b'); expect(obj).toEqual({ x: 'y', nested: ['a'] }); expect(newObj).toEqual({ x: 'y', nested: ['b'] }); }); it('adds new item to nested array', () => { const obj = { x: 'y', nested: ['a'] }; const newObj = setIn(obj, 'nested.1', 'b'); expect(obj).toEqual({ x: 'y', nested: ['a'] }); expect(newObj).toEqual({ x: 'y', nested: ['a', 'b'] }); }); it('sticks to object with int key when defined', () => { const obj = { x: 'y', nested: { 0: 'a' } }; const newObj = setIn(obj, 'nested.0', 'b'); expect(obj).toEqual({ x: 'y', nested: { 0: 'a' } }); expect(newObj).toEqual({ x: 'y', nested: { 0: 'b' } }); }); it('supports bracket path', () => { const obj = { x: 'y' }; const newObj = setIn(obj, 'nested[0]', 'value'); expect(obj).toEqual({ x: 'y' }); expect(newObj).toEqual({ x: 'y', nested: ['value'] }); }); it('supports path containing key of the object', () => { const obj = { x: 'y' }; const newObj = setIn(obj, 'a.x.c', 'value'); expect(obj).toEqual({ x: 'y' }); expect(newObj).toEqual({ x: 'y', a: { x: { c: 'value' } } }); }); it('should keep class inheritance for the top level object', () => { class TestClass { constructor(public key: string, public setObj?: any) {} } const obj = new TestClass('value'); const newObj = setIn(obj, 'setObj.nested', 'setInValue'); expect(obj).toEqual(new TestClass('value')); expect(newObj).toEqual({ key: 'value', setObj: { nested: 'setInValue' }, }); expect(obj instanceof TestClass).toEqual(true); expect(newObj instanceof TestClass).toEqual(true); }); it('can convert primitives to objects before setting', () => { const obj = { x: [{ y: true }] }; const newObj = setIn(obj, 'x.0.y.z', true); expect(obj).toEqual({ x: [{ y: true }] }); expect(newObj).toEqual({ x: [{ y: { z: true } }] }); }); }); describe('isPromise', () => { it('verifies that a value is a promise', () => { const alwaysResolve = (resolve: Function) => resolve(); const promise = new Promise(alwaysResolve); expect(isPromise(promise)).toEqual(true); }); it('verifies that a value is not a promise', () => { const emptyObject = {}; const identity = (i: any) => i; const foo = 'foo'; const answerToLife = 42; expect(isPromise(emptyObject)).toEqual(false); expect(isPromise(identity)).toEqual(false); expect(isPromise(foo)).toEqual(false); expect(isPromise(answerToLife)).toEqual(false); expect(isPromise(undefined)).toEqual(false); expect(isPromise(null)).toEqual(false); }); }); describe('getActiveElement', () => { it('test getActiveElement with undefined', () => { const result = getActiveElement(undefined); expect(result).toEqual(document.body); }); it('test getActiveElement with valid document', () => { const result = getActiveElement(document); expect(result).toEqual(document.body); }); }); describe('isNaN', () => { it('correctly validate NaN', () => { expect(isNaN(NaN)).toBe(true); }); it('correctly validate not NaN', () => { expect(isNaN(undefined)).toBe(false); expect(isNaN(1)).toBe(false); expect(isNaN('')).toBe(false); expect(isNaN([])).toBe(false); }); }); });
1,233
0
petrpan-code/jaredpalmer/formik/packages/formik
petrpan-code/jaredpalmer/formik/packages/formik/test/withFormik.test.tsx
import * as React from 'react'; import { act, render, waitFor } from '@testing-library/react'; import * as Yup from 'yup'; import { withFormik, FormikProps } from '../src'; import { noop } from './testHelpers'; interface Values { name: string; } const Form: React.FC<FormikProps<Values>> = ({ values, handleSubmit, handleChange, handleBlur, touched, setStatus, status, errors, isSubmitting, }) => { return ( <form onSubmit={handleSubmit}> <input type="text" onChange={handleChange} onBlur={handleBlur} value={values.name} name="name" /> {touched.name && errors.name && <div id="feedback">{errors.name}</div>} {isSubmitting && <div id="submitting">Submitting</div>} <button id="statusButton" type="button" onClick={() => setStatus({ myStatusMessage: 'True' })} > Call setStatus </button> {status && !!status.myStatusMessage && ( <div id="statusMessage">{status.myStatusMessage}</div> )} <button type="submit">Submit</button> </form> ); }; const InitialValues: Values = { name: 'jared' }; const renderWithFormik = (options?: any, props?: any) => { let injected: any; const FormikForm = withFormik<{}, Values>({ mapPropsToValues: () => InitialValues, handleSubmit: noop, ...options, })(props => (injected = props) && <Form {...props} />); return { getProps() { return injected; }, ...render(<FormikForm {...props} />), }; }; describe('withFormik()', () => { it('should initialize Formik state and pass down props', () => { const { getProps } = renderWithFormik(); const props = getProps(); expect(props).toEqual({ initialValues: { name: 'jared', }, initialErrors: {}, initialTouched: {}, values: { name: InitialValues.name, }, dirty: false, errors: {}, handleBlur: expect.any(Function), handleChange: expect.any(Function), handleReset: expect.any(Function), handleSubmit: expect.any(Function), isSubmitting: false, isValid: true, isValidating: false, getFieldProps: expect.any(Function), getFieldMeta: expect.any(Function), getFieldHelpers: expect.any(Function), registerField: expect.any(Function), resetForm: expect.any(Function), setErrors: expect.any(Function), setFieldError: expect.any(Function), setFieldTouched: expect.any(Function), setFieldValue: expect.any(Function), setFormikState: expect.any(Function), setStatus: expect.any(Function), setSubmitting: expect.any(Function), setTouched: expect.any(Function), setValues: expect.any(Function), submitCount: 0, submitForm: expect.any(Function), touched: {}, unregisterField: expect.any(Function), validateField: expect.any(Function), validateForm: expect.any(Function), validateOnBlur: true, validateOnMount: false, validateOnChange: true, }); }); it('should render child element', () => { const { container } = renderWithFormik(); expect(container.firstChild).toBeDefined(); }); it('calls validate with values and props', async () => { const validate = jest.fn(); const myProps = { my: 'prop' }; const { getProps } = renderWithFormik({ validate }, myProps); act(() => { getProps().submitForm(); }); await waitFor(() => expect(validate).toHaveBeenCalledWith({ name: 'jared' }, myProps) ); }); it('calls validationSchema', async () => { const validate = jest.fn(() => Promise.resolve()); const { getProps } = renderWithFormik({ validationSchema: { validate }, }); act(() => { getProps().submitForm(); }); await waitFor(() => expect(validate).toHaveBeenCalled()); }); it('calls validationSchema function with props', async () => { const validationSchema = jest.fn(() => Yup.object()); const myProps = { my: 'prop' }; const { getProps } = renderWithFormik( { validationSchema, }, myProps ); act(() => { getProps().submitForm(); }); await waitFor(() => expect(validationSchema).toHaveBeenCalledWith(myProps)); }); it('calls handleSubmit with values, actions and custom props', async () => { const handleSubmit = jest.fn(); const myProps = { my: 'prop' }; const { getProps } = renderWithFormik( { handleSubmit, }, myProps ); act(() => { getProps().submitForm(); }); await waitFor(() => expect(handleSubmit).toHaveBeenCalledWith( { name: 'jared' }, { props: myProps, resetForm: expect.any(Function), setErrors: expect.any(Function), setFieldError: expect.any(Function), setFieldTouched: expect.any(Function), setFieldValue: expect.any(Function), setFormikState: expect.any(Function), setStatus: expect.any(Function), setSubmitting: expect.any(Function), setTouched: expect.any(Function), setValues: expect.any(Function), validateField: expect.any(Function), validateForm: expect.any(Function), submitForm: expect.any(Function), } ) ); }); it('passes down custom props', () => { const { getProps } = renderWithFormik({}, { my: 'prop' }); expect(getProps().my).toEqual('prop'); }); // no ref, WONTFIX? // it('should correctly set displayName', () => { // const tree = mount(<BasicForm user={{ name: 'jared' }} />); // expect((tree.get(0).type as any).displayName).toBe('WithFormik(Form)'); // }); });
1,234
0
petrpan-code/jaredpalmer/formik/packages/formik
petrpan-code/jaredpalmer/formik/packages/formik/test/yupHelpers.test.ts
import * as Yup from 'yup'; import { validateYupSchema, yupToFormErrors } from '../src'; const schema = Yup.object().shape({ name: Yup.string().required('required'), field: Yup.string(), }); const nestedSchema = Yup.object().shape({ object: Yup.object().shape({ nestedField: Yup.string(), nestedArray: Yup.array().of(Yup.string().nullable(true)), }), }); const deepNestedSchema = Yup.object({ object: Yup.object({ nestedField: Yup.number().required(), }), object2: Yup.object({ nestedFieldWithRef: Yup.number().min(0).max(Yup.ref('$object.nestedField')), }), }); describe('Yup helpers', () => { describe('yupToFormErrors()', () => { it('should transform Yup ValidationErrors into an object', async () => { try { await schema.validate({}, { abortEarly: false }); } catch (e) { expect(yupToFormErrors(e)).toEqual({ name: 'required', }); } }); }); describe('validateYupSchema()', () => { it('should validate', async () => { try { await validateYupSchema({}, schema); } catch (e) { const err = e as Yup.ValidationError; expect(err.name).toEqual('ValidationError'); expect(err.errors).toEqual(['required']); } }); it('should stringify all values', async () => { try { const result = await validateYupSchema({ name: 1 }, schema); expect(result).not.toEqual({ name: 1 }); expect(result).toEqual({ name: '1' }); } catch (e) { throw e; } }); it('should set undefined empty strings', async () => { try { const result = await validateYupSchema( { name: 'foo', field: '' }, schema ); expect(result.field).toBeUndefined(); } catch (e) { throw e; } }); it('should set undefined nested empty strings', async () => { try { const result = await validateYupSchema( { name: 'foo', object: { nestedField: '' } }, nestedSchema ); expect(result.object!.nestedField).toBeUndefined(); } catch (e) { throw e; } }); it('should set undefined nested empty strings', async () => { try { const result = await validateYupSchema( { name: 'foo', object: { nestedField: 'swag', nestedArray: ['', 'foo', 'bar'] }, }, nestedSchema ); expect(result.object!.nestedArray!).toEqual([undefined, 'foo', 'bar']); } catch (e) { throw e; } }); it('should provide current values as context to enable deep object field validation', async () => { try { await validateYupSchema( { object: { nestedField: 23 }, object2: { nestedFieldWithRef: 24 } }, deepNestedSchema ); } catch (e) { expect((e as Yup.ValidationError).name).toEqual('ValidationError'); expect((e as Yup.ValidationError).errors).toEqual([ 'object2.nestedFieldWithRef must be less than or equal to 23', ]); } }); }); });
1,577
0
petrpan-code/jaredpalmer/after.js/packages/after.js
petrpan-code/jaredpalmer/after.js/packages/after.js/test/errorPage.test.tsx
import { vi } from 'vitest'; import { render as renderPage } from '../src'; import { Helmet } from 'react-helmet'; import Home from './components/Home'; import NonAsyncRedirect from './components/NonAsyncRedirectComponent'; import AsyncRedirectComponent from './components/AsyncRedirectComponent'; import UserDefined404Component from './components/UserDefined404Component'; import AsyncNotFound from './components/AsyncNotFoundComponent'; import DefaultNotFoundComponent from '../src/NotFoundComponent'; function render({ url, ...params }) { return renderPage({ req: { url }, ...params }); } describe('ErrorPage', () => { let res; const assets = { client: { css: '', js: '' } }; const chunks = { client: { css: [], js: [] } }; Helmet.canUseDOM = false; const routes = [{ path: '/', exact: true, component: Home }]; beforeEach(() => { res = { status: vi.fn(), redirect: vi.fn(), }; }); it('should set statusCode to 200', async () => { await render({ url: '/', res, routes, assets, chunks }); expect(res.status).toBeCalled(); expect(res.status).toBeCalledWith(200); expect(res.status).toBeCalledTimes(1); }); it('should set response header to 404', async () => { await render({ url: '/nope', res, routes, assets, chunks }); expect(res.status).toBeCalledWith(404); }); it('should set response header to 404 and show NotFound component (async)', async () => { const routes = [{ path: '/', component: AsyncNotFound }]; const result = await render({ url: '/', res, routes, assets, chunks }); expect(res.status).toBeCalledWith(404); expect(result).toContain(AsyncNotFound.data); }); it("should redirect to '/new-location' before react render (async)", async () => { const routes = [ { component: AsyncRedirectComponent, path: '/old-location' }, ]; const html = await render({ url: '/old-location', res, routes, assets, chunks, }); expect(res.redirect).toBeCalledWith(302, '/new-location'); expect(html).toEqual(''); }); it("should redirect to '/new-location' after react render", async () => { const routes = [{ component: NonAsyncRedirect, path: '/old-location' }]; const html = await render({ url: '/old-location', res, routes, assets, chunks, }); expect(res.redirect).toBeCalledWith(302, '/new-location'); expect(html).toContain(''); }); // user can define 404 Component in three ways // 1) { path: "*", Component: NotFoundComponent } // 2) { path: "**", Component: NotFoundComponent } // 3) { Component: NotFoundComponent } // path is undefined it("should render user defined 404 Component with '*' path in routes", async () => { const routes = [{ component: UserDefined404Component, path: '*' }]; const html = await render({ url: '/old-location', res, routes, assets, chunks, }); expect(res.status).toBeCalledWith(404); expect(html).toContain(UserDefined404Component.data); expect(html).not.toContain(DefaultNotFoundComponent.data); }); it("should render user defined 404 Component with '**' path in routes", async () => { const routes = [{ component: UserDefined404Component, path: '**' }]; const html = await render({ url: '/old-location', res, routes, assets, chunks, }); expect(res.status).toBeCalledWith(404); expect(html).toContain(UserDefined404Component.data); expect(html).not.toContain(DefaultNotFoundComponent.data); }); it('should render user defined 404 Component with undefined path in routes', async () => { const routes = [{ component: UserDefined404Component }]; const html = await render({ url: '/old-location', res, routes, assets, chunks, }); expect(res.status).toBeCalledWith(404); expect(html).toContain(UserDefined404Component.data); expect(html).not.toContain(DefaultNotFoundComponent.data); }); it('should render after.js default 404 Component when no user defined 404 Component is available', async () => { const html = await render({ url: '/nope', res, routes, assets, chunks }); expect(res.status).toBeCalledWith(404); expect(html).toContain(DefaultNotFoundComponent.data); expect(html).not.toContain(UserDefined404Component.data); }); });
1,578
0
petrpan-code/jaredpalmer/after.js/packages/after.js
petrpan-code/jaredpalmer/after.js/packages/after.js/test/getAssets.test.tsx
import { vi } from 'vitest'; import { getAssets as getRouteChunks, errorMeesage, AsyncRouteProps, asyncComponent, } from '../src'; import chunks from './chunks'; import routes from './routes'; import { matchPath } from 'react-router-dom'; // @ts-ignore import logger from 'razzle-dev-utils/logger'; function getRoute(url): AsyncRouteProps { const matchedComponent = routes.find((route: AsyncRouteProps) => { // matchPath dont't accept undifined path property // in <Switch> componet Child <Route> default path value is an empty string const match = matchPath(url, { ...route, path: route.path || '' }); return !!match; }); return matchedComponent; } function getAssets(url, route = getRoute(url)) { return getRouteChunks({ route, chunks }); } vi.mock('razzle-dev-utils/logger'); describe('getAssets', () => { test('for non-dynamic-import route should return empty array', () => { const requestUrl = '/non-dynamic-import'; const { scripts, styles } = getAssets(requestUrl); expect(scripts).toHaveLength(0); expect(styles).toHaveLength(0); }); test('for a async route should return styles and scripts from manifest', () => { const requestUrl = '/'; const chunkNameForRequestedUrl = 'components-Home'; const { scripts, styles } = getAssets(requestUrl); expect(scripts).toEqual(chunks[chunkNameForRequestedUrl].js); expect(styles).toEqual(chunks[chunkNameForRequestedUrl].css); }); test('should log and then throw error when chunkName is undefined and component is async', () => { const errorLoger = vi.fn(); logger.error.mockImplementation(errorLoger); const requestUrl = '/bad-route-config'; const route = { path: '/bad-route-config', component: asyncComponent({ loader: () => import('./components/Home') }), }; expect(() => { getAssets(requestUrl, route); }).toThrow(); expect(errorLoger).toBeCalledTimes(1); expect(errorLoger).toBeCalledWith(errorMeesage); }); });
1,579
0
petrpan-code/jaredpalmer/after.js/packages/after.js
petrpan-code/jaredpalmer/after.js/packages/after.js/test/loadInitialProps.test.tsx
import { loadInitialProps } from '../src'; import routes from './routes'; import { createMemoryHistory } from 'history'; import { History } from 'history'; describe('loadInitialProps', () => { let history: History; beforeEach(() => { history = createMemoryHistory(); }); it('should find matched component and call getInitialProps', async () => { const url = '/'; const matched = await loadInitialProps(url, routes, { history }); const expected = routes.find(r => r.path === url); expect(matched.match).toEqual(expected); expect(matched.data).toEqual({ stuff: 'home stuffs' }); }); it('should retrieve initial props from async call', async () => { const url = '/async-get-initial-props'; const matched = await loadInitialProps(url, routes, { history }); expect(matched.match.path).toBe(url); expect(matched.data).toEqual({ stuff: 'async call' }); }); it('should call getInitialProps for non dynamic import component', async () => { const url = '/non-dynamic-import'; const matched = await loadInitialProps(url, routes, { history }); expect(matched.match.path).toBe(url); expect(matched.data).toEqual({ stuff: 'non dynamic export' }); }); it('should call getInitialProps for non default export component', async () => { const url = '/non-default-export'; const matched = await loadInitialProps(url, routes, { history }); expect(matched.match.path).toBe(url); expect(matched.data).toEqual({ stuff: 'non default export' }); }); it('should load component with no getInitialProps', async () => { const url = '/no-get-initial-props'; const matched = await loadInitialProps(url, routes, { history }); expect(matched.match.path).toBe(url); expect(matched.data).toBeUndefined(); }); });
1,660
0
petrpan-code/jaredpalmer/react-fns/src/Network
petrpan-code/jaredpalmer/react-fns/src/Network/__tests__/Network.test.tsx
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { Network } from '../'; describe('<Network />', () => { describe('<Network render />', () => { const node = document.createElement('div'); afterEach(() => { ReactDOM.unmountComponentAtNode(node); }); it('receives { online } props', () => { ReactDOM.render( <Network render={props => console.log(props) || expect(props.online).toEqual(true) || null } />, node ); }); it('renders elements', () => { ReactDOM.render(<Network render={() => <div>online</div>} />, node); expect(node.innerHTML.includes('online')).toBe(true); }); }); });
1,661
0
petrpan-code/jaredpalmer/react-fns/src/Network
petrpan-code/jaredpalmer/react-fns/src/Network/__tests__/withNetwork.test.tsx
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { withNetwork } from '../'; describe('withNetwork()', () => { const node = document.createElement('div'); afterEach(() => { ReactDOM.unmountComponentAtNode(node); }); it('receives { online } props', () => { const hello = 'hi'; const WrappedComponent = withNetwork<{ hello: string }>( props => expect(props.online).toEqual(true) || null ); ReactDOM.render(<WrappedComponent hello={hello} />, node); }); // it('renders elements and passes thru props', () => { // const hello = 'hi'; // const WrappedComponent = withNetwork<{ hello: string }>(props => ( // <div> // x: {props.x}, y: {props.y} {hello} // </div> // )); // ReactDOM.render(<WrappedComponent hello={hello} />, node); // expect(node.innerHTML.includes('0')).toBe(true); // expect(node.innerHTML.includes('hi')).toBe(true); // }); });
1,665
0
petrpan-code/jaredpalmer/react-fns/src/Scroll
petrpan-code/jaredpalmer/react-fns/src/Scroll/__tests__/Scroll.test.tsx
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { Scroll } from '../Scroll'; describe('<Scroll />', () => { describe('<Scroll render />', () => { const node = document.createElement('div'); afterEach(() => { ReactDOM.unmountComponentAtNode(node); }); it('receives { x, y } props', () => { ReactDOM.render( <Scroll render={scrollProps => expect(scrollProps).toEqual({ x: 0, y: 0 }) || null } />, node ); }); it('renders elements', () => { ReactDOM.render( <Scroll render={scrollProps => ( <div> x: {scrollProps.x}, y: {scrollProps.y} </div> )} />, node ); expect(node.innerHTML.includes('0')).toBe(true); }); }); });
1,666
0
petrpan-code/jaredpalmer/react-fns/src/Scroll
petrpan-code/jaredpalmer/react-fns/src/Scroll/__tests__/withScroll.test.tsx
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { withScroll } from '../'; describe('withScroll()', () => { const node = document.createElement('div'); afterEach(() => { ReactDOM.unmountComponentAtNode(node); }); it('receives { x, y } props', () => { const hello = 'hi'; const WrappedComponent = withScroll<{ hello: string }>( props => expect(props).toEqual({ x: 0, y: 0, hello }) || null ); ReactDOM.render(<WrappedComponent hello={hello} />, node); }); it('renders elements and passes thru props', () => { const hello = 'hi'; const WrappedComponent = withScroll<{ hello: string }>(props => ( <div> x: {props.x}, y: {props.y} {hello} </div> )); ReactDOM.render(<WrappedComponent hello={hello} />, node); expect(node.innerHTML.includes('0')).toBe(true); expect(node.innerHTML.includes('hi')).toBe(true); }); });
1,670
0
petrpan-code/jaredpalmer/react-fns/src/WindowSize
petrpan-code/jaredpalmer/react-fns/src/WindowSize/__tests__/WindowSize.test.tsx
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { WindowSize } from '../WindowSize'; describe('<WindowSize />', () => { describe('<WindowSize render />', () => { const node = document.createElement('div'); afterEach(() => { ReactDOM.unmountComponentAtNode(node); }); it('receives { width, height } props', () => { ReactDOM.render( <WindowSize render={sizeProps => expect(sizeProps).toEqual({ width: 1024, height: 768 }) || null } />, node ); }); it('renders elements', () => { ReactDOM.render( <WindowSize render={sizeProps => ( <div> x: {sizeProps.width}, y: {sizeProps.width} </div> )} />, node ); expect(node.innerHTML.includes('0')).toBe(true); }); }); });
1,671
0
petrpan-code/jaredpalmer/react-fns/src/WindowSize
petrpan-code/jaredpalmer/react-fns/src/WindowSize/__tests__/withWindowSize.test.tsx
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { withWindowSize } from '../withWindowSize'; describe('withScroll()', () => { const node = document.createElement('div'); afterEach(() => { ReactDOM.unmountComponentAtNode(node); }); it('receives { width, height } props', () => { const hello = 'hi'; const WrappedComponent = withWindowSize<{ hello: string }>( props => expect(props).toEqual({ width: 1024, height: 768, hello }) || null ); ReactDOM.render(<WrappedComponent hello={hello} />, node); }); it('renders elements and passes thru props', () => { const hello = 'hi'; const WrappedComponent = withWindowSize<{ hello: string }>(props => ( <div> x: {props.height}, y: {props.width} {hello} </div> )); ReactDOM.render(<WrappedComponent hello={hello} />, node); expect(node.innerHTML.includes('1024')).toBe(true); expect(node.innerHTML.includes('768')).toBe(true); expect(node.innerHTML.includes('hi')).toBe(true); }); });
4,463
0
petrpan-code/novuhq/novu/packages/application-generic/src/usecases
petrpan-code/novuhq/novu/packages/application-generic/src/usecases/get-feature-flag/get-feature-flag.test.ts
import { GetIsApiRateLimitingEnabled, GetIsTemplateStoreEnabled, GetIsTopicNotificationEnabled, } from './index'; import { FeatureFlagCommand } from './get-feature-flag.command'; import { FeatureFlagsService } from '../../services'; const originalLaunchDarklySdkKey = process.env.LAUNCH_DARKLY_SDK_KEY; describe('Get Feature Flag', () => { let featureFlagCommand: FeatureFlagCommand; describe('Provider: Launch Darkly', () => { describe('No SDK key environment variable is set', () => { beforeEach(async () => { process.env.LAUNCH_DARKLY_SDK_KEY = ''; featureFlagCommand = FeatureFlagCommand.create({ environmentId: 'environmentId', organizationId: 'organizationId', userId: 'userId', }); }); describe('IS_TEMPLATE_STORE_ENABLED', () => { it('should return default hardcoded value when no SDK env is set and no feature flag is set', async () => { process.env.IS_TEMPLATE_STORE_ENABLED = ''; const getIsTemplateStoreEnabled = new GetIsTemplateStoreEnabled( new FeatureFlagsService() ); const result = await getIsTemplateStoreEnabled.execute( featureFlagCommand ); expect(result).toEqual(false); }); it('should return env variable value when no SDK env is set but the feature flag is set', async () => { process.env.IS_TEMPLATE_STORE_ENABLED = 'true'; const getIsTemplateStoreEnabled = new GetIsTemplateStoreEnabled( new FeatureFlagsService() ); const result = await getIsTemplateStoreEnabled.execute( featureFlagCommand ); expect(result).toEqual(true); }); }); describe('IS_TOPIC_NOTIFICATION_ENABLED', () => { it('should return default hardcoded value when no SDK env is set and no feature flag is set', async () => { process.env.FF_IS_TOPIC_NOTIFICATION_ENABLED = ''; const getIsTopicNotificationEnabled = new GetIsTopicNotificationEnabled(new FeatureFlagsService()); const result = await getIsTopicNotificationEnabled.execute( featureFlagCommand ); expect(result).toEqual(true); }); it('should return env variable value when no SDK env is set but the feature flag is set', async () => { process.env.FF_IS_TOPIC_NOTIFICATION_ENABLED = 'false'; const getIsTopicNotificationEnabled = new GetIsTopicNotificationEnabled(new FeatureFlagsService()); const result = await getIsTopicNotificationEnabled.execute( featureFlagCommand ); expect(result).toEqual(false); }); }); describe('IS_API_RATE_LIMITING_ENABLED', () => { it('should return default hardcoded value when no SDK env is set and no feature flag is set', async () => { process.env.IS_API_RATE_LIMITING_ENABLED = ''; const getIsApiRateLimitingEnabled = new GetIsApiRateLimitingEnabled( new FeatureFlagsService() ); const result = await getIsApiRateLimitingEnabled.execute( featureFlagCommand ); expect(result).toEqual(false); }); it('should return env variable value when no SDK env is set but the feature flag is set', async () => { process.env.IS_API_RATE_LIMITING_ENABLED = 'true'; const getIsApiRateLimitingEnabled = new GetIsApiRateLimitingEnabled( new FeatureFlagsService() ); const result = await getIsApiRateLimitingEnabled.execute( featureFlagCommand ); expect(result).toEqual(true); }); }); }); describe('SDK key environment variable is set', () => { beforeEach(async () => { process.env.LAUNCH_DARKLY_SDK_KEY = originalLaunchDarklySdkKey; featureFlagCommand = FeatureFlagCommand.create({ environmentId: 'environmentId', organizationId: 'organizationId', userId: 'userId', }); }); describe('IS_TEMPLATE_STORE_ENABLED', () => { it(`should get the feature flag value stored in Launch Darkly (enabled) when the SDK key env variable is set regardless of the feature flag set`, async () => { process.env.IS_TEMPLATE_STORE_ENABLED = 'false'; const getIsTemplateStoreEnabled = new GetIsTemplateStoreEnabled( new FeatureFlagsService() ); const result = await getIsTemplateStoreEnabled.execute( featureFlagCommand ); expect(result).toEqual(true); }); }); describe('IS_TOPIC_NOTIFICATION_ENABLED', () => { it(`should get the feature flag value stored in Launch Darkly (enabled) when the SDK key env variable is set regardless of the feature flag set`, async () => { process.env.FF_IS_TOPIC_NOTIFICATION_ENABLED = 'false'; const getIsTopicNotificationEnabled = new GetIsTopicNotificationEnabled(new FeatureFlagsService()); const result = await getIsTopicNotificationEnabled.execute( featureFlagCommand ); expect(result).toEqual(true); }); }); }); }); });
4,469
0
petrpan-code/novuhq/novu/packages/application-generic/src/usecases
petrpan-code/novuhq/novu/packages/application-generic/src/usecases/get-feature-flag/get-system-critical-flag.test.ts
import { GetIsInMemoryClusterModeEnabled } from './index'; describe('Get System Critical Flag', () => { describe('SystemCriticalFlagEnum.IS_IN_MEMORY_CLUSTER_MODE_ENABLED', () => { it('should return default hardcoded value when no environment variable is set', async () => { // TODO: Temporary coexistence to replace env variable name process.env.IS_IN_MEMORY_CLUSTER_MODE_ENABLED = ''; process.env.IN_MEMORY_CLUSTER_MODE_ENABLED = ''; const getIsInMemoryClusterModeEnabled = new GetIsInMemoryClusterModeEnabled(); const result = getIsInMemoryClusterModeEnabled.execute(); expect(result).toEqual(false); }); it('should return old environment variable value when no new environment variable is set', async () => { // TODO: Temporary coexistence to replace env variable name process.env.IS_IN_MEMORY_CLUSTER_MODE_ENABLED = ''; process.env.IN_MEMORY_CLUSTER_MODE_ENABLED = 'true'; const getIsInMemoryClusterModeEnabled = new GetIsInMemoryClusterModeEnabled(); const result = getIsInMemoryClusterModeEnabled.execute(); expect(result).toEqual(true); }); it('should return new environment variable value when is set', async () => { // TODO: Temporary coexistence to replace env variable name process.env.IS_IN_MEMORY_CLUSTER_MODE_ENABLED = 'true'; process.env.IN_MEMORY_CLUSTER_MODE_ENABLED = 'false'; const getIsInMemoryClusterModeEnabled = new GetIsInMemoryClusterModeEnabled(); const result = getIsInMemoryClusterModeEnabled.execute(); expect(result).toEqual(true); }); it('should return new environment variable value when is set even if it is false', async () => { // TODO: Temporary coexistence to replace env variable name process.env.IS_IN_MEMORY_CLUSTER_MODE_ENABLED = 'false'; process.env.IN_MEMORY_CLUSTER_MODE_ENABLED = 'true'; const getIsInMemoryClusterModeEnabled = new GetIsInMemoryClusterModeEnabled(); const result = getIsInMemoryClusterModeEnabled.execute(); expect(result).toEqual(false); }); }); });
4,592
0
petrpan-code/novuhq/novu/packages/headless/src
petrpan-code/novuhq/novu/packages/headless/src/lib/headless.service.test.ts
import { ApiService, IUserGlobalPreferenceSettings, IUserPreferenceSettings, } from '@novu/client'; import { WebSocketEventEnum } from '@novu/shared'; import io from 'socket.io-client'; import { ChannelCTATypeEnum, ChannelTypeEnum, IMessage, IOrganizationEntity, ButtonTypeEnum, MessageActionStatusEnum, } from '@novu/shared'; import { ISession } from '../utils/types'; import { HeadlessService, NOTIFICATION_CENTER_TOKEN_KEY, } from './headless.service'; const promiseResolveTimeout = (ms: number, arg: unknown = {}) => new Promise((resolve) => setTimeout(resolve, ms, arg)); const promiseRejectTimeout = (ms: number, arg: unknown = {}) => new Promise((resolve, reject) => setTimeout(reject, ms, arg)); const templateId = 'templateId'; const notificationId = 'notificationId'; const mockSession: ISession = { token: 'token', profile: { _id: '_id', firstName: 'firstName', lastName: 'lastName', email: 'email', organizationId: 'organizationId?', environmentId: 'environmentId', aud: 'widget_user', subscriberId: '1234ABCD', }, }; const mockOrganization: IOrganizationEntity = { _id: '_id', name: 'mock organization', members: [], }; const mockUnseenCount = { count: 99 }; const mockUnreadCount = { count: 101 }; const mockNotification: IMessage = { _id: notificationId, _templateId: templateId, _environmentId: '_environmentId', _organizationId: '_organizationId', _notificationId: '_notificationId', _subscriberId: '_subscriberId', templateIdentifier: 'templateIdentifier', content: 'content', channel: ChannelTypeEnum.IN_APP, seen: false, read: false, lastSeenDate: 'lastSeenDate', lastReadDate: 'lastReadDate', createdAt: 'createdAt', cta: { type: ChannelCTATypeEnum.REDIRECT, data: {}, action: { status: MessageActionStatusEnum.PENDING, buttons: [{ type: ButtonTypeEnum.PRIMARY, content: 'button' }], result: { payload: {}, type: ButtonTypeEnum.PRIMARY, }, }, }, _feedId: '_feedId', payload: {}, }; const mockNotificationsList: Array<IMessage> = [mockNotification]; const mockUserPreferenceSetting: IUserPreferenceSettings = { template: { _id: templateId, name: 'mock template', critical: false }, preference: { enabled: true, channels: { email: true, sms: true, in_app: true, chat: true, push: true, }, }, }; const mockUserGlobalPreferenceSetting: IUserGlobalPreferenceSettings = { preference: { enabled: true, channels: { email: true, sms: true, in_app: true, chat: true, push: true, }, }, }; const mockUserPreferences = [mockUserPreferenceSetting]; const mockServiceInstance = { initializeSession: jest.fn(() => promiseResolveTimeout(0, mockSession)), setAuthorizationToken: jest.fn(), disposeAuthorizationToken: jest.fn(), getOrganization: jest.fn(() => promiseResolveTimeout(0, mockOrganization)), getUnseenCount: jest.fn(() => promiseResolveTimeout(0, mockUnseenCount)), getUnreadCount: jest.fn(() => promiseResolveTimeout(0, mockUnreadCount)), getUserPreference: jest.fn(() => promiseResolveTimeout(0, mockUserPreferences) ), getNotificationsList: jest.fn(() => promiseResolveTimeout(0, mockNotificationsList) ), updateSubscriberPreference: jest.fn(() => promiseResolveTimeout(0, mockUserPreferenceSetting) ), updateSubscriberGlobalPreference: jest.fn(() => promiseResolveTimeout(0, mockUserGlobalPreferenceSetting) ), markMessageAs: jest.fn(), removeMessage: jest.fn(), updateAction: jest.fn(), markAllMessagesAsRead: jest.fn(), markAllMessagesAsSeen: jest.fn(), removeAllMessages: jest.fn(), }; jest.mock('@novu/client', () => ({ ...jest.requireActual<typeof import('@novu/client')>('@novu/client'), ApiService: jest.fn().mockImplementation(() => mockServiceInstance), })); const mockSocket = { on: jest.fn(), off: jest.fn(), }; jest.mock('socket.io-client', () => ({ ...jest.requireActual<typeof import('socket.io-client')>('socket.io-client'), __esModule: true, default: jest.fn().mockImplementation(() => mockSocket), })); jest.spyOn(Storage.prototype, 'getItem'); jest.spyOn(Storage.prototype, 'setItem'); jest.spyOn(Storage.prototype, 'removeItem'); Storage.prototype.getItem = jest.fn(); Storage.prototype.setItem = jest.fn(); Storage.prototype.removeItem = jest.fn(); describe('headless.service', () => { const options = { backendUrl: 'http://localhost:3000', socketUrl: 'http://localhost:3001', applicationIdentifier: 'applicationIdentifier', subscriberId: 'subscriberId', subscriberHash: 'subscriberHash', config: { retry: 0, retryDelay: 0, }, }; describe('constructor', () => { test('sets the options', () => { const headlessService = new HeadlessService(options); expect(ApiService).toHaveBeenCalledWith(options.backendUrl); expect((headlessService as any).options).toEqual(options); expect((headlessService as any).queryClient).not.toBeUndefined(); expect((headlessService as any).queryService).not.toBeUndefined(); expect(localStorage.getItem).toHaveBeenCalledWith( NOTIFICATION_CENTER_TOKEN_KEY ); }); test.skip('when there is no token should call disposeAuthorizationToken', () => { expect(localStorage.getItem).toHaveBeenCalledWith( NOTIFICATION_CENTER_TOKEN_KEY ); expect(mockServiceInstance.disposeAuthorizationToken).toBeCalledTimes(1); expect(localStorage.removeItem).toHaveBeenCalledWith( NOTIFICATION_CENTER_TOKEN_KEY ); }); test.skip('when there is a token should call setAuthorizationToken', () => { const mockToken = 'mock-token'; jest.spyOn(Storage.prototype, 'setItem'); Storage.prototype.getItem = jest .fn() .mockImplementationOnce(() => mockToken); expect(mockServiceInstance.setAuthorizationToken).toHaveBeenCalledWith( mockToken ); expect(localStorage.setItem).toHaveBeenCalledWith( NOTIFICATION_CENTER_TOKEN_KEY, mockToken ); }); }); describe('initializeSession', () => { test('calls initializeSession successfully', async () => { const headlessService = new HeadlessService(options); const listener = jest.fn(); const onSuccess = jest.fn(); headlessService.initializeSession({ listener, onSuccess, }); expect((headlessService as any).session).toBeNull(); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(0); expect(mockServiceInstance.initializeSession).toBeCalledTimes(1); expect((headlessService as any).session).toEqual(mockSession); expect(localStorage.setItem).toHaveBeenCalledWith( NOTIFICATION_CENTER_TOKEN_KEY, mockSession.token ); expect(mockServiceInstance.setAuthorizationToken).toHaveBeenCalledWith( mockSession.token ); expect(io).toHaveBeenNthCalledWith( 1, options.socketUrl, expect.objectContaining({ reconnectionDelayMax: 10000, transports: ['websocket'], query: { token: `${mockSession.token}`, }, }) ); expect(mockSocket.on).toHaveBeenNthCalledWith( 1, 'connect_error', expect.any(Function) ); expect(onSuccess).toHaveBeenNthCalledWith(1, mockSession); }); test('handles the error', async () => { const error = new Error('error'); mockServiceInstance.initializeSession.mockImplementationOnce(() => promiseRejectTimeout(0, error) ); const headlessService = new HeadlessService(options); const listener = jest.fn(); const onError = jest.fn(); headlessService.initializeSession({ listener, onError, }); expect((headlessService as any).session).toBeNull(); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(0); expect(mockServiceInstance.initializeSession).toBeCalledTimes(1); expect(onError).toHaveBeenCalledWith(error); expect((headlessService as any).session).toBeNull(); expect(listener).toHaveBeenNthCalledWith( 2, expect.objectContaining({ isLoading: false, data: undefined, error }) ); }); }); describe('fetchOrganization', () => { test('calls fetchOrganization successfully', async () => { const headlessService = new HeadlessService(options); const listener = jest.fn(); const onSuccess = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchOrganization({ listener, onSuccess, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(0); expect(mockServiceInstance.getOrganization).toBeCalledTimes(1); expect(onSuccess).toHaveBeenNthCalledWith(1, mockOrganization); }); test('handles the error', async () => { const error = new Error('error'); mockServiceInstance.getOrganization.mockImplementationOnce(() => promiseRejectTimeout(0, error) ); const headlessService = new HeadlessService(options); const listener = jest.fn(); const onError = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchOrganization({ listener, onError, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(0); expect(mockServiceInstance.getOrganization).toBeCalledTimes(1); expect(onError).toHaveBeenCalledWith(error); expect(listener).toHaveBeenNthCalledWith( 2, expect.objectContaining({ isLoading: false, data: undefined, error }) ); }); }); describe('fetchUnseenCount', () => { test('calls fetchUnseenCount successfully', async () => { const headlessService = new HeadlessService(options); const listener = jest.fn(); const onSuccess = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchUnseenCount({ listener, onSuccess, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(0); expect(mockServiceInstance.getUnseenCount).toBeCalledTimes(1); expect(onSuccess).toHaveBeenNthCalledWith(1, mockUnseenCount); }); test('handles the error', async () => { const error = new Error('error'); mockServiceInstance.getUnseenCount.mockImplementationOnce(() => promiseRejectTimeout(0, error) ); const headlessService = new HeadlessService(options); const listener = jest.fn(); const onError = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchUnseenCount({ listener, onError, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(0); expect(mockServiceInstance.getUnseenCount).toBeCalledTimes(1); expect(onError).toHaveBeenCalledWith(error); expect(listener).toHaveBeenNthCalledWith( 2, expect.objectContaining({ isLoading: false, data: undefined, error }) ); }); }); describe('fetchUnreadCount', () => { test('calls fetchUnreadCount successfully', async () => { const headlessService = new HeadlessService(options); const listener = jest.fn(); const onSuccess = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchUnreadCount({ listener, onSuccess, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(0); expect(mockServiceInstance.getUnreadCount).toBeCalledTimes(1); expect(onSuccess).toHaveBeenNthCalledWith(1, mockUnreadCount); }); test('handles the error', async () => { const error = new Error('error'); mockServiceInstance.getUnreadCount.mockImplementationOnce(() => promiseRejectTimeout(0, error) ); const headlessService = new HeadlessService(options); const listener = jest.fn(); const onError = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchUnreadCount({ listener, onError, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(0); expect(mockServiceInstance.getUnreadCount).toBeCalledTimes(1); expect(onError).toHaveBeenCalledWith(error); expect(listener).toHaveBeenNthCalledWith( 2, expect.objectContaining({ isLoading: false, data: undefined, error }) ); }); }); describe('fetchNotifications', () => { test('calls fetchNotifications successfully', async () => { const headlessService = new HeadlessService(options); const listener = jest.fn(); const onSuccess = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchNotifications({ listener, onSuccess, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(0); expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(1); expect(onSuccess).toHaveBeenNthCalledWith(1, mockNotificationsList); expect(listener).toHaveBeenCalledTimes(2); expect(listener).toHaveBeenNthCalledWith( 2, expect.objectContaining({ isLoading: false, data: mockNotificationsList, }) ); }); test('will return the cached data', async () => { const headlessService = new HeadlessService(options); const listener1 = jest.fn(); const onSuccess1 = jest.fn(); (headlessService as any).session = mockSession; // fetch headlessService.fetchNotifications({ listener: listener1, onSuccess: onSuccess1, }); expect(listener1).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(0); expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(1); expect(onSuccess1).toHaveBeenNthCalledWith(1, mockNotificationsList); // fetch again const listener2 = jest.fn(); const onSuccess2 = jest.fn(); headlessService.fetchNotifications({ listener: listener2, onSuccess: onSuccess2, }); expect(listener2).toHaveBeenCalledTimes(1); expect(listener2).toBeCalledWith( expect.objectContaining({ isLoading: false, data: mockNotificationsList, }) ); }); test('handles the error', async () => { const error = new Error('error'); mockServiceInstance.getNotificationsList.mockImplementationOnce(() => promiseRejectTimeout(0, error) ); const headlessService = new HeadlessService(options); const listener = jest.fn(); const onError = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchNotifications({ listener, onError, }); expect(listener).toBeCalledTimes(1); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(0); expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(1); expect(onError).toHaveBeenCalledWith(error); expect(listener).toHaveBeenNthCalledWith( 2, expect.objectContaining({ isLoading: false, data: undefined, error }) ); }); }); describe('listenNotificationReceive', () => { test('calls listenNotificationReceive successfully', async () => { // when const mockedMessage = { test: 'hello' }; const headlessService = new HeadlessService(options); const messageListener = jest.fn(); const notificationsListener = jest.fn(); const mockedSocket = { on: jest.fn((type, callback) => { if (type === WebSocketEventEnum.RECEIVED) { callback({ message: mockedMessage }); } }), off: jest.fn(), }; (headlessService as any).session = mockSession; (headlessService as any).socket = mockedSocket; // fetch notifications before, the listenNotificationReceive will clear notifications cache headlessService.fetchNotifications({ listener: notificationsListener, }); await promiseResolveTimeout(0); // then headlessService.listenNotificationReceive({ listener: messageListener, }); await promiseResolveTimeout(0); // check results expect(mockedSocket.on).toHaveBeenNthCalledWith( 1, WebSocketEventEnum.RECEIVED, expect.any(Function) ); expect(messageListener).toHaveBeenCalledWith(mockedMessage); // should fetch the notifications again, because the cache should be cleared const onNotificationsListSuccess = jest.fn(); headlessService.fetchNotifications({ listener: notificationsListener, onSuccess: onNotificationsListSuccess, onError: (error) => { console.log({ error }); }, }); await promiseResolveTimeout(0); expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(2); expect(notificationsListener).toHaveBeenCalledTimes(4); expect(notificationsListener).toHaveBeenNthCalledWith( 4, expect.objectContaining({ isLoading: false, data: mockNotificationsList, }) ); expect(onNotificationsListSuccess).toHaveBeenNthCalledWith( 1, mockNotificationsList ); }); test('should unsubscribe', async () => { // when const headlessService = new HeadlessService(options); const listener = jest.fn(); const mockedSocket = { on: jest.fn(), off: jest.fn(), }; (headlessService as any).session = mockSession; (headlessService as any).socket = mockedSocket; // then const unsubscribe = headlessService.listenUnseenCountChange({ listener, }); unsubscribe(); expect(mockedSocket.off).toHaveBeenCalledWith(WebSocketEventEnum.UNSEEN); }); }); describe('listenUnseenCountChange', () => { test('calls listenUnseenCountChange successfully', async () => { // when const mockedUnseenCount = { unseenCount: 101 }; const headlessService = new HeadlessService(options); const listener = jest.fn(); const unseenCountListener = jest.fn(); const notificationsListener = jest.fn(); const mockedSocket = { on: jest.fn((type, callback) => { if (type === WebSocketEventEnum.UNSEEN) { callback(mockedUnseenCount); } }), off: jest.fn(), }; (headlessService as any).session = mockSession; (headlessService as any).socket = mockedSocket; // fetch unseen count before, the listenUnseenCountChange will update it later headlessService.fetchUnseenCount({ listener: unseenCountListener, }); await promiseResolveTimeout(0); // fetch notifications before, the listenUnseenCountChange will clear notifications cache headlessService.fetchNotifications({ listener: notificationsListener, }); await promiseResolveTimeout(0); // then headlessService.listenUnseenCountChange({ listener, }); await promiseResolveTimeout(0); // check results expect(mockedSocket.on).toHaveBeenNthCalledWith( 1, WebSocketEventEnum.UNSEEN, expect.any(Function) ); expect(listener).toHaveBeenCalledWith(mockedUnseenCount.unseenCount); expect(unseenCountListener).toHaveBeenNthCalledWith( 3, expect.objectContaining({ data: { count: mockedUnseenCount.unseenCount }, }) ); // should fetch the notifications again, because the cache should be cleared const onNotificationsListSuccess = jest.fn(); headlessService.fetchNotifications({ listener: notificationsListener, onSuccess: onNotificationsListSuccess, onError: (error) => { console.log({ error }); }, }); await promiseResolveTimeout(0); expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(2); expect(notificationsListener).toHaveBeenCalledTimes(4); expect(notificationsListener).toHaveBeenNthCalledWith( 4, expect.objectContaining({ isLoading: false, data: mockNotificationsList, }) ); expect(onNotificationsListSuccess).toHaveBeenNthCalledWith( 1, mockNotificationsList ); }); test('should unsubscribe', async () => { // when const headlessService = new HeadlessService(options); const listener = jest.fn(); const mockedSocket = { on: jest.fn(), off: jest.fn(), }; (headlessService as any).session = mockSession; (headlessService as any).socket = mockedSocket; // then const unsubscribe = headlessService.listenUnseenCountChange({ listener, }); unsubscribe(); expect(mockedSocket.off).toHaveBeenCalledWith(WebSocketEventEnum.UNSEEN); }); }); describe('listenUnreadCountChange', () => { test('calls listenUnreadCountChange successfully', async () => { // when const mockedUnreadCount = { unreadCount: 101 }; const headlessService = new HeadlessService(options); const listener = jest.fn(); const unreadCountListener = jest.fn(); const notificationsListener = jest.fn(); const mockedSocket = { on: jest.fn((type, callback) => { if (type === WebSocketEventEnum.UNREAD) { callback(mockedUnreadCount); } }), off: jest.fn(), }; (headlessService as any).session = mockSession; (headlessService as any).socket = mockedSocket; // fetch unseen count before, the listenUnreadCountChange will update it later headlessService.fetchUnreadCount({ listener: unreadCountListener, }); await promiseResolveTimeout(0); // fetch notifications before, the listenUnreadCountChange will clear notifications cache headlessService.fetchNotifications({ listener: notificationsListener, }); await promiseResolveTimeout(0); // then headlessService.listenUnreadCountChange({ listener, }); await promiseResolveTimeout(0); // check results expect(mockedSocket.on).toHaveBeenNthCalledWith( 1, WebSocketEventEnum.UNREAD, expect.any(Function) ); expect(listener).toHaveBeenCalledWith(mockedUnreadCount.unreadCount); expect(unreadCountListener).toHaveBeenNthCalledWith( 3, expect.objectContaining({ data: { count: mockedUnreadCount.unreadCount }, }) ); // should fetch the notifications again, because the cache should be cleared const onNotificationsListSuccess = jest.fn(); headlessService.fetchNotifications({ listener: notificationsListener, onSuccess: onNotificationsListSuccess, onError: (error) => { console.log({ error }); }, }); await promiseResolveTimeout(0); expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(2); expect(notificationsListener).toHaveBeenCalledTimes(4); expect(notificationsListener).toHaveBeenNthCalledWith( 4, expect.objectContaining({ isLoading: false, data: mockNotificationsList, }) ); expect(onNotificationsListSuccess).toHaveBeenNthCalledWith( 1, mockNotificationsList ); }); test('should unsubscribe', async () => { // when const headlessService = new HeadlessService(options); const listener = jest.fn(); const mockedSocket = { on: jest.fn(), off: jest.fn(), }; (headlessService as any).session = mockSession; (headlessService as any).socket = mockedSocket; // then const unsubscribe = headlessService.listenUnreadCountChange({ listener, }); unsubscribe(); expect(mockedSocket.off).toHaveBeenCalledWith(WebSocketEventEnum.UNREAD); }); }); describe('fetchUserPreferences', () => { test('calls fetchUserPreferences successfully', async () => { const headlessService = new HeadlessService(options); const listener = jest.fn(); const onSuccess = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchUserPreferences({ listener, onSuccess, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(0); expect(mockServiceInstance.getUserPreference).toBeCalledTimes(1); expect(onSuccess).toHaveBeenNthCalledWith(1, mockUserPreferences); }); test('handles the error', async () => { const error = new Error('error'); mockServiceInstance.getUserPreference.mockImplementationOnce(() => promiseRejectTimeout(0, error) ); const headlessService = new HeadlessService(options); const listener = jest.fn(); const onError = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchUserPreferences({ listener, onError, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(0); expect(mockServiceInstance.getUserPreference).toBeCalledTimes(1); expect(onError).toHaveBeenCalledWith(error); expect(listener).toHaveBeenNthCalledWith( 2, expect.objectContaining({ isLoading: false, data: undefined, error }) ); }); }); describe('updateUserPreferences', () => { test('calls updateUserPreferences successfully', async () => { const channelType = 'chat'; const checked = false; const updatedUserPreferenceSetting = { ...mockUserPreferenceSetting, preference: { enabled: true, channels: { email: true, sms: true, in_app: true, chat: false, push: true, }, }, }; mockServiceInstance.updateSubscriberPreference.mockImplementationOnce( () => promiseResolveTimeout(0, updatedUserPreferenceSetting) ); const headlessService = new HeadlessService(options); const fetchUserPreferencesListener = jest.fn(); const listener = jest.fn(); const onSuccess = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchUserPreferences({ listener: fetchUserPreferencesListener, }); await promiseResolveTimeout(0); expect(fetchUserPreferencesListener).toHaveBeenCalledTimes(2); headlessService.updateUserPreferences({ templateId, channelType, checked, listener, onSuccess, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(100); expect(mockServiceInstance.updateSubscriberPreference).toBeCalledTimes(1); expect(onSuccess).toHaveBeenNthCalledWith( 1, updatedUserPreferenceSetting ); expect(fetchUserPreferencesListener).toHaveBeenNthCalledWith( 3, expect.objectContaining({ data: [updatedUserPreferenceSetting], }) ); }); test('handles the error', async () => { const channelType = 'chat'; const checked = false; const error = new Error('error'); mockServiceInstance.updateSubscriberPreference.mockImplementationOnce( () => promiseRejectTimeout(0, error) ); const headlessService = new HeadlessService(options); const listener = jest.fn(); const onError = jest.fn(); (headlessService as any).session = mockSession; headlessService.updateUserPreferences({ templateId, channelType, checked, listener, onError, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(100); expect(mockServiceInstance.updateSubscriberPreference).toBeCalledTimes(1); expect(onError).toHaveBeenCalledWith(error); expect(listener).toHaveBeenNthCalledWith( 2, expect.objectContaining({ isLoading: false, data: undefined, error }) ); }); }); describe('updateUserGlobalPreferences', () => { test('calls updateUserGlobalPreferences successfully', async () => { const payload = { enabled: true, preferences: [ { channelType: ChannelTypeEnum.EMAIL, enabled: false, }, ], }; const updatedUserGlobalPreferenceSetting = { preference: { enabled: true, channels: { email: false, }, }, }; mockServiceInstance.updateSubscriberGlobalPreference.mockImplementationOnce( () => promiseResolveTimeout(0, updatedUserGlobalPreferenceSetting) ); const headlessService = new HeadlessService(options); const listener = jest.fn(); const onSuccess = jest.fn(); (headlessService as any).session = mockSession; headlessService.updateUserGlobalPreferences({ preferences: payload.preferences, enabled: payload.enabled, listener, onSuccess, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(100); expect( mockServiceInstance.updateSubscriberGlobalPreference ).toBeCalledTimes(1); expect(onSuccess).toHaveBeenNthCalledWith( 1, updatedUserGlobalPreferenceSetting ); }); test('handles the error', async () => { const payload = { enabled: true, preferences: [ { channelType: ChannelTypeEnum.EMAIL, enabled: true, }, ], }; const error = new Error('error'); mockServiceInstance.updateSubscriberGlobalPreference.mockImplementationOnce( () => promiseRejectTimeout(0, error) ); const headlessService = new HeadlessService(options); const listener = jest.fn(); const onError = jest.fn(); (headlessService as any).session = mockSession; headlessService.updateUserGlobalPreferences({ preferences: payload.preferences, enabled: payload.enabled, listener, onError, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(100); expect( mockServiceInstance.updateSubscriberGlobalPreference ).toBeCalledTimes(1); expect(onError).toHaveBeenCalledWith(error); expect(listener).toHaveBeenNthCalledWith( 2, expect.objectContaining({ isLoading: false, data: undefined, error }) ); }); }); describe('markNotificationsAsRead', () => { test('calls markNotificationsAsRead successfully', async () => { const updatedNotification = { ...mockNotification, seen: true, read: true, }; mockServiceInstance.markMessageAs.mockImplementationOnce(() => promiseResolveTimeout(0, [updatedNotification]) ); mockServiceInstance.getNotificationsList.mockImplementationOnce(() => promiseResolveTimeout(0, [updatedNotification]) ); const headlessService = new HeadlessService(options); const markNotificationsAsReadListener = jest.fn(); const fetchNotificationsListener = jest.fn(); const onSuccess = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchNotifications({ listener: fetchNotificationsListener, }); await promiseResolveTimeout(0); expect(fetchNotificationsListener).toHaveBeenCalledTimes(2); headlessService.markNotificationsAsRead({ messageId: notificationId, listener: markNotificationsAsReadListener, onSuccess, }); expect(markNotificationsAsReadListener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(300); expect(mockServiceInstance.markMessageAs).toBeCalledTimes(1); expect(onSuccess).toHaveBeenNthCalledWith(1, [updatedNotification]); expect(fetchNotificationsListener).toHaveBeenNthCalledWith( 3, expect.objectContaining({ data: [updatedNotification], error: null, isError: false, isFetching: true, isLoading: false, status: 'success', }) ); }); test('handles the error', async () => { const error = new Error('error'); mockServiceInstance.markMessageAs.mockImplementationOnce(() => promiseRejectTimeout(0, error) ); const headlessService = new HeadlessService(options); const listener = jest.fn(); const onError = jest.fn(); (headlessService as any).session = mockSession; headlessService.markNotificationsAsRead({ messageId: notificationId, listener, onError, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(100); expect(mockServiceInstance.markMessageAs).toBeCalledTimes(1); expect(onError).toHaveBeenCalledWith(error); expect(listener).toHaveBeenNthCalledWith( 2, expect.objectContaining({ isLoading: false, data: undefined, error }) ); }); }); describe('markNotificationsAs', () => { const PAYLOADS = [ { seen: true }, { seen: false }, { seen: true, read: false }, { seen: false, read: true }, { seen: false, read: false }, { seen: true, read: true }, { read: true }, { read: false }, ]; test.each(PAYLOADS)( 'calls markNotificationsAs successfully with payload: %s', async (payload) => { const updatedNotification = { ...mockNotification, ...payload, }; mockServiceInstance.markMessageAs.mockImplementationOnce(() => promiseResolveTimeout(0, [updatedNotification]) ); mockServiceInstance.getNotificationsList.mockImplementationOnce(() => promiseResolveTimeout(0, [updatedNotification]) ); const headlessService = new HeadlessService(options); const markNotificationsAsListener = jest.fn(); const fetchNotificationsListener = jest.fn(); const onSuccess = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchNotifications({ listener: fetchNotificationsListener, }); await promiseResolveTimeout(0); expect(fetchNotificationsListener).toHaveBeenCalledTimes(2); headlessService.markNotificationsAs({ messageId: notificationId, mark: payload, listener: markNotificationsAsListener, onSuccess, }); expect(markNotificationsAsListener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(300); expect(mockServiceInstance.markMessageAs).toBeCalledTimes(1); expect(onSuccess).toHaveBeenNthCalledWith(1, [updatedNotification]); expect(fetchNotificationsListener).toHaveBeenNthCalledWith( 3, expect.objectContaining({ data: [updatedNotification], error: null, isError: false, isFetching: true, isLoading: false, status: 'success', }) ); } ); test.each(PAYLOADS)( `handles the error with payload: %s`, async (payload) => { const error = new Error('error'); mockServiceInstance.markMessageAs.mockImplementationOnce(() => promiseRejectTimeout(0, error) ); const headlessService = new HeadlessService(options); const listener = jest.fn(); const onError = jest.fn(); (headlessService as any).session = mockSession; headlessService.markNotificationsAs({ messageId: notificationId, mark: payload, listener, onError, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(100); expect(mockServiceInstance.markMessageAs).toBeCalledTimes(1); expect(onError).toHaveBeenCalledWith(error); expect(listener).toHaveBeenNthCalledWith( 2, expect.objectContaining({ isLoading: false, data: undefined, error }) ); } ); }); describe('removeNotification', () => { test('calls removeNotification successfully', async () => { const updatedNotification = { ...mockNotification, deleted: true, }; mockServiceInstance.removeMessage.mockImplementationOnce(() => promiseResolveTimeout(0, updatedNotification) ); const headlessService = new HeadlessService(options); const removeNotificationListener = jest.fn(); const fetchNotificationsListener = jest.fn(); const onSuccess = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchNotifications({ listener: fetchNotificationsListener, }); await promiseResolveTimeout(0); expect(fetchNotificationsListener).toHaveBeenCalledTimes(2); headlessService.removeNotification({ messageId: notificationId, listener: removeNotificationListener, onSuccess, }); expect(removeNotificationListener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(100); expect(mockServiceInstance.removeMessage).toBeCalledTimes(1); expect(onSuccess).toHaveBeenNthCalledWith(1, updatedNotification); expect(fetchNotificationsListener).toHaveBeenNthCalledWith( 2, expect.not.objectContaining({ data: [updatedNotification], }) ); }); test('handles the error', async () => { const error = new Error('error'); mockServiceInstance.removeMessage.mockImplementationOnce(() => promiseRejectTimeout(0, error) ); const headlessService = new HeadlessService(options); const listener = jest.fn(); const onError = jest.fn(); (headlessService as any).session = mockSession; headlessService.removeNotification({ messageId: notificationId, listener, onError, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(100); expect(mockServiceInstance.removeMessage).toBeCalledTimes(1); expect(onError).toHaveBeenCalledWith(error); expect(listener).toHaveBeenNthCalledWith( 2, expect.objectContaining({ isLoading: false, data: undefined, error }) ); }); }); describe('updateAction', () => { test('calls updateAction successfully', async () => { const actionButtonType = ButtonTypeEnum.PRIMARY; const status = MessageActionStatusEnum.PENDING; const payload = {}; const updatedNotification = { ...mockNotification, cta: { ...mockNotification.cta, action: { status, buttons: [{ type: ButtonTypeEnum.PRIMARY, content: 'button' }], result: { payload, type: ButtonTypeEnum.PRIMARY, }, }, }, }; mockServiceInstance.updateAction.mockImplementationOnce(() => promiseResolveTimeout(0, updatedNotification) ); const headlessService = new HeadlessService(options); const markNotificationsAsReadListener = jest.fn(); const fetchNotificationsListener = jest.fn(); const onSuccess = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchNotifications({ listener: fetchNotificationsListener, }); await promiseResolveTimeout(0); expect(fetchNotificationsListener).toHaveBeenCalledTimes(2); headlessService.updateAction({ messageId: notificationId, actionButtonType, status, payload, listener: markNotificationsAsReadListener, onSuccess, }); expect(markNotificationsAsReadListener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(100); expect(mockServiceInstance.updateAction).toBeCalledTimes(1); expect(onSuccess).toHaveBeenNthCalledWith(1, updatedNotification); expect(fetchNotificationsListener).toHaveBeenNthCalledWith( 3, expect.objectContaining({ data: [updatedNotification], }) ); }); test('handles the error', async () => { const actionButtonType = ButtonTypeEnum.PRIMARY; const status = MessageActionStatusEnum.PENDING; const payload = {}; const error = new Error('error'); mockServiceInstance.updateAction.mockImplementationOnce(() => promiseRejectTimeout(0, error) ); const headlessService = new HeadlessService(options); const listener = jest.fn(); const onError = jest.fn(); (headlessService as any).session = mockSession; headlessService.updateAction({ messageId: notificationId, actionButtonType, status, payload, listener, onError, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(100); expect(mockServiceInstance.updateAction).toBeCalledTimes(1); expect(onError).toHaveBeenCalledWith(error); expect(listener).toHaveBeenNthCalledWith( 2, expect.objectContaining({ isLoading: false, data: undefined, error }) ); }); }); describe('markAllMessagesAsRead', () => { test('calls markAllMessagesAsRead successfully', async () => { mockServiceInstance.markAllMessagesAsRead.mockImplementationOnce(() => promiseResolveTimeout(0) ); const headlessService = new HeadlessService(options); const markAllNotificationsAsReadListener = jest.fn(); const fetchNotificationsListener = jest.fn(); const onSuccess = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchNotifications({ listener: fetchNotificationsListener, }); await promiseResolveTimeout(0); expect(fetchNotificationsListener).toHaveBeenCalledTimes(2); headlessService.markAllMessagesAsRead({ listener: markAllNotificationsAsReadListener, onSuccess, }); expect(markAllNotificationsAsReadListener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(100); expect(mockServiceInstance.markAllMessagesAsRead).toBeCalledTimes(1); expect(onSuccess).toHaveBeenNthCalledWith(1, {}); }); test('handles the error', async () => { const error = new Error('error'); mockServiceInstance.markAllMessagesAsRead.mockImplementationOnce(() => promiseRejectTimeout(0, error) ); const headlessService = new HeadlessService(options); const listener = jest.fn(); const onError = jest.fn(); (headlessService as any).session = mockSession; headlessService.markAllMessagesAsRead({ listener, onError, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(100); expect(mockServiceInstance.markAllMessagesAsRead).toBeCalledTimes(1); expect(onError).toHaveBeenCalledWith(error); expect(listener).toHaveBeenNthCalledWith( 2, expect.objectContaining({ isLoading: false, data: undefined, error }) ); }); }); describe('markAllMessagesAsSeen', () => { test('calls markAllMessagesAsSeen successfully', async () => { mockServiceInstance.markAllMessagesAsSeen.mockImplementationOnce(() => promiseResolveTimeout(0) ); const headlessService = new HeadlessService(options); const markAllNotificationsAsSeenListener = jest.fn(); const fetchNotificationsListener = jest.fn(); const onSuccess = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchNotifications({ listener: fetchNotificationsListener, }); await promiseResolveTimeout(0); expect(fetchNotificationsListener).toHaveBeenCalledTimes(2); headlessService.markAllMessagesAsSeen({ listener: markAllNotificationsAsSeenListener, onSuccess, }); expect(markAllNotificationsAsSeenListener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(100); expect(mockServiceInstance.markAllMessagesAsSeen).toBeCalledTimes(1); expect(onSuccess).toHaveBeenNthCalledWith(1, {}); }); test('handles the error', async () => { const error = new Error('error'); mockServiceInstance.markAllMessagesAsSeen.mockImplementationOnce(() => promiseRejectTimeout(0, error) ); const headlessService = new HeadlessService(options); const listener = jest.fn(); const onError = jest.fn(); (headlessService as any).session = mockSession; headlessService.markAllMessagesAsSeen({ listener, onError, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(100); expect(mockServiceInstance.markAllMessagesAsSeen).toBeCalledTimes(1); expect(onError).toHaveBeenCalledWith(error); expect(listener).toHaveBeenNthCalledWith( 2, expect.objectContaining({ isLoading: false, data: undefined, error }) ); }); }); describe('removeAllNotifications', () => { test('calls removeAllNotifications successfully', async () => { mockServiceInstance.removeAllMessages.mockImplementationOnce(() => promiseResolveTimeout(0) ); const headlessService = new HeadlessService(options); const removeAllNotificationsListener = jest.fn(); const fetchNotificationsListener = jest.fn(); const onSuccess = jest.fn(); (headlessService as any).session = mockSession; headlessService.fetchNotifications({ listener: fetchNotificationsListener, }); await promiseResolveTimeout(0); expect(fetchNotificationsListener).toHaveBeenCalledTimes(2); headlessService.removeAllNotifications({ listener: removeAllNotificationsListener, onSuccess, }); expect(removeAllNotificationsListener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(100); expect(mockServiceInstance.removeAllMessages).toBeCalledTimes(1); expect(onSuccess).toHaveBeenNthCalledWith(1); }); test('handles the error', async () => { const error = new Error('error'); mockServiceInstance.removeAllMessages.mockImplementationOnce(() => promiseRejectTimeout(0, error) ); const headlessService = new HeadlessService(options); const listener = jest.fn(); const onError = jest.fn(); (headlessService as any).session = mockSession; headlessService.removeAllNotifications({ listener, onError, }); expect(listener).toBeCalledWith( expect.objectContaining({ isLoading: true, data: undefined }) ); await promiseResolveTimeout(100); expect(mockServiceInstance.removeAllMessages).toBeCalledTimes(1); expect(onError).toHaveBeenCalledWith(error); expect(listener).toHaveBeenNthCalledWith( 2, expect.objectContaining({ isLoading: false, data: undefined, error }) ); }); }); });
4,713
0
petrpan-code/novuhq/novu/packages/notification-center
petrpan-code/novuhq/novu/packages/notification-center/src/index.test.ts
import { IStoreQuery, IUserPreferenceSettings, IPreferenceChannels, ScreensEnum, ColorScheme, IMessage, ChannelTypeEnum, IMessageCTA, IActor, ActorTypeEnum, ChannelCTATypeEnum, IMessageAction, MessageActionStatusEnum, IMessageButton, ButtonTypeEnum, } from './index'; describe('@novu/notification-center - general export interface', () => { it('validate IStoreQuery interface', () => { const storeQuery: IStoreQuery = { feedIdentifier: 'abc123', seen: true, read: true, }; expect(storeQuery.feedIdentifier).toBe('abc123'); expect(storeQuery.seen).toBe(true); expect(storeQuery.read).toBe(true); }); it('validate IUserPreferenceSettings interface', () => { const userPreferenceSettings: IUserPreferenceSettings = { template: { _id: 'test_id', name: 'test_name', critical: true }, preference: { enabled: true, channels: {}, }, }; expect(userPreferenceSettings.template._id).toBe('test_id'); expect(userPreferenceSettings.template.name).toBe('test_name'); expect(userPreferenceSettings.template.critical).toBe(true); expect(userPreferenceSettings.preference.enabled).toBe(true); expect(userPreferenceSettings.preference.channels).toStrictEqual({}); }); it('validate IPreferenceChannels interface', () => { const preferenceChannels: IPreferenceChannels = { email: true, sms: true, in_app: true, chat: true, push: true, }; expect(preferenceChannels.email).toBe(true); expect(preferenceChannels.sms).toBe(true); expect(preferenceChannels.in_app).toBe(true); expect(preferenceChannels.chat).toBe(true); expect(preferenceChannels.push).toBe(true); }); it('validate ScreensEnum interface', () => { const screensEnumNOTIFICATIONS: ScreensEnum = ScreensEnum.NOTIFICATIONS; const screensEnumSETTINGS: ScreensEnum = ScreensEnum.SETTINGS; expect(screensEnumNOTIFICATIONS).toBe('notifications'); expect(screensEnumSETTINGS).toBe('settings'); }); it('validate ColorScheme interface', () => { const colorSchemeLight: ColorScheme = 'light'; const colorSchemeDark: ColorScheme = 'dark'; expect(colorSchemeLight).toBe('light'); expect(colorSchemeDark).toBe('dark'); }); it('validate IMessage interface', () => { const message: IMessage = { _id: 'test_123', _templateId: 'test_123_template', _environmentId: 'test_123_environment', _organizationId: 'test_123_organization', _notificationId: 'test_123_notification', _subscriberId: 'test_123_subscriber', content: 'test_123_content', channel: {} as ChannelTypeEnum, seen: true, read: true, lastSeenDate: 'test_lastSeenDate', lastReadDate: 'test_lastReadDate', createdAt: 'test_createdAt', cta: {} as IMessageCTA, _feedId: 'test_feedId', payload: {}, actor: {} as IActor, }; expect(message._id).toBe('test_123'); expect(message._templateId).toBe('test_123_template'); expect(message._environmentId).toBe('test_123_environment'); expect(message._organizationId).toBe('test_123_organization'); expect(message._notificationId).toBe('test_123_notification'); expect(message._subscriberId).toBe('test_123_subscriber'); expect(message.content).toBe('test_123_content'); expect(message.channel).toStrictEqual({}); expect(message.seen).toBe(true); expect(message.read).toBe(true); expect(message.lastSeenDate).toBe('test_lastSeenDate'); expect(message.lastReadDate).toBe('test_lastReadDate'); expect(message.createdAt).toBe('test_createdAt'); expect(message.cta).toStrictEqual({}); expect(message._feedId).toBe('test_feedId'); expect(message.payload).toStrictEqual({}); expect(message.actor).toStrictEqual({}); }); it('validate ChannelTypeEnum interface', () => { const channelTypeEnumInApp: ChannelTypeEnum = ChannelTypeEnum.IN_APP; const channelTypeEnumEmail: ChannelTypeEnum = ChannelTypeEnum.EMAIL; const channelTypeEnumSms: ChannelTypeEnum = ChannelTypeEnum.SMS; const channelTypeEnumChat: ChannelTypeEnum = ChannelTypeEnum.CHAT; const channelTypeEnumPush: ChannelTypeEnum = ChannelTypeEnum.PUSH; expect(channelTypeEnumInApp).toBe('in_app'); expect(channelTypeEnumEmail).toBe('email'); expect(channelTypeEnumSms).toBe('sms'); expect(channelTypeEnumChat).toBe('chat'); expect(channelTypeEnumPush).toBe('push'); }); it('validate IActor interface', () => { const actor: IActor = { type: 'none' as ActorTypeEnum, data: 'data_test', }; expect(actor.type).toBe('none'); expect(actor.data).toBe('data_test'); }); it('validate ActorTypeEnum interface', () => { const actorTypeEnumNone: ActorTypeEnum = ActorTypeEnum.NONE; const actorTypeEnumUser: ActorTypeEnum = ActorTypeEnum.USER; const actorTypeEnumSystemIcon: ActorTypeEnum = ActorTypeEnum.SYSTEM_ICON; const actorTypeEnumSystemCustom: ActorTypeEnum = ActorTypeEnum.SYSTEM_CUSTOM; expect(actorTypeEnumNone).toBe('none'); expect(actorTypeEnumUser).toBe('user'); expect(actorTypeEnumSystemIcon).toBe('system_icon'); expect(actorTypeEnumSystemCustom).toBe('system_custom'); }); it('validate IMessageCTA interface', () => { const channelCTATypeEnum: ChannelCTATypeEnum = ChannelCTATypeEnum.REDIRECT; const messageCTA: IMessageCTA = { type: channelCTATypeEnum, data: { url: 'data_url', }, action: {} as IMessageAction, }; expect(messageCTA.type).toBe('redirect'); expect(messageCTA.data.url).toBe('data_url'); expect(messageCTA.action).toStrictEqual({}); }); it('validate IMessageAction interface', () => { const messageAction: IMessageAction = { status: 'pending' as MessageActionStatusEnum, buttons: [] as IMessageButton[], result: { payload: {}, type: 'primary' as ButtonTypeEnum, }, }; expect(messageAction.status).toBe('pending'); expect(messageAction.buttons).toStrictEqual([]); expect(messageAction.result.payload).toStrictEqual({}); expect(messageAction.result.type).toBe('primary'); }); it('validate MessageActionStatusEnum interface', () => { const messageActionStatusEnumDone: MessageActionStatusEnum = MessageActionStatusEnum.DONE; const messageActionStatusEnumPending: MessageActionStatusEnum = MessageActionStatusEnum.PENDING; expect(messageActionStatusEnumDone).toBe('done'); expect(messageActionStatusEnumPending).toBe('pending'); }); it('validate IMessageButton interface', () => { const messageButton: IMessageButton = { type: ButtonTypeEnum.PRIMARY, content: 'test_content', resultContent: 'test_resultContent', }; expect(messageButton.type).toBe('primary'); expect(messageButton.content).toBe('test_content'); expect(messageButton.resultContent).toBe('test_resultContent'); }); it('validate ButtonTypeEnum interface', () => { const buttonTypeEnumPrimary: ButtonTypeEnum = ButtonTypeEnum.PRIMARY; const buttonTypeEnumSecondary: ButtonTypeEnum = ButtonTypeEnum.SECONDARY; const buttonTypeEnumClicked: ButtonTypeEnum = ButtonTypeEnum.CLICKED; expect(buttonTypeEnumPrimary).toBe('primary'); expect(buttonTypeEnumSecondary).toBe('secondary'); expect(buttonTypeEnumClicked).toBe('clicked'); }); });
4,751
0
petrpan-code/novuhq/novu/packages/notification-center/src/components
petrpan-code/novuhq/novu/packages/notification-center/src/components/novu-provider/NovuProvider.test.tsx
/* cSpell:disable */ import React from 'react'; import { configure, fireEvent, render, screen, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom'; import { ChannelCTATypeEnum, ChannelTypeEnum, IMessage, IOrganizationEntity, ButtonTypeEnum, MessageActionStatusEnum, IPaginatedResponse, } from '@novu/shared'; import { IUserPreferenceSettings } from '@novu/client'; import { ISession } from '../../shared/interfaces'; import { NovuProvider } from '../../components'; import { queryClient } from '../../components/novu-provider/NovuProvider'; import { NotificationBell, PopoverNotificationCenter } from '../..'; configure({ testIdAttribute: 'data-test-id', }); const promiseResolveTimeout = (ms: number, arg: unknown = {}) => new Promise((resolve) => setTimeout(resolve, ms, arg)); const templateId = 'templateId'; const notificationId = 'notificationId'; const mockSession: ISession = { token: 'token', profile: { _id: '_id', firstName: 'firstName', lastName: 'lastName', email: 'email', subscriberId: 'subscriberId_1234', organizationId: 'organizationId?', environmentId: 'environmentId', aud: 'widget_user', }, }; const mockOrganization: IOrganizationEntity = { _id: '_id', name: 'mock organization', members: [], }; const mockUnseenCount = { count: 1 }; const mockNotification: IMessage = { _id: notificationId, _templateId: templateId, _environmentId: '_environmentId', _organizationId: '_organizationId', _notificationId: '_notificationId', _subscriberId: '_subscriberId', templateIdentifier: 'templateIdentifier', content: 'content', channel: ChannelTypeEnum.IN_APP, seen: false, read: false, lastSeenDate: '2023-06-09T12:53:55.095Z', lastReadDate: '2023-06-09T12:53:55.095Z', createdAt: '2023-06-09T12:53:55.095Z', cta: { type: ChannelCTATypeEnum.REDIRECT, data: {}, action: { status: MessageActionStatusEnum.PENDING, buttons: [{ type: ButtonTypeEnum.PRIMARY, content: 'button' }], result: { payload: {}, type: ButtonTypeEnum.PRIMARY, }, }, }, _feedId: '_feedId', payload: {}, }; const mockNotificationsList: IPaginatedResponse<IMessage> = { data: [mockNotification], totalCount: 1, pageSize: 10, page: 0, hasMore: false, }; const mockUserPreferenceSetting: IUserPreferenceSettings = { template: { _id: templateId, name: 'mock template', critical: false }, preference: { enabled: true, channels: { email: true, sms: true, in_app: true, chat: true, push: true, }, }, }; const mockUserPreferences = [mockUserPreferenceSetting]; const mockServiceInstance = { initializeSession: jest.fn(() => promiseResolveTimeout(0, mockSession)), setAuthorizationToken: jest.fn(), disposeAuthorizationToken: jest.fn(), getOrganization: jest.fn(() => promiseResolveTimeout(0, mockOrganization)), getUnseenCount: jest.fn(() => promiseResolveTimeout(0, mockUnseenCount)), getUnreadCount: jest.fn(() => promiseResolveTimeout(0, mockUnseenCount)), getTabCount: jest.fn(() => promiseResolveTimeout(0, mockUnseenCount)), getUserPreference: jest.fn(() => promiseResolveTimeout(0, mockUserPreferences)), getNotificationsList: jest.fn(() => promiseResolveTimeout(0, mockNotificationsList)), updateSubscriberPreference: jest.fn(() => promiseResolveTimeout(0, mockUserPreferenceSetting)), markMessageAs: jest.fn(() => promiseResolveTimeout(0, [{ ...mockNotification, read: true, seen: true }])), markAllMessagesAsRead: jest.fn(() => promiseResolveTimeout(0, [{ ...mockNotification }])), markAllMessagesAsSeen: jest.fn(() => promiseResolveTimeout(0, [{ ...mockNotification }])), updateAction: jest.fn(() => promiseResolveTimeout(0)), postUsageLog: jest.fn(() => promiseResolveTimeout(0)), removeMessage: jest.fn(() => promiseResolveTimeout(0)), }; const mockSocket = { on: jest.fn(), off: jest.fn(), }; const onNotificationClick = jest.fn(); jest.mock('@novu/client', () => ({ ...jest.requireActual<typeof import('@novu/client')>('@novu/client'), ApiService: jest.fn().mockImplementation(() => mockServiceInstance), })); jest.mock('socket.io-client', () => ({ ...jest.requireActual<typeof import('socket.io-client')>('socket.io-client'), __esModule: true, io: jest.fn().mockImplementation(() => mockSocket), })); window.ResizeObserver = window.ResizeObserver || jest.fn().mockImplementation(() => ({ disconnect: jest.fn(), observe: jest.fn(), unobserve: jest.fn(), })); describe('NovuProvider', () => { afterEach(() => { jest.clearAllMocks(); queryClient.clear(); }); const props = { applicationIdentifier: 'mock_app', subscriberId: 'mock_subscriber_id', subscriberHash: 'mock_subscriber_hash', }; it.each` allProps | prop ${{ ...props, applicationIdentifier: undefined }} | ${'applicationIdentifier'} ${{ ...props, subscriberId: undefined }} | ${'subscriberId'} `('when $prop is not provided should not initialize the session', async ({ allProps }) => { render( <NovuProvider backendUrl="https://mock_url.com" socketUrl="wss://mock_url.com" applicationIdentifier={allProps.applicationIdentifier} subscriberId={allProps.subscriberId} subscriberHash={allProps.subscriberHash} > <PopoverNotificationCenter onNotificationClick={onNotificationClick} colorScheme="dark"> {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />} </PopoverNotificationCenter> </NovuProvider> ); await waitFor(() => { expect(mockServiceInstance.initializeSession).toBeCalledTimes(0); expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(0); expect(screen.queryAllByTestId('notification-list-item')).toHaveLength(0); }); }); it.each` fetchNotifications ${true} ${false} `( 'when applicationIdentifier and subscriberId are provided should initialize the session and fetch notifications: $fetchNotifications', async ({ fetchNotifications }) => { render( <NovuProvider backendUrl="https://mock_url.com" socketUrl="wss://mock_url.com" applicationIdentifier={'applicationIdentifier'} subscriberId={'subscriberId'} initialFetchingStrategy={{ fetchNotifications }} > <PopoverNotificationCenter onNotificationClick={onNotificationClick} colorScheme="dark"> {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />} </PopoverNotificationCenter> </NovuProvider> ); await waitFor(() => { expect(mockServiceInstance.initializeSession).toBeCalledTimes(1); expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(fetchNotifications ? 1 : 0); }); fireEvent.click(screen.getByRole('button')); await waitFor(() => { expect(mockServiceInstance.initializeSession).toBeCalledTimes(1); expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(fetchNotifications ? 1 : 0); expect(screen.queryAllByTestId('notification-list-item')).toHaveLength(fetchNotifications ? 1 : 0); }); } ); it('when bell button is clicked and session initialized should fetch notifications', async () => { render( <NovuProvider backendUrl="https://mock_url.com" socketUrl="wss://mock_url.com" applicationIdentifier={'applicationIdentifier'} subscriberId={'subscriberId'} > <PopoverNotificationCenter onNotificationClick={onNotificationClick} colorScheme="dark"> {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />} </PopoverNotificationCenter> </NovuProvider> ); fireEvent.click(screen.getByRole('button')); await waitFor(() => { expect(mockServiceInstance.initializeSession).toBeCalledTimes(1); expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(1); expect(screen.queryAllByTestId('notification-list-item')).toHaveLength(1); }); }); it('should show the feeds tabs', async () => { const newsletterFeed = 'newsletter'; const hotDealFeed = 'hotdeal'; const newsletterNotifications = Array.from({ length: 10 }, (_, i) => ({ ...mockNotification, _id: `${notificationId}${i + 1}`, content: `${mockNotification.content} ${newsletterFeed}`, })); const hotDealNotifications = Array.from({ length: 10 }, (_, i) => ({ ...mockNotification, _id: `${notificationId}${i + 11}`, content: `${mockNotification.content} ${hotDealFeed}`, })); mockServiceInstance.getNotificationsList .mockImplementationOnce(() => promiseResolveTimeout(0, { data: [...newsletterNotifications], totalCount: 10, pageSize: 10, page: 0, hasMore: true, }) ) .mockImplementationOnce(() => promiseResolveTimeout(0, { data: [...hotDealNotifications], totalCount: 10, pageSize: 10, page: 0, hasMore: true, }) ); render( <NovuProvider backendUrl="https://mock_url.com" socketUrl="wss://mock_url.com" applicationIdentifier={'applicationIdentifier'} subscriberId={'subscriberId'} stores={[ { storeId: newsletterFeed, query: { feedIdentifier: newsletterFeed } }, { storeId: hotDealFeed, query: { feedIdentifier: hotDealFeed } }, ]} > <PopoverNotificationCenter onNotificationClick={onNotificationClick} colorScheme="dark" tabs={[ { name: 'Newsletter', storeId: newsletterFeed }, { name: 'Hot Deal', storeId: hotDealFeed }, ]} > {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />} </PopoverNotificationCenter> </NovuProvider> ); fireEvent.click(screen.getByRole('button')); await waitFor(() => { expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(1); expect(screen.queryByTestId(`tab-${newsletterFeed}`)).toBeDefined(); expect(screen.queryByTestId(`tab-${hotDealFeed}`)).toBeDefined(); expect(screen.queryByText('Newsletter')).toBeDefined(); expect(screen.queryByText('Hot Deal')).toBeDefined(); expect(screen.queryAllByTestId('notification-list-item')).toHaveLength(10); screen.queryAllByTestId('notification-content').forEach((item) => { expect(item.innerHTML).toEqual(`${mockNotification.content} ${newsletterFeed}`); }); }); fireEvent.click(screen.getByTestId(`tab-${hotDealFeed}`)); await waitFor(() => { expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(2); expect(mockServiceInstance.markMessageAs).toBeCalledTimes(1); expect(mockServiceInstance.markMessageAs).toHaveBeenCalledWith( newsletterNotifications.map((el) => el._id), { seen: true, read: false } ); expect(screen.queryByTestId('notifications-scroll-area')).toBeDefined(); expect(screen.queryAllByTestId('notification-list-item')).toHaveLength(10); screen.queryAllByTestId('notification-content').forEach((item) => { expect(item.innerHTML).toEqual(`${mockNotification.content} ${hotDealFeed}`); }); }); }); it('when changing applicationIdentifier, subscriberId, subscriberHash should reinitialize the session and fetch notifications', async () => { const subscriberOneProps = { applicationIdentifier: 'mock_app', subscriberId: 'mock_subscriber_id1', subscriberHash: 'mock_subscriber_hash1', }; const subscriberTwoProps = { applicationIdentifier: 'mock_app', subscriberId: 'mock_subscriber_id2', subscriberHash: 'mock_subscriber_hash2', }; const subscriberTwoHashProps = { applicationIdentifier: 'mock_app', subscriberId: 'mock_subscriber_id2', subscriberHash: 'mock_subscriber_hash3', }; const appTwoProps = { applicationIdentifier: 'mock_app2', subscriberId: 'mock_subscriber_id2', subscriberHash: 'mock_subscriber_hash2', }; mockServiceInstance.getNotificationsList .mockImplementationOnce(() => promiseResolveTimeout(0, { ...mockNotificationsList, data: [{ ...mockNotification, content: 'content1' }] }) ) .mockImplementationOnce(() => promiseResolveTimeout(0, { ...mockNotificationsList, data: [{ ...mockNotification, content: 'content2' }] }) ) .mockImplementationOnce(() => promiseResolveTimeout(0, { ...mockNotificationsList, data: [{ ...mockNotification, content: 'content3' }] }) ) .mockImplementationOnce(() => promiseResolveTimeout(0, { ...mockNotificationsList, data: [{ ...mockNotification, content: 'content4' }] }) ); const { rerender } = render( <NovuProvider backendUrl="https://mock_url.com" socketUrl="wss://mock_url.com" applicationIdentifier={subscriberOneProps.applicationIdentifier} subscriberId={subscriberOneProps.subscriberId} subscriberHash={subscriberOneProps.subscriberHash} > <PopoverNotificationCenter onNotificationClick={onNotificationClick} colorScheme="dark"> {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />} </PopoverNotificationCenter> </NovuProvider> ); fireEvent.click(screen.getByRole('button')); await waitFor(() => { expect(mockServiceInstance.initializeSession).toBeCalledTimes(1); expect(mockServiceInstance.getOrganization).toBeCalledTimes(1); expect(mockServiceInstance.getUnseenCount).toBeCalledTimes(1); expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(1); expect(screen.queryAllByTestId('notification-list-item')).toHaveLength(1); expect(screen.getByTestId('notification-content').innerHTML).toEqual('content1'); expect(screen.getByTestId('unseen-count-label').firstElementChild?.textContent).toEqual('1'); }); rerender( <NovuProvider backendUrl="https://mock_url.com" socketUrl="wss://mock_url.com" applicationIdentifier={subscriberTwoProps.applicationIdentifier} subscriberId={subscriberTwoProps.subscriberId} subscriberHash={subscriberTwoProps.subscriberHash} > <PopoverNotificationCenter onNotificationClick={onNotificationClick} colorScheme="dark"> {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />} </PopoverNotificationCenter> </NovuProvider> ); await waitFor(() => { expect(mockServiceInstance.initializeSession).toBeCalledTimes(2); expect(mockServiceInstance.getOrganization).toBeCalledTimes(2); expect(mockServiceInstance.getUnseenCount).toBeCalledTimes(2); expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(2); expect(screen.queryAllByTestId('notification-list-item')).toHaveLength(1); expect(screen.getByTestId('notification-content').innerHTML).toEqual('content2'); expect(screen.getByTestId('unseen-count-label').firstElementChild?.textContent).toEqual('1'); }); rerender( <NovuProvider backendUrl="https://mock_url.com" socketUrl="wss://mock_url.com" applicationIdentifier={subscriberTwoHashProps.applicationIdentifier} subscriberId={subscriberTwoHashProps.subscriberId} subscriberHash={subscriberTwoHashProps.subscriberHash} > <PopoverNotificationCenter onNotificationClick={onNotificationClick} colorScheme="dark"> {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />} </PopoverNotificationCenter> </NovuProvider> ); await waitFor(() => { expect(mockServiceInstance.initializeSession).toBeCalledTimes(3); expect(mockServiceInstance.getOrganization).toBeCalledTimes(3); expect(mockServiceInstance.getUnseenCount).toBeCalledTimes(3); expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(3); expect(screen.queryAllByTestId('notification-list-item')).toHaveLength(1); expect(screen.getByTestId('notification-content').innerHTML).toEqual('content3'); expect(screen.getByTestId('unseen-count-label').firstElementChild?.textContent).toEqual('1'); }); rerender( <NovuProvider backendUrl="https://mock_url.com" socketUrl="wss://mock_url.com" applicationIdentifier={appTwoProps.applicationIdentifier} subscriberId={appTwoProps.subscriberId} subscriberHash={appTwoProps.subscriberHash} > <PopoverNotificationCenter onNotificationClick={onNotificationClick} colorScheme="dark"> {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />} </PopoverNotificationCenter> </NovuProvider> ); await waitFor(() => { expect(mockServiceInstance.initializeSession).toBeCalledTimes(4); expect(mockServiceInstance.getOrganization).toBeCalledTimes(4); expect(mockServiceInstance.getUnseenCount).toBeCalledTimes(4); expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(4); expect(screen.queryAllByTestId('notification-list-item')).toHaveLength(1); expect(screen.getByTestId('notification-content').innerHTML).toEqual('content4'); expect(screen.getByTestId('unseen-count-label').firstElementChild?.textContent).toEqual('1'); }); }); it('when scrolling to the bottom should fetch the next page', async () => { const firstTenNotifications = Array.from({ length: 10 }, (_, i) => ({ ...mockNotification, _id: `${notificationId}${i + 1}`, content: `${mockNotification.content}${i + 1}`, })); const secondTenNotifications = Array.from({ length: 10 }, (_, i) => ({ ...mockNotification, _id: `${notificationId}${i + 11}`, content: `${mockNotification.content}${i + 11}`, })); mockServiceInstance.getNotificationsList .mockImplementationOnce(() => promiseResolveTimeout(0, { data: [...firstTenNotifications], totalCount: 20, pageSize: 10, page: 0, hasMore: true, }) ) .mockImplementationOnce(() => promiseResolveTimeout(0, { data: [...secondTenNotifications], totalCount: 20, pageSize: 10, page: 1, hasMore: true, }) ); render( <NovuProvider backendUrl="https://mock_url.com" socketUrl="wss://mock_url.com" applicationIdentifier={'applicationIdentifier'} subscriberId={'subscriberId'} > <PopoverNotificationCenter onNotificationClick={onNotificationClick} colorScheme="dark"> {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />} </PopoverNotificationCenter> </NovuProvider> ); fireEvent.click(screen.getByRole('button')); await waitFor(() => { expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(1); expect(screen.queryByTestId('notifications-scroll-area')).toBeDefined(); expect(screen.queryAllByTestId('notification-list-item')).toHaveLength(10); screen.queryAllByTestId('notification-content').forEach((item, i) => { expect(item.innerHTML).toEqual(`${mockNotification.content}${i + 1}`); }); }); fireEvent.scroll(document.querySelectorAll('.infinite-scroll-component')[0], { target: { scrollY: 1000 } }); await waitFor(() => { expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(2); expect(screen.queryByTestId('notifications-scroll-area')).toBeDefined(); expect(screen.queryAllByTestId('notification-list-item')).toHaveLength(20); screen.queryAllByTestId('notification-content').forEach((item, i) => { expect(item.innerHTML).toEqual(`${mockNotification.content}${i + 1}`); }); }); }); it('when clicking on "Mark all as read" should mark all messages as read and seen', async () => { render( <NovuProvider backendUrl="https://mock_url.com" socketUrl="wss://mock_url.com" applicationIdentifier={'applicationIdentifier'} subscriberId={'subscriberId'} > <PopoverNotificationCenter onNotificationClick={onNotificationClick} colorScheme="dark"> {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />} </PopoverNotificationCenter> </NovuProvider> ); fireEvent.click(screen.getByRole('button')); await waitFor(() => { expect(screen.queryAllByTestId('notification-list-item')).toHaveLength(1); expect(screen.queryAllByTestId('notification-list-item')[0].getAttribute('class')).toContain( 'nc-notifications-list-item-unread' ); expect(screen.getByTestId('notification-content').innerHTML).toEqual('content'); expect(screen.getByTestId('unseen-count-label').firstElementChild?.textContent).toEqual('1'); }); fireEvent.click(screen.getByTestId('notifications-header-mark-all-as-read')); await waitFor(() => { expect(mockServiceInstance.markAllMessagesAsRead).toBeCalledTimes(1); expect(screen.queryAllByTestId('notification-list-item')[0].getAttribute('class')).toContain( 'nc-notifications-list-item-read' ); }); }); it('when clicking on notification should mark it as read', async () => { render( <NovuProvider backendUrl="https://mock_url.com" socketUrl="wss://mock_url.com" applicationIdentifier={'applicationIdentifier'} subscriberId={'subscriberId'} > <PopoverNotificationCenter onNotificationClick={onNotificationClick} colorScheme="dark"> {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />} </PopoverNotificationCenter> </NovuProvider> ); fireEvent.click(screen.getByRole('button')); await waitFor(() => { expect(screen.queryAllByTestId('notification-list-item')).toHaveLength(1); expect(screen.queryAllByTestId('notification-list-item')[0].getAttribute('class')).toContain( 'nc-notifications-list-item-unread' ); expect(screen.getByTestId('notification-content').innerHTML).toEqual('content'); expect(screen.getByTestId('unseen-count-label').firstElementChild?.textContent).toEqual('1'); }); fireEvent.click(screen.getByTestId('notification-list-item')); await waitFor(() => { expect(mockServiceInstance.markMessageAs).toBeCalledTimes(1); expect(mockServiceInstance.markMessageAs).toHaveBeenCalledWith(notificationId, { seen: true, read: true }); expect(screen.queryAllByTestId('notification-list-item')[0].getAttribute('class')).toContain( 'nc-notifications-list-item-read' ); }); }); // Due to flakiness in tests, skipping this for now intentionally it.skip('when clicking on mark as read from dropdown menu should mark it as read', async () => { render( <NovuProvider backendUrl="https://mock_url.com" socketUrl="wss://mock_url.com" applicationIdentifier={'applicationIdentifier'} subscriberId={'subscriberId'} > <PopoverNotificationCenter onNotificationClick={onNotificationClick} colorScheme="dark"> {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />} </PopoverNotificationCenter> </NovuProvider> ); fireEvent.click(screen.getByRole('button')); await waitFor(() => { expect(screen.queryAllByTestId('notification-list-item')).toHaveLength(1); expect(screen.queryAllByTestId('notification-list-item')[0].getAttribute('class')).toContain( 'nc-notifications-list-item-unread' ); expect(screen.getByTestId('notification-content').innerHTML).toEqual('content'); expect(screen.getByTestId('unseen-count-label').firstElementChild?.textContent).toEqual('1'); }); fireEvent.click(screen.getByTestId('notification-dots-button')); await waitFor(() => { expect(screen.queryAllByTestId('notification-mark-as-read')).toHaveLength(1); expect(screen.queryAllByTestId('notification-remove-message')).toHaveLength(1); }); fireEvent.click(screen.getByTestId('notification-mark-as-read')); await promiseResolveTimeout(0); await waitFor(() => { expect(mockServiceInstance.markMessageAs).toBeCalledTimes(1); expect(mockServiceInstance.markMessageAs).toHaveBeenCalledWith(notificationId, { seen: true, read: true }); expect(screen.queryAllByTestId('notification-list-item')[0].getAttribute('class')).toContain( 'nc-notifications-list-item-read' ); }); fireEvent.click(screen.getByTestId('notification-dots-button')); await waitFor(() => { expect(screen.queryAllByTestId('notification-mark-as-unread')).toHaveLength(1); expect(screen.queryAllByTestId('notification-remove-message')).toHaveLength(1); }); }, 10000); });
4,774
0
petrpan-code/novuhq/novu/packages/notification-center/src
petrpan-code/novuhq/novu/packages/notification-center/src/hooks/useNotifications.test.tsx
import React, { useEffect, useState } from 'react'; import { act, renderHook, RenderHookResult } from '@testing-library/react-hooks'; import { ChannelCTATypeEnum, ChannelTypeEnum, IMessage, IOrganizationEntity, ButtonTypeEnum, MessageActionStatusEnum, IPaginatedResponse, } from '@novu/shared'; import { IUserPreferenceSettings } from '@novu/client'; import { ISession, INotificationsContext } from '../shared/interfaces'; import { NovuProvider } from '../components'; import { useNotifications } from './useNotifications'; import { queryClient } from '../components/novu-provider/NovuProvider'; const PROMISE_TIMEOUT = 150; const promiseResolveTimeout = (ms: number, arg: unknown = {}) => new Promise((resolve) => setTimeout(resolve, ms, arg)); const templateId = 'templateId'; const notificationId = 'notificationId'; const mockSession: ISession = { token: 'token', profile: { _id: '_id', firstName: 'firstName', lastName: 'lastName', email: 'email', subscriberId: 'subscriberId_1234', organizationId: 'organizationId?', environmentId: 'environmentId', aud: 'widget_user', }, }; const mockOrganization: IOrganizationEntity = { _id: '_id', name: 'mock organization', members: [], }; const mockUnseenCount = { count: 99 }; const mockNotification: IMessage = { _id: notificationId, _templateId: templateId, _environmentId: '_environmentId', _organizationId: '_organizationId', _notificationId: '_notificationId', _subscriberId: '_subscriberId', templateIdentifier: 'templateIdentifier', content: 'content', channel: ChannelTypeEnum.IN_APP, seen: false, read: false, lastSeenDate: 'lastSeenDate', lastReadDate: 'lastReadDate', createdAt: 'createdAt', cta: { type: ChannelCTATypeEnum.REDIRECT, data: {}, action: { status: MessageActionStatusEnum.PENDING, buttons: [{ type: ButtonTypeEnum.PRIMARY, content: 'button' }], result: { payload: {}, type: ButtonTypeEnum.PRIMARY, }, }, }, _feedId: '_feedId', payload: {}, }; const mockNotificationsList: IPaginatedResponse<IMessage> = { data: [mockNotification], totalCount: 1, pageSize: 10, page: 0, hasMore: false, }; const mockUserPreferenceSetting: IUserPreferenceSettings = { template: { _id: templateId, name: 'mock template', critical: false }, preference: { enabled: true, channels: { email: true, sms: true, in_app: true, chat: true, push: true, }, }, }; const mockUserPreferences = [mockUserPreferenceSetting]; const mockServiceInstance = { initializeSession: jest.fn(() => promiseResolveTimeout(0, mockSession)), setAuthorizationToken: jest.fn(), disposeAuthorizationToken: jest.fn(), getOrganization: jest.fn(() => promiseResolveTimeout(0, mockOrganization)), getUnseenCount: jest.fn(() => promiseResolveTimeout(0, mockUnseenCount)), getUserPreference: jest.fn(() => promiseResolveTimeout(0, mockUserPreferences)), getNotificationsList: jest.fn(() => promiseResolveTimeout(0, mockNotificationsList)), updateSubscriberPreference: jest.fn(() => promiseResolveTimeout(0, mockUserPreferenceSetting)), markMessageAs: jest.fn(), updateAction: jest.fn(), }; const mockSocket = { on: jest.fn(), off: jest.fn(), }; jest.mock('@novu/client', () => ({ ...jest.requireActual<typeof import('@novu/client')>('@novu/client'), ApiService: jest.fn().mockImplementation(() => mockServiceInstance), })); jest.mock('socket.io-client', () => ({ ...jest.requireActual<typeof import('socket.io-client')>('socket.io-client'), __esModule: true, io: jest.fn().mockImplementation(() => mockSocket), })); describe('useNotifications', () => { let hook: RenderHookResult< { children: any; }, INotificationsContext >; beforeEach(() => { const wrapper = ({ children }) => ( <NovuProvider backendUrl="https://mock_url.com" socketUrl="wss://mock_url.com" applicationIdentifier="mock_app" subscriberId="mock_subscriber_id" initialFetchingStrategy={{ fetchNotifications: true }} > {children} </NovuProvider> ); hook = renderHook(() => useNotifications(), { wrapper }); }); afterEach(() => { jest.clearAllMocks(); queryClient.clear(); }); it('unseen count', async () => { const { rerender, result } = hook; await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); expect(mockServiceInstance.getUnseenCount).toBeCalledTimes(1); expect(result.current.unseenCount).toEqual(mockUnseenCount.count); }); it('single page', async () => { const { rerender, result } = hook; expect(result.current.isLoading).toBeTruthy(); await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); const { notifications, isLoading, hasNextPage } = result.current; expect(isLoading).toBeFalsy(); expect(hasNextPage).toBeFalsy(); expect(notifications).toStrictEqual([mockNotification]); }); it('has next page', async () => { const mockNotificationsResponse = { data: [mockNotification], totalCount: 12, pageSize: 10, page: 0, hasMore: true, }; mockServiceInstance.getNotificationsList.mockImplementationOnce(() => promiseResolveTimeout(0, mockNotificationsResponse) ); const { rerender, result } = hook; expect(result.current.isLoading).toBeTruthy(); await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); const { notifications, isLoading, hasNextPage } = result.current; expect(isLoading).toBeFalsy(); expect(hasNextPage).toBeTruthy(); expect(notifications).toStrictEqual([mockNotification]); }); it('setStore refetches notifications', async () => { const stores = [ { storeId: 'first', query: { feedIdentifier: 'first' } }, { storeId: 'second', query: { feedIdentifier: 'second' } }, ]; const wrapper = ({ children }) => ( <NovuProvider backendUrl="https://mock_url.com" socketUrl="wss://mock_url.com" applicationIdentifier="mock_app" subscriberId="mock_subscriber_id" stores={stores} initialFetchingStrategy={{ fetchNotifications: true }} > {children} </NovuProvider> ); const innerHook = renderHook(() => useNotifications(), { wrapper }); const { rerender, result } = innerHook; expect(result.current.isLoading).toBeTruthy(); await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); expect(mockServiceInstance.getNotificationsList).toHaveBeenNthCalledWith(1, 0, stores[0].query); act(() => { result.current.setStore('second'); }); expect(result.current.isLoading).toBeTruthy(); await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); expect(mockServiceInstance.getNotificationsList).toHaveBeenNthCalledWith(2, 0, stores[1].query); }); const props = { applicationIdentifier: 'applicationIdentifier', subscriberId: 'subscriberId', subscriberHash: 'subscriberHash', }; const applicationIdentifierChanged = { ...props, applicationIdentifier: 'applicationIdentifier1', }; const subscriberIdChanged = { ...props, subscriberId: 'subscriberId1', }; const subscriberHashChanged = { ...props, subscriberHash: 'subscriberHash1', }; it.each` theChangeObject | change ${applicationIdentifierChanged} | ${`applicationIdentifier`} ${subscriberHashChanged} | ${`subscriberHash`} ${subscriberIdChanged} | ${`subscriberId`} `('refetches the notifications, unseen count, organization when $change changes', async ({ theChangeObject }) => { const payloads = [props, { ...theChangeObject }]; const wrapper = ({ children }) => { const [payload, setPayload] = useState(payloads[0]); useEffect(() => { const timeout = setTimeout(() => { act(() => { setPayload(payloads[1]); }); }, 200); return () => clearTimeout(timeout); }, []); return ( <NovuProvider backendUrl="https://mock_url.com" applicationIdentifier={payload.applicationIdentifier} subscriberId={payload.subscriberId} subscriberHash={payload.subscriberHash} initialFetchingStrategy={{ fetchNotifications: true }} > {children} </NovuProvider> ); }; const innerHook = renderHook(() => useNotifications(), { wrapper }); const { rerender, result } = innerHook; expect(result.current.isLoading).toBeTruthy(); await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(1); expect(mockServiceInstance.getUnseenCount).toBeCalledTimes(1); expect(mockServiceInstance.getOrganization).toBeCalledTimes(1); await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); expect(mockServiceInstance.getNotificationsList).toBeCalledTimes(2); expect(mockServiceInstance.getUnseenCount).toBeCalledTimes(2); expect(mockServiceInstance.getOrganization).toBeCalledTimes(2); }); it('fetch next page', async () => { const mockNotification1 = { ...mockNotification, _id: 'mockNotification1' }; const mockNotification2 = { ...mockNotification, _id: 'mockNotification2' }; const mockNotification3 = { ...mockNotification, _id: 'mockNotification3' }; const mockNotificationsResponse1 = { data: [mockNotification1, mockNotification2], totalCount: 3, pageSize: 2, page: 0, hasMore: true, }; const mockNotificationsResponse2 = { data: [mockNotification3], totalCount: 3, pageSize: 2, page: 1, hasMore: false, }; mockServiceInstance.getNotificationsList .mockImplementationOnce(() => promiseResolveTimeout(0, mockNotificationsResponse1)) .mockImplementationOnce(() => promiseResolveTimeout(0, mockNotificationsResponse2)); const { rerender, result } = hook; expect(result.current.isLoading).toBeTruthy(); await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); expect(result.current.isLoading).toBeFalsy(); expect(result.current.hasNextPage).toBeTruthy(); expect(result.current.notifications).toStrictEqual([mockNotification1, mockNotification2]); // fetch next page result.current.fetchNextPage(); rerender(); expect(result.current.isFetching).toBeTruthy(); expect(result.current.isFetchingNextPage).toBeTruthy(); await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); expect(result.current.isLoading).toBeFalsy(); expect(result.current.isFetching).toBeFalsy(); expect(result.current.isFetchingNextPage).toBeFalsy(); expect(result.current.hasNextPage).toBeFalsy(); expect(result.current.notifications).toStrictEqual([mockNotification1, mockNotification2, mockNotification3]); }); it('refetch will fetch notifications again for the same store', async () => { const mockNotification1 = { ...mockNotification, _id: 'mockNotification1' }; const mockNotification2 = { ...mockNotification, _id: 'mockNotification2' }; const mockNotification3 = { ...mockNotification, _id: 'mockNotification3' }; const mockNotificationsResponse1 = { data: [mockNotification1], totalCount: 1, pageSize: 10, page: 0, }; const mockNotificationsResponse2 = { data: [mockNotification1, mockNotification2, mockNotification3], totalCount: 3, pageSize: 10, page: 1, }; mockServiceInstance.getNotificationsList .mockImplementationOnce(() => promiseResolveTimeout(0, mockNotificationsResponse1)) .mockImplementationOnce(() => promiseResolveTimeout(0, mockNotificationsResponse2)); const { rerender, result } = hook; expect(result.current.isLoading).toBeTruthy(); await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); expect(mockServiceInstance.getNotificationsList).toHaveBeenNthCalledWith(1, 0, {}); expect(result.current.notifications).toStrictEqual([mockNotification1]); act(() => { result.current.refetch(); }); rerender(); expect(result.current.isLoading).toBeFalsy(); expect(result.current.isFetching).toBeTruthy(); await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); expect(mockServiceInstance.getNotificationsList).toHaveBeenNthCalledWith(2, 0, {}); expect(result.current.notifications).toStrictEqual([mockNotification1, mockNotification2, mockNotification3]); }); it('refetch will fetch notifications from a specified page number', async () => { const mockNotification1 = { ...mockNotification, _id: 'mockNotification1' }; const mockNotification2 = { ...mockNotification, _id: 'mockNotification2' }; const mockNotification3 = { ...mockNotification, _id: 'mockNotification3' }; const mockNotificationsResponse1 = { data: [mockNotification1], totalCount: 1, pageSize: 10, page: 0, }; const mockNotificationsResponse2 = { data: [mockNotification2, mockNotification3], totalCount: 3, pageSize: 10, page: 1, }; mockServiceInstance.getNotificationsList .mockImplementationOnce(() => promiseResolveTimeout(0, mockNotificationsResponse1)) .mockImplementationOnce(() => promiseResolveTimeout(0, mockNotificationsResponse2)); const { rerender, result } = hook; expect(result.current.isLoading).toBeTruthy(); await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); expect(mockServiceInstance.getNotificationsList).toHaveBeenNthCalledWith(1, 0, {}); expect(result.current.notifications).toStrictEqual([mockNotification1]); act(() => { result.current.refetch({ page: 1 }); }); rerender(); expect(result.current.isLoading).toBeFalsy(); expect(result.current.isFetching).toBeTruthy(); await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); expect(mockServiceInstance.getNotificationsList).toHaveBeenNthCalledWith(2, 1, {}); expect(result.current.notifications).toStrictEqual([mockNotification1, mockNotification2, mockNotification3]); }); it('mark notification as read', async () => { mockServiceInstance.markMessageAs.mockImplementationOnce(() => promiseResolveTimeout(0, [{ ...mockNotification, read: true, seen: true }]) ); const { rerender, result } = hook; await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); act(() => { result.current.markNotificationAsRead(result.current.notifications[0]._id); }); await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); const { notifications } = result.current; const [firstNotification] = notifications; expect(mockServiceInstance.markMessageAs).toHaveBeenCalledWith(firstNotification._id, { seen: true, read: true, }); expect(firstNotification.read).toBeTruthy(); expect(firstNotification.seen).toBeTruthy(); }); it('mark fetched notifications as read', async () => { const mockNotification1 = { ...mockNotification, _id: 'mockNotification1' }; const mockNotification2 = { ...mockNotification, _id: 'mockNotification2' }; const mockNotificationsResponse1 = { data: [mockNotification1, mockNotification2], totalCount: 10, pageSize: 10, page: 0, hasMore: false, }; mockServiceInstance.getNotificationsList.mockImplementationOnce(() => promiseResolveTimeout(0, mockNotificationsResponse1) ); mockServiceInstance.markMessageAs.mockImplementationOnce(() => promiseResolveTimeout(0, [ { ...mockNotification1, read: true, seen: true }, { ...mockNotification2, read: true, seen: true }, ]) ); const { rerender, result } = hook; await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); act(() => { result.current.markFetchedNotificationsAsRead(); }); await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); const { notifications } = result.current; const [firstNotification, secondNotification] = notifications; expect(mockServiceInstance.markMessageAs).toHaveBeenCalledWith([firstNotification._id, secondNotification._id], { seen: true, read: true, }); expect(firstNotification.read).toBeTruthy(); expect(firstNotification.seen).toBeTruthy(); expect(secondNotification.read).toBeTruthy(); expect(secondNotification.seen).toBeTruthy(); }); it('mark notification as seen', async () => { mockServiceInstance.markMessageAs.mockImplementationOnce(() => promiseResolveTimeout(0, [{ ...mockNotification, read: false, seen: true }]) ); const { rerender, result } = hook; await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); act(() => { result.current.markNotificationAsSeen(result.current.notifications[0]._id); }); await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); const { notifications } = result.current; const [firstNotification] = notifications; expect(mockServiceInstance.markMessageAs).toHaveBeenCalledWith(firstNotification._id, { seen: true, read: false, }); expect(firstNotification.read).toBeFalsy(); expect(firstNotification.seen).toBeTruthy(); }); it('mark fetched notifications as seen', async () => { const mockNotification1 = { ...mockNotification, _id: 'mockNotification1' }; const mockNotification2 = { ...mockNotification, _id: 'mockNotification2' }; const mockNotificationsResponse1 = { data: [mockNotification1, mockNotification2], totalCount: 10, pageSize: 10, page: 0, }; mockServiceInstance.getNotificationsList.mockImplementationOnce(() => promiseResolveTimeout(0, mockNotificationsResponse1) ); mockServiceInstance.markMessageAs.mockImplementationOnce(() => promiseResolveTimeout(0, [ { ...mockNotification1, read: false, seen: true }, { ...mockNotification2, read: false, seen: true }, ]) ); const { rerender, result } = hook; await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); act(() => { result.current.markFetchedNotificationsAsSeen(); }); await promiseResolveTimeout(PROMISE_TIMEOUT); rerender(); const { notifications } = result.current; const [firstNotification, secondNotification] = notifications; expect(mockServiceInstance.markMessageAs).toHaveBeenCalledWith([firstNotification._id, secondNotification._id], { seen: true, read: false, }); expect(firstNotification.read).toBeFalsy(); expect(firstNotification.seen).toBeTruthy(); expect(secondNotification.read).toBeFalsy(); expect(secondNotification.seen).toBeTruthy(); }); });
4,918
0
petrpan-code/novuhq/novu/packages/notification-center/src
petrpan-code/novuhq/novu/packages/notification-center/src/utils/pagination.test.ts
import { getNextPageParam } from './pagination'; describe('getNextPageParam', () => { it.each` totalCount | pageSize | page | nextPage | hasMore ${50} | ${10} | ${0} | ${1} | ${true} ${50} | ${10} | ${1} | ${2} | ${true} ${50} | ${10} | ${2} | ${3} | ${true} ${50} | ${10} | ${3} | ${4} | ${true} ${50} | ${10} | ${4} | ${undefined} | ${false} ${2} | ${1} | ${0} | ${1} | ${true} ${2} | ${1} | ${1} | ${undefined} | ${false} ${1} | ${1} | ${0} | ${undefined} | ${false} `( 'returns the next page: totalCount: $totalCount, pageSize: $pageSize, page: $page, nextPage: $nextPage,', ({ totalCount, pageSize, page, nextPage, hasMore }) => { const result = getNextPageParam({ totalCount, pageSize, page, data: [], hasMore }); expect(result).toBe(nextPage); } ); });
6,909
0
petrpan-code/appsmithorg/appsmith/app/client/packages/ast
petrpan-code/appsmithorg/appsmith/app/client/packages/ast/src/index.test.ts
import { parseJSObject } from "../index"; import { extractIdentifierInfoFromCode, getMemberExpressionObjectFromProperty, isFunctionPresent, } from "../src/index"; describe("getAllIdentifiers", () => { it("works properly", () => { const cases: Array<{ script: string; expectedResults: string[]; invalidIdentifiers?: Record<string, unknown>; }> = [ { // Entity reference script: "DirectTableReference", expectedResults: ["DirectTableReference"], }, { // One level nesting script: "TableDataReference.data", expectedResults: ["TableDataReference.data"], }, { // Deep nesting script: "TableDataDetailsReference.data.details", expectedResults: ["TableDataDetailsReference.data.details"], }, { // Deep nesting script: "TableDataDetailsMoreReference.data.details.more", expectedResults: ["TableDataDetailsMoreReference.data.details.more"], }, { // Deep optional chaining script: "TableDataOptionalReference.data?.details.more", expectedResults: ["TableDataOptionalReference.data"], }, { // Deep optional chaining with logical operator script: "TableDataOptionalWithLogical.data?.details.more || FallbackTableData.data", expectedResults: [ "TableDataOptionalWithLogical.data", "FallbackTableData.data", ], }, { // null coalescing script: "TableDataOptionalWithLogical.data ?? FallbackTableData.data", expectedResults: [ "TableDataOptionalWithLogical.data", "FallbackTableData.data", ], }, { // Basic map function script: "Table5.data.map(c => ({ name: c.name }))", expectedResults: ["Table5.data.map"], }, { // Literal property search script: "Table6['data']", expectedResults: ["Table6"], }, { // Deep literal property search script: "TableDataOptionalReference['data'].details", expectedResults: ["TableDataOptionalReference"], }, { // Array index search script: "array[8]", expectedResults: ["array[8]"], }, { // Deep array index search script: "Table7.data[4]", expectedResults: ["Table7.data[4]"], }, { // Deep array index search script: "Table7.data[4].value", expectedResults: ["Table7.data[4].value"], }, { // string literal and array index search script: "Table['data'][9]", expectedResults: ["Table"], }, { // array index and string literal search script: "Array[9]['data']", expectedResults: [], invalidIdentifiers: { Array: true, }, }, { // Index identifier search script: "Table8.data[row][name]", expectedResults: ["Table8.data", "row"], // name is a global scoped variable invalidIdentifiers: { name: true, }, }, { // Index identifier search with global script: "Table9.data[appsmith.store.row]", expectedResults: ["Table9.data", "appsmith.store.row"], }, { // Index literal with further nested lookups script: "Table10.data[row].name", expectedResults: ["Table10.data", "row"], }, { // IIFE and if conditions script: "(function(){ if(Table11.isVisible) { return Api1.data } else { return Api2.data } })()", expectedResults: ["Table11.isVisible", "Api1.data", "Api2.data"], }, { // Functions and arguments script: "JSObject1.run(Api1.data, Api2.data)", expectedResults: ["JSObject1.run", "Api1.data", "Api2.data"], }, { // IIFE - without braces script: `function() { const index = Input1.text const obj = { "a": 123 } return obj[index] }()`, expectedResults: ["Input1.text"], }, { // IIFE script: `(function() { const index = Input2.text const obj = { "a": 123 } return obj[index] })()`, expectedResults: ["Input2.text"], }, { // arrow IIFE - without braces - will fail script: `() => { const index = Input3.text const obj = { "a": 123 } return obj[index] }()`, expectedResults: [], }, { // arrow IIFE script: `(() => { const index = Input4.text const obj = { "a": 123 } return obj[index] })()`, expectedResults: ["Input4.text"], }, { // Direct object access script: `{ "a": 123 }[Input5.text]`, expectedResults: ["Input5.text"], }, { // Function declaration and default arguments script: `function run(apiData = Api1.data) { return apiData; }`, expectedResults: ["Api1.data"], }, { // Function declaration with arguments script: `function run(data) { return data; }`, expectedResults: [], }, { // anonymous function with variables script: `() => { let row = 0; const data = {}; while(row < 10) { data["test__" + row] = Table12.data[row]; row = row += 1; } }`, expectedResults: ["Table12.data"], }, { // function with variables script: `function myFunction() { let row = 0; const data = {}; while(row < 10) { data["test__" + row] = Table13.data[row]; row = row += 1; } }`, expectedResults: ["Table13.data"], }, { // expression with arithmetic operations script: `Table14.data + 15`, expectedResults: ["Table14.data"], }, { // expression with logical operations script: `Table15.data || [{}]`, expectedResults: ["Table15.data"], }, // JavaScript built in classes should not be valid identifiers { script: `function(){ const firstApiRun = Api1.run(); const secondApiRun = Api2.run(); const randomNumber = Math.random(); return Promise.all([firstApiRun, secondApiRun]) }()`, expectedResults: ["Api1.run", "Api2.run"], invalidIdentifiers: { Math: true, Promise: true, }, }, // Global dependencies should not be valid identifiers { script: `function(){ const names = [["john","doe"],["Jane","dane"]]; const flattenedNames = _.flatten(names); return {flattenedNames, time: moment()} }()`, expectedResults: [], invalidIdentifiers: { _: true, moment: true, }, }, // browser Apis should not be valid identifiers { script: `function(){ const names = { firstName: "John", lastName:"Doe" }; const joinedName = Object.values(names).join(" "); console.log(joinedName) return Api2.name }()`, expectedResults: ["Api2.name"], invalidIdentifiers: { Object: true, console: true, }, }, // identifiers and member expressions derived from params should not be valid identifiers { script: `function(a, b){ return a.name + b.name }()`, expectedResults: [], }, // identifiers and member expressions derived from local variables should not be valid identifiers { script: `function(){ const a = "variableA"; const b = "variableB"; return a.length + b.length }()`, expectedResults: [], }, // "appsmith" is an internal identifier and should be a valid reference { script: `function(){ return appsmith.user }()`, expectedResults: ["appsmith.user"], }, ]; // commenting to trigger test shared workflow action cases.forEach((perCase) => { const { references } = extractIdentifierInfoFromCode( perCase.script, 2, perCase.invalidIdentifiers, ); expect(references).toStrictEqual(perCase.expectedResults); }); }); }); describe("parseJSObjectWithAST", () => { it("parse js object", () => { const body = `export default{ myVar1: [], myVar2: {}, myFun1: () => { //write code here }, myFun2: async () => { //use async-await or promises } }`; const expectedParsedObject = [ { key: "myVar1", value: "[]", rawContent: "myVar1: []", type: "ArrayExpression", position: { startLine: 2, startColumn: 1, endLine: 2, endColumn: 11, keyStartLine: 2, keyEndLine: 2, keyStartColumn: 1, keyEndColumn: 7, }, }, { key: "myVar2", value: "{}", rawContent: "myVar2: {}", type: "ObjectExpression", position: { startLine: 3, startColumn: 1, endLine: 3, endColumn: 11, keyStartLine: 3, keyEndLine: 3, keyStartColumn: 1, keyEndColumn: 7, }, }, { key: "myFun1", value: "() => {}", rawContent: "myFun1: () => {\n\t\t//write code here\n\t}", type: "ArrowFunctionExpression", position: { startLine: 4, startColumn: 1, endLine: 6, endColumn: 2, keyStartLine: 4, keyEndLine: 4, keyStartColumn: 1, keyEndColumn: 7, }, arguments: [], isMarkedAsync: false, }, { key: "myFun2", value: "async () => {}", rawContent: "myFun2: async () => {\n\t\t//use async-await or promises\n\t}", type: "ArrowFunctionExpression", position: { startLine: 7, startColumn: 1, endLine: 9, endColumn: 2, keyStartLine: 7, keyEndLine: 7, keyStartColumn: 1, keyEndColumn: 7, }, arguments: [], isMarkedAsync: true, }, ]; const { parsedObject } = parseJSObject(body); expect(parsedObject).toStrictEqual(expectedParsedObject); }); it("parse js object with literal", () => { const body = `export default{ myVar1: [], myVar2: { "a": "app", }, myFun1: () => { //write code here }, myFun2: async () => { //use async-await or promises } }`; const expectedParsedObject = [ { key: "myVar1", value: "[]", rawContent: "myVar1: []", type: "ArrayExpression", position: { startLine: 2, startColumn: 1, endLine: 2, endColumn: 11, keyStartLine: 2, keyEndLine: 2, keyStartColumn: 1, keyEndColumn: 7, }, }, { key: "myVar2", value: '{\n "a": "app"\n}', rawContent: 'myVar2: {\n\t\t"a": "app",\n\t}', type: "ObjectExpression", position: { startLine: 3, startColumn: 1, endLine: 5, endColumn: 2, keyStartLine: 3, keyEndLine: 3, keyStartColumn: 1, keyEndColumn: 7, }, }, { key: "myFun1", value: "() => {}", rawContent: "myFun1: () => {\n\t\t//write code here\n\t}", type: "ArrowFunctionExpression", position: { startLine: 6, startColumn: 1, endLine: 8, endColumn: 2, keyStartLine: 6, keyEndLine: 6, keyStartColumn: 1, keyEndColumn: 7, }, arguments: [], isMarkedAsync: false, }, { key: "myFun2", value: "async () => {}", rawContent: "myFun2: async () => {\n\t\t//use async-await or promises\n\t}", type: "ArrowFunctionExpression", position: { startLine: 9, startColumn: 1, endLine: 11, endColumn: 2, keyStartLine: 9, keyEndLine: 9, keyStartColumn: 1, keyEndColumn: 7, }, arguments: [], isMarkedAsync: true, }, ]; const { parsedObject } = parseJSObject(body); expect(parsedObject).toStrictEqual(expectedParsedObject); }); it("parse js object with variable declaration inside function", () => { const body = `export default{ myFun1: () => { const a = { conditions: [], requires: 1, testFunc: () => {}, testFunc2: function(){} }; }, myFun2: async () => { //use async-await or promises } }`; const expectedParsedObject = [ { key: "myFun1", value: "() => {\n" + " const a = {\n" + " conditions: [],\n" + " requires: 1,\n" + " testFunc: () => {},\n" + " testFunc2: function () {}\n" + " };\n" + "}", rawContent: "myFun1: () => {\n" + " const a = {\n" + " conditions: [],\n" + " requires: 1,\n" + " testFunc: () => {},\n" + " testFunc2: function(){}\n" + " };\n" + " }", type: "ArrowFunctionExpression", position: { startLine: 2, startColumn: 6, endLine: 9, endColumn: 7, keyStartLine: 2, keyEndLine: 2, keyStartColumn: 6, keyEndColumn: 12, }, arguments: [], isMarkedAsync: false, }, { key: "myFun2", value: "async () => {}", rawContent: "myFun2: async () => {\n //use async-await or promises\n }", type: "ArrowFunctionExpression", position: { startLine: 10, startColumn: 6, endLine: 12, endColumn: 7, keyStartLine: 10, keyEndLine: 10, keyStartColumn: 6, keyEndColumn: 12, }, arguments: [], isMarkedAsync: true, }, ]; const { parsedObject } = parseJSObject(body); expect(parsedObject).toStrictEqual(expectedParsedObject); }); it("parse js object with params of all types", () => { const body = `export default{ myFun2: async (a,b = Array(1,2,3),c = "", d = [], e = this.myVar1, f = {}, g = function(){}, h = Object.assign({}), i = String(), j = storeValue()) => { //use async-await or promises }, }`; const expectedParsedObject = [ { key: "myFun2", value: 'async (a, b = Array(1, 2, 3), c = "", d = [], e = this.myVar1, f = {}, g = function () {}, h = Object.assign({}), i = String(), j = storeValue()) => {}', rawContent: 'myFun2: async (a,b = Array(1,2,3),c = "", d = [], e = this.myVar1, f = {}, g = function(){}, h = Object.assign({}), i = String(), j = storeValue()) => {\n' + " //use async-await or promises\n" + " }", type: "ArrowFunctionExpression", position: { startLine: 2, startColumn: 6, endLine: 4, endColumn: 7, keyStartLine: 2, keyEndLine: 2, keyStartColumn: 6, keyEndColumn: 12, }, arguments: [ { paramName: "a", defaultValue: undefined }, { paramName: "b", defaultValue: undefined }, { paramName: "c", defaultValue: undefined }, { paramName: "d", defaultValue: undefined }, { paramName: "e", defaultValue: undefined }, { paramName: "f", defaultValue: undefined }, { paramName: "g", defaultValue: undefined }, { paramName: "h", defaultValue: undefined }, { paramName: "i", defaultValue: undefined }, { paramName: "j", defaultValue: undefined }, ], isMarkedAsync: true, }, ]; const { parsedObject } = parseJSObject(body); expect(parsedObject).toStrictEqual(expectedParsedObject); }); }); describe("isFunctionPresent", () => { it("should return true if function is present", () => { const code = "function myFun(){}"; const result = isFunctionPresent(code, 2); expect(result).toBe(true); }); it("should return true if arrow function is present", () => { const code = "const myFun = () => {}"; const result = isFunctionPresent(code, 2); expect(result).toBe(true); }); it("should return false if function is absent", () => { const code = "const a = { key: 'value' }"; const result = isFunctionPresent(code, 2); expect(result).toBe(false); }); it("should return false for a string", () => { const code = "Hello world {{appsmith.store.name}}!!"; const result = isFunctionPresent(code, 2); expect(result).toBe(false); }); it("should return true for shorthand arrow function", () => { const code = "const myFun = () => 'value'"; const result = isFunctionPresent(code, 2); expect(result).toBe(true); }); it("should return true for IFFE function", () => { const code = "(function myFun(){ console.log('hello') })()"; const result = isFunctionPresent(code, 2); expect(result).toBe(true); }); it("should return true for functions with parameters", () => { const code = "function myFun(arg1, arg2){ console.log(arg1, arg2); }"; const result = isFunctionPresent(code, 2); expect(result).toBe(true); }); it("should return true for functions with parameters", () => { const code = "function myFun(arg1, arg2){ console.log(arg1, arg2); }"; const result = isFunctionPresent(code, 2); expect(result).toBe(true); }); it("should return true for higher order functions", () => { const code = "function myFun(cb){ const val = cb(); }"; const result = isFunctionPresent(code, 2); expect(result).toBe(true); }); it("should return true for functions with promises", () => { const code = "async function myFun(promise){ const val = await promise; }"; const result = isFunctionPresent(code, 2); expect(result).toBe(true); }); }); describe("getMemberExpressionObjectFromProperty", () => { it("returns an empty array for empty property name", () => { const code = `function(){ const test = Api1.data.test return "Favour" }`; const propertyName = ""; const actualResponse = getMemberExpressionObjectFromProperty( propertyName, code, ); expect(actualResponse).toStrictEqual([]); }); it("returns an empty array for invalid js", () => { const code = `function(){ const test = Api1.data.test return "Favour" `; const propertyName = "test"; const actualResponse = getMemberExpressionObjectFromProperty( propertyName, code, ); expect(actualResponse).toStrictEqual([]); }); it("returns correct member expression object(s)", () => { const testData = [ { code: `function(){ const test = Api1.data.test return "Favour" }`, propertyName: "test", expectedResponse: ["Api1.data"], }, { code: `function(){ const test = Api1.data.test; Button1.test; return "Favour" }`, propertyName: "test", expectedResponse: ["Api1.data", "Button1"], }, { code: `function(){ // const test = Api1.data.test return "Favour" }`, propertyName: "test", expectedResponse: [], }, { code: `function(){ const test = Api1.data.test.now return "Favour" }`, propertyName: "test", expectedResponse: ["Api1.data"], }, { code: `function(){ const test = Api1.data["test"] return "Favour" }`, propertyName: "test", expectedResponse: ["Api1.data"], }, ]; for (const testDatum of testData) { const actualResponse = getMemberExpressionObjectFromProperty( testDatum.propertyName, testDatum.code, ); expect(actualResponse).toStrictEqual(testDatum.expectedResponse); } }); });
6,912
0
petrpan-code/appsmithorg/appsmith/app/client/packages/ast/src
petrpan-code/appsmithorg/appsmith/app/client/packages/ast/src/actionCreator/index.test.ts
import { getFuncExpressionAtPosition, setCallbackFunctionField, getActionBlocks, getFunctionBodyStatements, getFunctionName, getMainAction, getThenCatchBlocksFromQuery, setThenBlockInQuery, setCatchBlockInQuery, setTextArgumentAtPosition, getEnumArgumentAtPosition, canTranslateToUI, } from "./index"; describe("getFuncExpressionAtPosition", () => { it("should return the function expression at the position", () => { const value = "Api1.run(() => setAlert('Success'), () => showModal('Modal1'));"; const result = getFuncExpressionAtPosition(value, 1, 2); expect(result).toEqual("() => showModal('Modal1')"); }); it("should return empty string when function expression is not present at the position", () => { const value = "Api1.run();"; const result = getFuncExpressionAtPosition(value, 0, 2); expect(result).toEqual(""); }); it("should return the arguments from the first property", () => { const value = "Api2.run(() => setAlert('Success'), () => showModal('Modal1')).then(() => {});"; const result = getFuncExpressionAtPosition(value, 1, 2); expect(result).toEqual("() => showModal('Modal1')"); }); it("should return the arguments from the first property", () => { const value = "appsmith.geolocation.getCurrentPosition((location) => {});"; const result = getFuncExpressionAtPosition(value, 0, 2); expect(result).toEqual("location => {}"); }); it("should return the callback function for setInterval", () => { const value = "setInterval(() => { console.log('hello'); }, 1000);"; const result = getFuncExpressionAtPosition(value, 0, 2); expect(result).toEqual("() => {\n console.log('hello');\n}"); }); }); // describe("setTextArgumentAtPosition", () => { // it("should set text argument at position 3", () => { // const value = 'setInterval(() => {\n // add code here\n console.log("hello");\n}, 5000, "");'; // const text = "hello-id"; // const result = setTextArgumentAtPosition(value, text, 2, 2); // expect(result).toEqual('{{setInterval(() => {\n // add code here\n console.log("hello");\n}, 5000, "hello-id");}}'); // }); // }); describe("setCallbackFunctionField", () => { it("should set the expression at the position when no arguments exist", () => { const value = "Api1.run();"; const functionToAdd = "() => setAlert('Success')"; const result = setCallbackFunctionField(value, functionToAdd, 1, 2); expect(result).toEqual("Api1.run(() => setAlert('Success'));"); }); it("should set the expression at the position", () => { const value = "Api1.run(() => showModal('Modal1'), () => {});"; const functionToAdd = "() => setAlert('Success')"; const result = setCallbackFunctionField(value, functionToAdd, 1, 2); expect(result).toEqual( "Api1.run(() => showModal('Modal1'), () => setAlert('Success'));", ); }); it("should be able to set Dynamic bindings as argument", () => { const value = "showAlert('hello', '');"; const message = "Button1.text"; const result = setCallbackFunctionField(value, message, 0, 2); expect(result).toEqual("showAlert(Button1.text, '');"); }); it("should be able to set empty string as argument", () => { const value = "appsmith.geolocation.getCurrentPosition(() => { console.log('hello'); });"; const callbackFunction = ""; const result = setCallbackFunctionField(value, callbackFunction, 0, 2); expect(result).toEqual("appsmith.geolocation.getCurrentPosition();"); }); it("should be able to set empty string as argument", () => { const value = "Api1.run(() => showModal('Modal1'), () => {});"; const callbackFunction = ""; const result = setCallbackFunctionField(value, callbackFunction, 0, 2); expect(result).toEqual("Api1.run('', () => {});"); }); it("should be able to set empty string as argument", () => { const value = "showAlert('hello', '');"; const message = ""; const result = setCallbackFunctionField(value, message, 0, 2); expect(result).toEqual("showAlert('', '');"); }); it("should set text argument at position 3", () => { const value = 'setInterval(() => {\n // add code here\n console.log("hello");\n}, 5000, "");'; const text = '"hello-id"'; const result = setCallbackFunctionField(value, text, 2, 2); expect(result).toEqual( 'setInterval(() => {\n // add code here\n console.log("hello");\n}, 5000, "hello-id");', ); }); }); describe("getActionBlocks", () => { it("should return an array of action blocks", () => { const result = getActionBlocks( "Api1.run(() => setAlert('Success'), () => {});showModal('Modal1')", 2, ); expect(result).toEqual([ "Api1.run(() => setAlert('Success'), () => {});", "showModal('Modal1');", ]); }); it("should return an array of action blocks", () => { const value = "Api1.run(() => {\n (() => {});\n}, () => {}, {});"; const result = getActionBlocks(value, 2); expect(result).toEqual([ "Api1.run(() => {\n (() => {});\n}, () => {}, {});", ]); }); }); describe("getFunctionBodyStatements", () => { it("should return an array of statements for Arrow Function", () => { const value = "() => { API1.run(() => {}); API2.run(); };"; const result = getFunctionBodyStatements(value, 2); expect(result).toEqual(["API1.run(() => {});", "API2.run();"]); }); it("should return an array of statements for non Arrow Function", () => { const value = "function hello() { API1.run(() => {}); API2.run(); }"; const result = getFunctionBodyStatements(value, 2); expect(result).toEqual(["API1.run(() => {});", "API2.run();"]); }); it("should return the function body that is not a block statement", () => { const value = "() => API1.run(() => {})"; const result = getFunctionBodyStatements(value, 2); expect(result).toEqual(["API1.run(() => {})"]); }); it("should return an array of statements for nested statements", () => { const value = `() => { Query1.run(() => {console.log('hello');}, () => {}, {}); }`; const result = getFunctionBodyStatements(value, 2); expect(result).toEqual([ `Query1.run(() => { console.log('hello'); }, () => {}, {});`, ]); }); }); describe("getMainAction", () => { it("should return the main action for object property callee", () => { const value = "Api1.run(() => setAlert('Success'), () => {});"; const result = getMainAction(value, 2); expect(result).toEqual("Api1.run()"); }); it("should return the main action for function call", () => { const value = "showAlert('Hello')"; const result = getMainAction(value, 2); expect(result).toEqual("showAlert('Hello')"); }); }); describe("getFunctionName", () => { it("should return the main action for object property callee", () => { const value = "Api1.run(() => setAlert('Success'), () => {});"; const result = getFunctionName(value, 2); expect(result).toEqual("Api1.run"); }); it("should return the main action for function call", () => { const value = "showAlert('Hello')"; const result = getFunctionName(value, 2); expect(result).toEqual("showAlert"); }); it("should return the main action when then/catch blocks are there", () => { const value = "Api1.run(() => setAlert('Success'), () => {}).then(() => {}).catch(() => {});"; const result = getFunctionName(value, 2); expect(result).toEqual("Api1.run"); }); it("should get the main action name for geolocation callback", () => { const value = "appsmith.geolocation.getCurrentPosition((location) => { console.log('hello'); });"; const result = getFunctionName(value, 2); expect(result).toEqual("appsmith.geolocation.getCurrentPosition"); }); it("should return empty string for no action", () => { const value = ";"; const result = getFunctionName(value, 2); expect(result).toEqual(""); }); }); describe("getThenCatchBlocksFromQuery", () => { it("should return then/catch callbacks appropriately", () => { const value = "Api1.run().then(() => { a() }).catch(() => { b() });"; const result = getThenCatchBlocksFromQuery(value, 2); expect(result).toMatchObject({ then: "() => {\n a();\n}", catch: "() => {\n b();\n}", }); }); it("should return then/catch callbacks appropriately", () => { const value = "Api1.run().catch(() => { a() }).then(() => { b() });"; const result = getThenCatchBlocksFromQuery(value, 2); expect(result).toEqual({ then: `() => {\n b();\n}`, catch: `() => {\n a();\n}`, }); }); it("should return then callback appropriately", () => { const value = "Api1.run().then(() => { a() });"; const result = getThenCatchBlocksFromQuery(value, 2); expect(JSON.stringify(result)).toEqual( JSON.stringify({ then: `() => {\n a();\n}`, }), ); }); it("should return catch callback appropriately", () => { const value = "Api1.run().catch(() => { a() });"; const result = getThenCatchBlocksFromQuery(value, 2); expect(JSON.stringify(result)).toEqual( JSON.stringify({ catch: `() => {\n a();\n}`, }), ); }); }); describe("setThenBlockInQuery", () => { it("should set then callback when both then and catch block are present", () => { const value = "Api1.run().then(() => { a() }).catch(() => { c() });"; const result = setThenBlockInQuery(value, "() => { b() }", 2); expect(result).toEqual( "Api1.run().then(() => {\n b();\n}).catch(() => {\n c();\n});", ); }); it("should set then callback even when then block is absent", () => { const value = "Api1.run()"; const result = setThenBlockInQuery(value, "() => { b() }", 2); expect(result).toEqual("Api1.run().then(() => {\n b();\n});"); }); }); describe("setCatchBlockInQuery", () => { it("should set catch callback appropriately", () => { const value = "Api2.run().then(() => { a() }).catch(() => { c() });"; const result = setCatchBlockInQuery(value, "() => { b() }", 2); expect(result).toEqual( "Api2.run().then(() => {\n a();\n}).catch(() => {\n b();\n});", ); }); it("should set catch callback even when it's not present", () => { const value = "Api2.run().then(() => { a() });"; const result = setCatchBlockInQuery(value, "() => { b() }", 2); expect(result).toEqual( "Api2.run().then(() => {\n a();\n}).catch(() => {\n b();\n});", ); }); }); describe("Tests AST methods around function arguments", function () { it("Sets argument at 0th index", function () { const code1 = 'showAlert("", "")'; const modified1 = setTextArgumentAtPosition(code1, "Hello", 0, 2); expect(modified1).toEqual(`{{showAlert("Hello", "");}}`); const code2 = 'showAlert("", 2).then(() => "Hello")'; const modified2 = setTextArgumentAtPosition(code2, "Hello", 0, 2); expect(modified2).toEqual(`{{showAlert("Hello", 2).then(() => "Hello");}}`); const arg1 = getEnumArgumentAtPosition(code2, 1, "", 2); expect(arg1).toBe("2"); }); }); describe("Test canTranslateToUI methoda", () => { const cases = [ { index: 0, input: "a(); JSObject1.myFunc1(); showModal();", expected: true, }, { index: 1, input: "navigateTo('Page1', {}, 'SAME_WINDOW'); showAlert('hi');", expected: true, }, { index: 2, input: "Api1.run(); copyToClipboard('hi');", expected: true }, { index: 3, input: "Api1.run().then(() => { return 1; }); copyToClipboard('hi');", expected: true, }, { index: 4, input: "Api1.run(() => { return 1; }); copyToClipboard('hi');", expected: true, }, { index: 5, input: "false || Api1.run(() => { return 1; }); copyToClipboard('hi');", expected: false, }, { index: 6, input: "true && Api1.run(() => { return 1; }); copyToClipboard('hi');", expected: false, }, ]; test.each(cases.map((x) => [x.index, x.input, x.expected]))( "test case %d", (_, input, expected) => { const result = canTranslateToUI(input as string, 2); expect(result).toEqual(expected); }, ); });
6,917
0
petrpan-code/appsmithorg/appsmith/app/client/packages/ast/src
petrpan-code/appsmithorg/appsmith/app/client/packages/ast/src/peekOverlay/index.test.ts
import { SourceType } from "../constants/ast"; import { PeekOverlayExpressionIdentifier } from "./index"; describe("extractExpressionAtPositionWholeDoc", () => { const scriptIdentifier = new PeekOverlayExpressionIdentifier({ sourceType: SourceType.script, }); const jsObjectIdentifier = new PeekOverlayExpressionIdentifier({ sourceType: SourceType.module, thisExpressionReplacement: "JsObject", }); const checkExpressionAtScript = async ( pos: number, resultString?: string, ) => { let result; try { result = await scriptIdentifier.extractExpressionAtPosition(pos); } catch (e) { expect(e).toBe( "PeekOverlayExpressionIdentifier - No expression found at position", ); } expect(result).toBe(resultString); }; const checkExpressionAtJsObject = async ( pos: number, resultString?: string, ) => { let result; try { result = await jsObjectIdentifier.extractExpressionAtPosition(pos); } catch (e) { expect(e).toBe( "PeekOverlayExpressionIdentifier - No expression found at position", ); } expect(result).toBe(resultString); }; it("handles MemberExpressions", async () => { // nested properties scriptIdentifier.updateScript("Api1.data[0].id"); // at position 'A' // 'A'pi1.data[0].id checkExpressionAtScript(0, "Api1"); // Ap'i'1.data[0].id checkExpressionAtScript(2, "Api1"); // Api1.'d'ata[0].id checkExpressionAtScript(6, "Api1.data"); // Api1.data['0'].id checkExpressionAtScript(11, "Api1.data[0]"); // Api1.data[0].i'd' checkExpressionAtScript(14, "Api1.data[0].id"); // function call // argument hover - Api1 scriptIdentifier.updateScript(`storeValue("abc", Api1.run)`); checkExpressionAtScript(18, "Api1"); scriptIdentifier.updateScript("Api1.check.run()"); // Ap'i'1.check.run() checkExpressionAtScript(2, "Api1"); // Api1.check.'r'un() checkExpressionAtScript(12, "Api1.check.run"); // local varibles are filtered scriptIdentifier.updateScript("Api1.check.data[x].id"); // Api1 checkExpressionAtScript(2, "Api1"); // check checkExpressionAtScript(7, "Api1.check"); // data checkExpressionAtScript(12, "Api1.check.data"); // x checkExpressionAtScript(16); // id checkExpressionAtScript(19); }); it("handles ExpressionStatements", async () => { // simple statement scriptIdentifier.updateScript("Api1"); // Ap'i'1 checkExpressionAtScript(2, "Api1"); // function call scriptIdentifier.updateScript(`storeValue("abc", 123)`); // storeValue("a'b'c", 123) checkExpressionAtScript(13); // st'o'reValue("abc", 123) - functionality not supported now checkExpressionAtScript(2); // consequent function calls scriptIdentifier.updateScript(`Api1.data[0].id.toFixed().toString()`); // toFixed checkExpressionAtScript(16, "Api1.data[0].id.toFixed"); // toString checkExpressionAtScript(26); // function call argument hover scriptIdentifier.updateScript(`storeValue("abc", Api1)`); checkExpressionAtScript(18, "Api1"); }); it("handles BinaryExpressions", async () => { // binary expression scriptIdentifier.updateScript( `Api1.data.users[0].id === "myData test" ? "Yes" : "No"`, ); // id checkExpressionAtScript(19, "Api1.data.users[0].id"); // myData checkExpressionAtScript(27); // ? checkExpressionAtScript(40); // Yes checkExpressionAtScript(43); // : checkExpressionAtScript(48); // No checkExpressionAtScript(51); // hardcoded LHS scriptIdentifier.updateScript(`"sample" === "myData test" ? "Yes" : "No"`); // sample checkExpressionAtScript(1); // nested expressions scriptIdentifier.updateScript( `"sample" === "myData test" ? "nested" === "nested check" ? "Yes" : "No" : "No"`, ); // nested checkExpressionAtScript(31); // nested check checkExpressionAtScript(44); // Yes checkExpressionAtScript(61); // No checkExpressionAtScript(69); }); it("handles JsObject cases", async () => { jsObjectIdentifier.updateScript(JsObjectWithThisKeyword); // this keyword cases // this checkExpressionAtJsObject(140, "JsObject"); // numArray checkExpressionAtJsObject(159, "JsObject.numArray"); // objectArray checkExpressionAtJsObject(180, "JsObject.objectArray"); // [0] checkExpressionAtJsObject(183, "JsObject.objectArray[0]"); // x checkExpressionAtJsObject(186, "JsObject.objectArray[0].x"); // 'x' checkExpressionAtJsObject(208, "JsObject.objectData['x']"); // 'a' checkExpressionAtJsObject(238, "JsObject.objectData['x']['a']"); // b checkExpressionAtJsObject(243, "JsObject.objectData['x']['a'].b"); // await keyword cases // resetWidget checkExpressionAtJsObject(255); // "Switch1" checkExpressionAtJsObject(266); // Api1 checkExpressionAtJsObject(287, "Api1"); // run checkExpressionAtJsObject(292, "Api1.run"); }); }); const JsObjectWithThisKeyword = `export default { numArray: [1, 2, 3], objectArray: [ {x: 123}, { y: "123"} ], objectData: { x: 123, y: "123" }, myFun1: async () => { this; this.numArray; this.objectArray[0].x; this.objectData["x"]; this.objectData["x"]["a"].b; await resetWidget("Switch1"); await Api1.run(); }, }`;
7,006
0
petrpan-code/appsmithorg/appsmith/app/client/packages/design-system/theming/src/color
petrpan-code/appsmithorg/appsmith/app/client/packages/design-system/theming/src/color/tests/DarkModeTheme.test.ts
import { DarkModeTheme } from "../src/DarkModeTheme"; describe("bg color", () => { it("should return correct color when chroma < 0.04", () => { const { bg } = new DarkModeTheme("oklch(0.92 0.02 110)").getColors(); expect(bg).toBe("rgb(4.3484% 4.3484% 4.3484%)"); }); it("should return correct color when chroma > 0.04", () => { const { bg } = new DarkModeTheme("oklch(0.92 0.05 110)").getColors(); expect(bg).toBe("rgb(5.3377% 4.7804% 0%)"); }); }); describe("bgAccent color", () => { it("should return correct color when lightness < 0.3", () => { const { bgAccent } = new DarkModeTheme("oklch(0.2 0.09 231)").getColors(); expect(bgAccent).toBe("rgb(0% 19.987% 30.122%)"); }); }); describe("bgAccentHover color", () => { it("should return correct color when lightness < 0.3", () => { const { bgAccentHover } = new DarkModeTheme( "oklch(0.2 0.09 231)", ).getColors(); expect(bgAccentHover).toBe("rgb(0% 25.498% 37.079%)"); }); it("should return correct color when lightness is between 0.3 and 0.45", () => { const { bgAccentHover } = new DarkModeTheme( "oklch(0.35 0.09 231)", ).getColors(); expect(bgAccentHover).toBe("rgb(0% 29.954% 42.35%)"); }); it("should return correct color when lightness is between 0.45 and 0.77", () => { const { bgAccentHover } = new DarkModeTheme( "oklch(0.50 0.09 231)", ).getColors(); expect(bgAccentHover).toBe("rgb(15.696% 45.773% 58.926%)"); }); it("should return correct color when lightness is between 0.77 and 0.85, hue is outside 120-300, and chroma > 0.04", () => { const { bgAccentHover } = new DarkModeTheme( "oklch(0.80 0.09 150)", ).getColors(); expect(bgAccentHover).toBe("rgb(51.184% 89.442% 60.062%)"); }); it("should return correct color when lightness is between 0.77 and 0.85, hue is inside 120-300, and chroma > 0.04", () => { const { bgAccentHover } = new DarkModeTheme( "oklch(0.80 0.09 110)", ).getColors(); expect(bgAccentHover).toBe("rgb(85.364% 85.594% 0%)"); }); it("should return correct color when lightness is between 0.77 and 0.85, and chroma < 0.04", () => { const { bgAccentHover } = new DarkModeTheme( "oklch(0.80 0.03 110)", ).getColors(); expect(bgAccentHover).toBe("rgb(79.687% 80.239% 71.58%)"); }); it("should return correct color when lightness > 0.85", () => { const { bgAccentHover } = new DarkModeTheme( "oklch(0.90 0.03 110)", ).getColors(); expect(bgAccentHover).toBe("rgb(78.426% 78.975% 70.34%)"); }); }); describe("bgAccentActive color", () => { it("should return correct color when seedLightness < 0.4", () => { const { bgAccentActive } = new DarkModeTheme( "oklch(0.2 0.09 231)", ).getColors(); expect(bgAccentActive).toBe("rgb(0% 17.836% 27.428%)"); }); it("should return correct color when seedLightness is between 0.4 and 0.7", () => { const { bgAccentActive } = new DarkModeTheme( "oklch(0.45 0.09 231)", ).getColors(); expect(bgAccentActive).toBe("rgb(0% 32.155% 44.665%)"); }); it("should return correct color when seedLightness is between 0.7 and 0.85", () => { const { bgAccentActive } = new DarkModeTheme( "oklch(0.75 0.09 231)", ).getColors(); expect(bgAccentActive).toBe("rgb(37.393% 66.165% 80.119%)"); }); it("should return correct color when seedLightness > or equal to 0.85", () => { const { bgAccentActive } = new DarkModeTheme( "oklch(0.90 0.09 231)", ).getColors(); expect(bgAccentActive).toBe("rgb(46.054% 74.898% 89.15%)"); }); }); describe("bgAccentSubtle color", () => { it("should return correct color when seedLightness > 0.25", () => { const { bgAccentSubtle } = new DarkModeTheme( "oklch(0.30 0.09 231)", ).getColors(); expect(bgAccentSubtle).toBe("rgb(0% 14.671% 23.499%)"); }); it("should return correct color when seedLightness < 0.2", () => { const { bgAccentSubtle } = new DarkModeTheme( "oklch(0.15 0.09 231)", ).getColors(); expect(bgAccentSubtle).toBe("rgb(0% 9.5878% 17.677%)"); }); it("should return correct color when seedChroma > 0.1", () => { const { bgAccentSubtle } = new DarkModeTheme( "oklch(0.30 0.15 231)", ).getColors(); expect(bgAccentSubtle).toBe("rgb(0% 14.556% 23.9%)"); }); it("should return correct color when seedChroma < 0.04", () => { const { bgAccentSubtle } = new DarkModeTheme( "oklch(0.30 0.03 231)", ).getColors(); expect(bgAccentSubtle).toBe("rgb(13.15% 13.15% 13.15%)"); }); }); describe("bgAccentSubtle color", () => { it("should return correct color when seedLightness > 0.25", () => { const { bgAccentSubtle } = new DarkModeTheme( "oklch(0.30 0.09 231)", ).getColors(); expect(bgAccentSubtle).toBe("rgb(0% 14.671% 23.499%)"); }); it("should return correct color when seedLightness < 0.2", () => { const { bgAccentSubtle } = new DarkModeTheme( "oklch(0.15 0.09 231)", ).getColors(); expect(bgAccentSubtle).toBe("rgb(0% 9.5878% 17.677%)"); }); it("should return correct color when seedChroma > 0.1", () => { const { bgAccentSubtle } = new DarkModeTheme( "oklch(0.30 0.15 231)", ).getColors(); expect(bgAccentSubtle).toBe("rgb(0% 14.556% 23.9%)"); }); it("should return correct color when seedChroma < 0.04", () => { const { bgAccentSubtle } = new DarkModeTheme( "oklch(0.30 0.03 231)", ).getColors(); expect(bgAccentSubtle).toBe("rgb(13.15% 13.15% 13.15%)"); }); }); describe("bgAccentSubtleHover color", () => { it("should return correct color for bgAccentSubtleHover1", () => { const { bgAccentSubtleHover } = new DarkModeTheme( "oklch(0.35 0.09 70)", ).getColors(); expect(bgAccentSubtleHover).toBe("rgb(25.181% 12.291% 0%)"); }); }); describe("bgAccentSubtleActive color", () => { it("should return correct color for bgAccentSubtleActive1", () => { const { bgAccentSubtleActive } = new DarkModeTheme( "oklch(0.35 0.09 70)", ).getColors(); expect(bgAccentSubtleActive).toBe("rgb(19.651% 7.4427% 0%)"); }); }); describe("bgAssistive color", () => { it("should return correct color for bgAssistive1 when seed is achromatic", () => { const { bgAssistive } = new DarkModeTheme( "oklch(0.95 0.03 170)", ).getColors(); expect(bgAssistive).toBe("rgb(92.148% 92.148% 92.148%)"); }); }); describe("bgNeutral color", () => { it("should return correct color when lightness < 0.5", () => { const { bgNeutral } = new DarkModeTheme("oklch(0.3 0.09 231)").getColors(); expect(bgNeutral).toEqual("rgb(18.887% 23.77% 26.341%)"); }); it("should return correct color when chroma < 0.04", () => { const { bgNeutral } = new DarkModeTheme("oklch(0.95 0.02 170)").getColors(); expect(bgNeutral).toEqual("rgb(93.448% 93.448% 93.448%)"); }); it("should return correct color when hue is between 120 and 300 and chroma is not less than 0.04", () => { const { bgNeutral } = new DarkModeTheme("oklch(0.95 0.06 240)").getColors(); expect(bgNeutral).toEqual("rgb(89.041% 94.38% 98.38%)"); }); it("should return correct color when hue is not between 120 and 300 and chroma is not less than 0.04", () => { const { bgNeutral } = new DarkModeTheme("oklch(0.95 0.06 30)").getColors(); expect(bgNeutral).toEqual("rgb(96.118% 92.595% 91.947%)"); }); }); describe("bgNeutralOpacity color", () => { it("should return correct color", () => { const { bgNeutralOpacity } = new DarkModeTheme( "oklch(0.51 0.24 279)", ).getColors(); expect(bgNeutralOpacity).toEqual("rgb(3.6355% 4.017% 7.6512% / 0.5)"); }); }); describe("bgNeutralHover color", () => { it("should return correct color when lightness > or equal to 0.85", () => { const { bgNeutralHover } = new DarkModeTheme( "oklch(0.86 0.03 170)", ).getColors(); expect(bgNeutralHover).toEqual("rgb(73.075% 73.075% 73.075%)"); }); it("should return correct color when lightness is between 0.77 and 0.85", () => { const { bgNeutralHover } = new DarkModeTheme( "oklch(0.80 0.03 170)", ).getColors(); expect(bgNeutralHover).toEqual("rgb(79.34% 79.34% 79.34%)"); }); it("should return correct color when lightness is between 0.45 and 0.77", () => { const { bgNeutralHover } = new DarkModeTheme( "oklch(0.60 0.03 170)", ).getColors(); expect(bgNeutralHover).toEqual("rgb(53.715% 53.715% 53.715%)"); }); it("should return correct color when lightness is between 0.3 and 0.45", () => { const { bgNeutralHover } = new DarkModeTheme( "oklch(0.35 0.03 170)", ).getColors(); expect(bgNeutralHover).toEqual("rgb(32.307% 32.307% 32.307%)"); }); }); describe("bgNeutralActive color", () => { it("should return correct color when lightness < 0.4", () => { const { bgNeutralActive } = new DarkModeTheme( "oklch(0.39 0.03 170)", ).getColors(); expect(bgNeutralActive).toEqual("rgb(28.06% 28.06% 28.06%)"); }); it("should return correct color when lightness is between 0.4 and 0.7", () => { const { bgNeutralActive } = new DarkModeTheme( "oklch(0.6 0.03 170)", ).getColors(); expect(bgNeutralActive).toEqual("rgb(45.608% 45.608% 45.608%)"); }); it("should return correct color when lightness is between 0.7 and 0.85", () => { const { bgNeutralActive } = new DarkModeTheme( "oklch(0.8 0.03 170)", ).getColors(); expect(bgNeutralActive).toEqual("rgb(68.134% 68.134% 68.134%)"); }); it("should return correct color when lightness > or equal to 0.85", () => { const { bgNeutralActive } = new DarkModeTheme( "oklch(0.9 0.03 170)", ).getColors(); expect(bgNeutralActive).toEqual("rgb(70.597% 70.597% 70.597%)"); }); }); describe("bgNeutralSubtle color", () => { it("should return correct color when lightness > 0.25", () => { const { bgNeutralSubtle } = new DarkModeTheme( "oklch(0.3 0.03 170)", ).getColors(); expect(bgNeutralSubtle).toEqual("rgb(13.15% 13.15% 13.15%)"); }); it("should return correct color when lightness < 0.2", () => { const { bgNeutralSubtle } = new DarkModeTheme( "oklch(0.15 0.03 170)", ).getColors(); expect(bgNeutralSubtle).toEqual("rgb(8.6104% 8.6104% 8.6104%)"); }); it("should return correct color when chroma > 0.025", () => { const { bgNeutralSubtle } = new DarkModeTheme( "oklch(0.3 0.03 170)", ).getColors(); expect(bgNeutralSubtle).toEqual("rgb(13.15% 13.15% 13.15%)"); }); it("should return correct color when chroma < 0.025 (achromatic)", () => { const { bgNeutralSubtle } = new DarkModeTheme( "oklch(0.3 0.01 170)", ).getColors(); expect(bgNeutralSubtle).toEqual("rgb(13.15% 13.15% 13.15%)"); }); }); describe("bgNeutralSubtleHover color", () => { it("should return correct color", () => { const { bgNeutralSubtleHover } = new DarkModeTheme( "oklch(0.3 0.01 170)", ).getColors(); expect(bgNeutralSubtleHover).toEqual("rgb(15.988% 15.988% 15.988%)"); }); }); describe("bgNeutralSubtleActive color", () => { it("should return correct color", () => { const { bgNeutralSubtleActive } = new DarkModeTheme( "oklch(0.3 0.01 170)", ).getColors(); expect(bgNeutralSubtleActive).toEqual("rgb(11.304% 11.304% 11.304%)"); }); }); describe("bgPositive color", () => { it("should return correct color when seed color is green (hue between 116 and 165) and chroma > 0.09", () => { const { bgPositive } = new DarkModeTheme( "oklch(0.62 0.17 145)", ).getColors(); expect(bgPositive).toEqual("rgb(33.244% 60.873% 10.585%)"); }); it("should return correct color when seed color is green (hue between 116 and 165) but chroma is 0.08", () => { const { bgPositive } = new DarkModeTheme( "oklch(0.62 0.08 145)", ).getColors(); expect(bgPositive).toEqual("rgb(18.515% 62.493% 23.87%)"); }); it("should return correct color when seed color is not green (hue outside 116-165) and chroma > 0.09", () => { const { bgPositive } = new DarkModeTheme( "oklch(0.62 0.17 100)", ).getColors(); expect(bgPositive).toEqual("rgb(18.515% 62.493% 23.87%)"); }); it("should return correct color when seed color is not green (hue outside 116-165) and chroma is 0.08", () => { const { bgPositive } = new DarkModeTheme( "oklch(0.62 0.08 100)", ).getColors(); expect(bgPositive).toEqual("rgb(18.515% 62.493% 23.87%)"); }); }); describe("bgPositiveHover color", () => { it("should return correct color", () => { const { bgPositiveHover } = new DarkModeTheme( "oklch(0.62 0.17 145)", ).getColors(); expect(bgPositiveHover).toEqual("rgb(36.781% 64.586% 15.952%)"); }); }); describe("bgPositiveActive color", () => { it("should return correct color", () => { const { bgPositiveActive } = new DarkModeTheme( "oklch(0.62 0.17 145)", ).getColors(); expect(bgPositiveActive).toEqual("rgb(28.549% 55.976% 0%)"); }); }); describe("bgPositiveSubtle color", () => { it("should return correct color", () => { const { bgPositiveSubtle } = new DarkModeTheme( "oklch(0.62 0.17 145)", ).getColors(); expect(bgPositiveSubtle).toEqual("rgb(7.8895% 15.556% 2.8063%)"); }); }); describe("bgPositiveSubtleHover color", () => { it("should return correct color", () => { const { bgPositiveSubtleHover } = new DarkModeTheme( "oklch(0.62 0.17 145)", ).getColors(); expect(bgPositiveSubtleHover).toEqual("rgb(10.689% 18.514% 5.7924%)"); }); }); describe("bgPositiveSubtleActive color", () => { it("should return correct color", () => { const { bgPositiveSubtleActive } = new DarkModeTheme( "oklch(0.62 0.17 145)", ).getColors(); expect(bgPositiveSubtleActive).toEqual("rgb(6.0555% 13.622% 1.2799%)"); }); }); describe("bgNegative color", () => { it("should return correct color when seed color is red (hue between 5 and 49) and chroma > 0.07", () => { const { bgNegative } = new DarkModeTheme("oklch(0.55 0.22 27)").getColors(); expect(bgNegative).toEqual("rgb(83.034% 1.7746% 18.798%)"); }); it("should return correct color when seed color is red (hue between 5 and 49) but chroma is not greater than 0.07", () => { const { bgNegative } = new DarkModeTheme("oklch(0.55 0.05 27)").getColors(); expect(bgNegative).toEqual("rgb(83.108% 4.6651% 10.252%)"); }); it("should return correct color when seed color is not red (hue outside 5-49) and chroma > 0.07", () => { const { bgNegative } = new DarkModeTheme("oklch(0.55 0.22 60)").getColors(); expect(bgNegative).toEqual("rgb(83.108% 4.6651% 10.252%)"); }); it("should return correct color when seed color is not red (hue outside 5-49) and chroma is not greater than 0.07", () => { const { bgNegative } = new DarkModeTheme("oklch(0.55 0.05 60)").getColors(); expect(bgNegative).toEqual("rgb(83.108% 4.6651% 10.252%)"); }); }); describe("bgNegativeHover color", () => { it("should return correct color", () => { const { bgNegativeHover } = new DarkModeTheme( "oklch(0.55 0.22 27)", ).getColors(); expect(bgNegativeHover).toEqual("rgb(87.347% 11.876% 22.315%)"); }); }); describe("bgNegativeActive color", () => { it("should return correct color", () => { const { bgNegativeActive } = new DarkModeTheme( "oklch(0.55 0.22 27)", ).getColors(); expect(bgNegativeActive).toEqual("rgb(77.305% 0% 13.994%)"); }); }); describe("bgNegativeSubtle color", () => { it("should return correct color", () => { const { bgNegativeSubtle } = new DarkModeTheme( "oklch(0.55 0.22 27)", ).getColors(); expect(bgNegativeSubtle).toEqual("rgb(77.305% 0% 13.994%)"); }); }); describe("bgNegativeSubtleHover color", () => { it("should return correct color", () => { const { bgNegativeSubtleHover } = new DarkModeTheme( "oklch(0.55 0.22 27)", ).getColors(); expect(bgNegativeSubtleHover).toEqual("rgb(29.827% 6.1224% 7.5796%)"); }); }); describe("bgNegativeSubtleActive color", () => { it("should return correct color", () => { const { bgNegativeSubtleActive } = new DarkModeTheme( "oklch(0.55 0.22 27)", ).getColors(); expect(bgNegativeSubtleActive).toEqual("rgb(24.04% 0.5234% 2.9937%)"); }); }); describe("bgWarning color", () => { it("should return correct color when seed color is yellow (hue between 60 and 115) and chroma > 0.09", () => { const { bgWarning } = new DarkModeTheme("oklch(0.75 0.15 85)").getColors(); expect(bgWarning).toEqual("rgb(91.527% 60.669% 16.491%)"); }); it("should return correct color when seed color is yellow (hue between 60 and 115) but chroma is not greater than 0.09", () => { const { bgWarning } = new DarkModeTheme("oklch(0.75 0.05 85)").getColors(); expect(bgWarning).toEqual("rgb(85.145% 64.66% 8.0286%)"); }); it("should return correct color when seed color is not yellow (hue outside 60-115) and chroma > 0.09", () => { const { bgWarning } = new DarkModeTheme("oklch(0.75 0.15 50)").getColors(); expect(bgWarning).toEqual("rgb(85.145% 64.66% 8.0286%)"); }); it("should return correct color when seed color is not yellow (hue outside 60-115) and chroma is not greater than 0.09", () => { const { bgWarning } = new DarkModeTheme("oklch(0.75 0.05 50)").getColors(); expect(bgWarning).toEqual("rgb(85.145% 64.66% 8.0286%)"); }); }); describe("bgWarningHover color", () => { it("should return correct color", () => { const { bgWarningHover } = new DarkModeTheme( "oklch(0.75 0.05 50)", ).getColors(); expect(bgWarningHover).toEqual("rgb(90.341% 69.671% 17.643%)"); }); }); describe("bgWarningActive color", () => { it("should return correct color", () => { const { bgWarningActive } = new DarkModeTheme( "oklch(0.75 0.05 50)", ).getColors(); expect(bgWarningActive).toEqual("rgb(78.726% 58.477% 0%)"); }); }); describe("bgWarningSubtle color", () => { it("should return correct color", () => { const { bgWarningSubtle } = new DarkModeTheme( "oklch(0.75 0.05 50)", ).getColors(); expect(bgWarningSubtle).toEqual("rgb(16.622% 12.537% 3.3792%)"); }); }); describe("bgWarningSubtleHover color", () => { it("should return correct color", () => { const { bgWarningSubtleHover } = new DarkModeTheme( "oklch(0.75 0.05 50)", ).getColors(); expect(bgWarningSubtleHover).toEqual("rgb(19.571% 15.398% 6.3225%)"); }); }); describe("bgWarningSubtleActive color", () => { it("should return correct color", () => { const { bgWarningSubtleActive } = new DarkModeTheme( "oklch(0.75 0.05 50)", ).getColors(); expect(bgWarningSubtleActive).toEqual("rgb(14.696% 10.673% 1.7722%)"); }); }); describe("fg color", () => { it("should return correct color when chroma < 0.04", () => { const { fg } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors(); expect(fg).toEqual("rgb(95.405% 95.405% 95.405%)"); }); it("should return correct color when chroma > 0.04", () => { const { fg } = new DarkModeTheme("oklch(0.45 0.1 60)").getColors(); expect(fg).toEqual("rgb(100% 94.175% 89.331%)"); }); }); describe("fgAccent color", () => { it("should return correct color when chroma < 0.04", () => { const { fgAccent } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors(); expect(fgAccent).toEqual("rgb(73.075% 73.075% 73.075%)"); }); it("should return correct color when chroma > 0.04", () => { const { fgAccent } = new DarkModeTheme("oklch(0.45 0.1 60)").getColors(); expect(fgAccent).toEqual("rgb(97.93% 64.37% 34.977%)"); }); }); describe("fgNeutral color", () => { it("should return correct color when chroma < 0.04", () => { const { fgNeutral } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors(); expect(fgNeutral).toEqual("rgb(78.08% 78.08% 78.08%)"); }); it("should return correct color when chroma > 0.04 and hue is between 120 and 300", () => { const { fgNeutral } = new DarkModeTheme("oklch(0.45 0.1 150)").getColors(); expect(fgNeutral).toEqual("rgb(73.047% 80.455% 74.211%)"); }); it("should return correct color when chroma > 0.04 and hue is not between 120 and 300", () => { const { fgNeutral } = new DarkModeTheme("oklch(0.45 0.1 110)").getColors(); expect(fgNeutral).toEqual("rgb(78.185% 78.394% 75.54%)"); }); }); describe("fgNeutralSubtle color", () => { it("should return correct color", () => { const { fgNeutralSubtle } = new DarkModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(fgNeutralSubtle).toEqual("rgb(59.646% 59.646% 59.646%)"); }); }); describe("fgPositive color", () => { it("should return correct color when chroma < 0.04", () => { const { fgPositive } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors(); expect(fgPositive).toEqual("rgb(30.123% 72.521% 33.746%)"); }); it("should return correct color when chroma > 0.04", () => { const { fgPositive } = new DarkModeTheme("oklch(0.45 0.1 60)").getColors(); expect(fgPositive).toEqual("rgb(30.123% 72.521% 33.746%)"); }); it("should return correct color hue is between 116 and 165", () => { const { fgPositive } = new DarkModeTheme("oklch(0.45 0.1 120)").getColors(); expect(fgPositive).toEqual("rgb(21.601% 73.197% 38.419%)"); }); it("should return correct color hue is not between 116 and 165", () => { const { fgPositive } = new DarkModeTheme("oklch(0.45 0.1 30)").getColors(); expect(fgPositive).toEqual("rgb(30.123% 72.521% 33.746%)"); }); }); describe("fgNegative color", () => { it("should return correct color when chroma < 0.04", () => { const { fgNegative } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors(); expect(fgNegative).toEqual("rgb(93.903% 0% 24.24%)"); }); it("should return correct color when chroma > 0.04", () => { const { fgNegative } = new DarkModeTheme("oklch(0.45 0.1 60)").getColors(); expect(fgNegative).toEqual("rgb(93.903% 0% 24.24%)"); }); it("should return correct color hue is between 5 and 49", () => { const { fgNegative } = new DarkModeTheme("oklch(0.45 0.1 30)").getColors(); expect(fgNegative).toEqual("rgb(93.292% 0% 32.205%)"); }); it("should return correct color hue is not between 5 and 49", () => { const { fgNegative } = new DarkModeTheme("oklch(0.45 0.1 120)").getColors(); expect(fgNegative).toEqual("rgb(93.903% 0% 24.24%)"); }); }); describe("fgWarning color", () => { it("should return correct color", () => { const { fgWarning } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors(); expect(fgWarning).toEqual("rgb(100% 78.06% 1.4578%)"); }); }); describe("fgOnAccent color ", () => { it("should return correct color when chroma < 0.04", () => { const { fgOnAccent } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors(); expect(fgOnAccent).toEqual("rgb(92.148% 92.148% 92.148%)"); }); it("should return correct color when chroma > 0.04", () => { const { fgOnAccent } = new DarkModeTheme("oklch(0.45 0.1 60)").getColors(); expect(fgOnAccent).toEqual("rgb(100% 89.256% 79.443%)"); }); }); describe("fgOnAssistive color ", () => { it("should return correct color", () => { const { fgOnAssistive } = new DarkModeTheme( "oklch(0.45 0.03 110)", ).getColors(); expect(fgOnAssistive).toEqual("rgb(15.033% 15.033% 15.033%)"); }); }); describe("fgOnNeutral color ", () => { it("should return correct color", () => { const { fgOnNeutral } = new DarkModeTheme( "oklch(0.45 0.03 110)", ).getColors(); expect(fgOnNeutral).toEqual("rgb(92.148% 92.148% 92.148%)"); }); }); describe("fgOnPositive color ", () => { it("should return correct color", () => { const { fgOnPositive } = new DarkModeTheme( "oklch(0.45 0.03 110)", ).getColors(); expect(fgOnPositive).toEqual("rgb(80.46% 100% 80.049%)"); }); }); describe("fgOnNegative color ", () => { it("should return correct color", () => { const { fgOnNegative } = new DarkModeTheme( "oklch(0.45 0.03 110)", ).getColors(); expect(fgOnNegative).toEqual("rgb(100% 85.802% 83.139%)"); }); }); describe("fgOnWarning color ", () => { it("should return correct color", () => { const { fgOnWarning } = new DarkModeTheme( "oklch(0.45 0.03 110)", ).getColors(); expect(fgOnWarning).toEqual("rgb(23.887% 11.273% 0%)"); }); }); describe("bd color", () => { it("should return correct color", () => { const { bd } = new DarkModeTheme("oklch(0.45 0.5 60)").getColors(); expect(bd).toEqual("rgb(32.033% 27.005% 23.081%)"); }); }); describe("bdAccent color", () => { it("should return correct color when chroma < 0.04", () => { const { bdAccent } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors(); expect(bdAccent).toEqual("rgb(76.823% 76.823% 76.823%)"); }); it("should return correct color when chroma > 0.04", () => { const { bdAccent } = new DarkModeTheme("oklch(0.45 0.1 60)").getColors(); expect(bdAccent).toEqual("rgb(94.8% 58.165% 23.581%)"); }); }); describe("bdFocus color", () => { it("should return correct color when lightness < 0.4", () => { const { bdFocus } = new DarkModeTheme("oklch(0.3 0.4 60)").getColors(); expect(bdFocus).toEqual("rgb(94.8% 58.165% 23.581%)"); }); it("should return correct color when lightness > 0.65", () => { const { bdFocus } = new DarkModeTheme("oklch(0.85 0.03 60)").getColors(); expect(bdFocus).toEqual("rgb(100% 73.208% 48.082%)"); }); it("should return correct color when chroma < 0.12", () => { const { bdFocus } = new DarkModeTheme("oklch(0.85 0.1 60)").getColors(); expect(bdFocus).toEqual("rgb(100% 73.208% 48.082%)"); }); it("should return correct color when hue is between 0 and 55", () => { const { bdFocus } = new DarkModeTheme("oklch(0.85 0.1 30)").getColors(); expect(bdFocus).toEqual("rgb(100% 70.589% 64.779%)"); }); it("should return correct color when hue > 340", () => { const { bdFocus } = new DarkModeTheme("oklch(0.85 0.1 350)").getColors(); expect(bdFocus).toEqual("rgb(100% 67.801% 85.002%)"); }); }); describe("bdNeutral color", () => { it("should return correct color when chroma < 0.04", () => { const { bdNeutral } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors(); expect(bdNeutral).toEqual("rgb(76.823% 76.823% 76.823%)"); }); }); describe("bdNeutralHover", () => { it("should return correct color", () => { const { bdNeutralHover } = new DarkModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdNeutralHover).toEqual("rgb(89.558% 89.558% 89.558%)"); }); }); describe("bdPositive", () => { it("should return correct color", () => { const { bdPositive } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors(); expect(bdPositive).toEqual("rgb(0% 71.137% 15.743%)"); }); }); describe("bdPositiveHover", () => { it("should return correct color", () => { const { bdPositiveHover } = new DarkModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdPositiveHover).toEqual("rgb(25.51% 86.719% 33.38%)"); }); }); describe("bdNegative", () => { it("should return correct color", () => { const { bdNegative } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors(); expect(bdNegative).toEqual("rgb(83.108% 4.6651% 10.252%)"); }); }); describe("bdNegativeHover", () => { it("should return correct color", () => { const { bdNegativeHover } = new DarkModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdNegativeHover).toEqual("rgb(100% 33.485% 30.164%)"); }); }); describe("bdWarning", () => { it("should return correct color", () => { const { bdWarning } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors(); expect(bdWarning).toEqual("rgb(85.145% 64.66% 8.0286%)"); }); }); describe("bdWarningHover", () => { it("should return correct color", () => { const { bdWarningHover } = new DarkModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdWarningHover).toEqual("rgb(100% 77.286% 0%)"); }); }); describe("bdOnAccent", () => { it("should return correct color", () => { const { bdOnAccent } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors(); expect(bdOnAccent).toEqual("rgb(8.8239% 3.8507% 0.7917%)"); }); }); describe("bdOnNeutral", () => { it("should return correct color", () => { const { bdOnNeutral } = new DarkModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdOnNeutral).toEqual("rgb(9.4978% 9.4978% 9.4978%)"); }); }); describe("bdOnPositive", () => { it("should return correct color", () => { const { bdOnPositive } = new DarkModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdOnPositive).toEqual("rgb(0% 38.175% 0%)"); }); }); describe("bdOnNegative", () => { it("should return correct color", () => { const { bdOnNegative } = new DarkModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdOnNegative).toEqual("rgb(36.138% 0% 2.5021%)"); }); }); describe("bdOnWarning", () => { it("should return correct color", () => { const { bdOnWarning } = new DarkModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdOnWarning).toEqual("rgb(49.811% 36.357% 0%)"); }); });
7,007
0
petrpan-code/appsmithorg/appsmith/app/client/packages/design-system/theming/src/color
petrpan-code/appsmithorg/appsmith/app/client/packages/design-system/theming/src/color/tests/LightModeTheme.test.ts
import { LightModeTheme } from "../src/LightModeTheme"; describe("bg color", () => { it("should return correct color when lightness > 0.93", () => { const { bg } = new LightModeTheme("oklch(0.95 0.09 231)").getColors(); expect(bg).toBe("rgb(84.831% 87.516% 88.974%)"); }); it("should return correct color when lightness < 0.93", () => { const { bg } = new LightModeTheme("oklch(0.92 0.09 231)").getColors(); expect(bg).toBe("rgb(95.828% 98.573% 100%)"); }); it("should return correct color when hue > 120 && hue < 300", () => { const { bg } = new LightModeTheme("oklch(0.95 0.07 231)").getColors(); expect(bg).toBe("rgb(84.831% 87.516% 88.974%)"); }); it("should return correct color when hue < 120 or hue > 300", () => { const { bg } = new LightModeTheme("oklch(0.92 0.07 110)").getColors(); expect(bg).toBe("rgb(98.101% 98.258% 96.176%)"); }); it("should return correct color when chroma < 0.04", () => { const { bg } = new LightModeTheme("oklch(0.92 0.02 110)").getColors(); expect(bg).toBe("rgb(98.026% 98.026% 98.026%)"); }); }); describe("bgAccent color", () => { it("should return correct color when lightness > 0.93", () => { const { bgAccent } = new LightModeTheme("oklch(0.95 0.09 231)").getColors(); expect(bgAccent).toBe("rgb(91.762% 98.141% 100%)"); }); }); describe("bgAccentHover color", () => { it("should return correct color when lightness < 0.06", () => { const { bgAccentHover } = new LightModeTheme( "oklch(0.05 0.09 231)", ).getColors(); expect(bgAccentHover).toBe("rgb(0% 23.271% 34.263%)"); }); it("should return correct color when lightness is between 0.06 and 0.14", () => { const { bgAccentHover } = new LightModeTheme( "oklch(0.08 0.09 231)", ).getColors(); expect(bgAccentHover).toBe("rgb(0% 17.836% 27.428%)"); }); it("should return correct color when lightness is between 0.14 and 0.21 and hue is between 120 and 300", () => { const { bgAccentHover } = new LightModeTheme( "oklch(0.17 0.09 231)", ).getColors(); expect(bgAccentHover).toBe("rgb(0% 16.773% 26.103%)"); }); it("should return correct color when lightness is between 0.14 and 0.21 and hue is not between 120 and 300", () => { const { bgAccentHover } = new LightModeTheme( "oklch(0.17 0.09 110)", ).getColors(); expect(bgAccentHover).toBe("rgb(19.339% 18.943% 0%)"); }); it("should return correct color when lightness is between 0.21 and 0.4", () => { const { bgAccentHover } = new LightModeTheme( "oklch(0.3 0.09 110)", ).getColors(); expect(bgAccentHover).toBe("rgb(28.395% 28.425% 0%)"); }); it("should return correct color when lightness is between 0.4 and 0.7", () => { const { bgAccentHover } = new LightModeTheme( "oklch(0.5 0.09 110)", ).getColors(); expect(bgAccentHover).toBe("rgb(45.795% 46.287% 19.839%)"); }); it("should return correct color when lightness > 0.7", () => { const { bgAccentHover } = new LightModeTheme( "oklch(0.9 0.09 110)", ).getColors(); expect(bgAccentHover).toBe("rgb(92.14% 93.271% 65.642%)"); }); it("should return correct color when lightness > 0.93 and hue is between 60 and 115", () => { const { bgAccentHover } = new LightModeTheme( "oklch(0.95 0.09 70)", ).getColors(); expect(bgAccentHover).toBe("rgb(100% 90.701% 78.457%)"); }); it("should return correct color when lightness > 0.93 and hue is not between 116 and 165", () => { const { bgAccentHover } = new LightModeTheme( "oklch(0.95 0.09 120)", ).getColors(); expect(bgAccentHover).toBe("rgb(89.886% 97.8% 66.657%)"); }); }); describe("bgAccentActive color", () => { it("should return correct color when lightness < 0.4", () => { const { bgAccentActive } = new LightModeTheme( "oklch(0.35 0.09 70)", ).getColors(); expect(bgAccentActive).toBe("rgb(28.712% 15.185% 0%)"); }); it("should return correct color when lightness is between 0.4 and 0.7", () => { const { bgAccentActive } = new LightModeTheme( "oklch(0.50 0.09 70)", ).getColors(); expect(bgAccentActive).toBe("rgb(49.27% 32.745% 10.549%)"); }); it("should return correct color when lightness > or equal to 0.7", () => { const { bgAccentActive } = new LightModeTheme( "oklch(0.75 0.09 70)", ).getColors(); expect(bgAccentActive).toBe("rgb(81.395% 63.124% 41.808%)"); }); it("should return correct color when lightness > 0.93", () => { const { bgAccentActive } = new LightModeTheme( "oklch(0.95 0.09 70)", ).getColors(); expect(bgAccentActive).toBe("rgb(100% 88.945% 74.563%)"); }); }); describe("bgAccentSubtle color", () => { it("should return correct color when seedLightness > 0.93", () => { const { bgAccentSubtle } = new LightModeTheme( "oklch(0.95 0.09 231)", ).getColors(); expect(bgAccentSubtle).toBe("rgb(85.876% 96.17% 100%)"); }); it("should return correct color when seedLightness < 0.93", () => { const { bgAccentSubtle } = new LightModeTheme( "oklch(0.92 0.09 231)", ).getColors(); expect(bgAccentSubtle).toBe("rgb(78.235% 93.705% 100%)"); }); it("should return correct color when seedChroma > 0.09 and hue is between 116 and 165", () => { const { bgAccentSubtle } = new LightModeTheme( "oklch(0.95 0.10 120)", ).getColors(); expect(bgAccentSubtle).toBe("rgb(90.964% 97.964% 71.119%)"); }); it("should return correct color when seedChroma > 0.06 and hue is not between 116 and 165", () => { const { bgAccentSubtle } = new LightModeTheme( "oklch(0.95 0.07 170)", ).getColors(); expect(bgAccentSubtle).toBe("rgb(75.944% 100% 91.359%)"); }); it("should return correct color when seedChroma < 0.04", () => { const { bgAccentSubtle } = new LightModeTheme( "oklch(0.95 0.03 170)", ).getColors(); expect(bgAccentSubtle).toBe("rgb(94.099% 94.099% 94.099%)"); }); }); describe("bgAccentSubtleHover color", () => { it("should return correct color", () => { const { bgAccentSubtleHover } = new LightModeTheme( "oklch(0.35 0.09 70)", ).getColors(); expect(bgAccentSubtleHover).toBe("rgb(100% 91.599% 80.256%)"); }); }); describe("bgAccentSubtleActive color", () => { it("should return correct color", () => { const { bgAccentSubtleActive } = new LightModeTheme( "oklch(0.35 0.09 70)", ).getColors(); expect(bgAccentSubtleActive).toBe("rgb(100% 87.217% 72.911%)"); }); }); describe("bgAssistive color", () => { it("should return correct color when seed is achromatic", () => { const { bgAssistive } = new LightModeTheme( "oklch(0.95 0.03 170)", ).getColors(); expect(bgAssistive).toBe("rgb(5.1758% 5.1758% 5.1759%)"); }); }); describe("bgNeutral color", () => { it("should return correct color when lightness > 0.85", () => { const { bgNeutral } = new LightModeTheme( "oklch(0.95 0.03 170)", ).getColors(); expect(bgNeutral).toEqual("rgb(94.099% 94.099% 94.099%)"); }); it("should return correct color when lightness is between 0.25 and 0.85", () => { const { bgNeutral } = new LightModeTheme("oklch(0.5 0.09 231)").getColors(); expect(bgNeutral).toEqual("rgb(21.658% 29.368% 33.367%)"); }); it("should return correct color when chroma < 0.04", () => { const { bgNeutral } = new LightModeTheme( "oklch(0.95 0.02 170)", ).getColors(); expect(bgNeutral).toEqual("rgb(94.099% 94.099% 94.099%)"); }); it("should return correct color when hue is between 120 and 300 and chroma is not less than 0.04", () => { const { bgNeutral } = new LightModeTheme( "oklch(0.95 0.06 240)", ).getColors(); expect(bgNeutral).toEqual("rgb(87.409% 95.47% 100%)"); }); it("should return correct color when hue is not between 120 and 300 and chroma is not less than 0.04", () => { const { bgNeutral } = new LightModeTheme("oklch(0.95 0.06 30)").getColors(); expect(bgNeutral).toEqual("rgb(98.083% 92.81% 91.842%)"); }); }); describe("bgNeutralOpacity color", () => { it("should return correct color", () => { const { bgNeutralOpacity } = new LightModeTheme( "oklch(0.51 0.24 279)", ).getColors(); expect(bgNeutralOpacity).toEqual("rgb(27.662% 28.6% 35.606% / 0.5)"); }); }); describe("bgNeutralHover color", () => { it("should return correct color when lightness < 0.06", () => { const { bgNeutralHover } = new LightModeTheme( "oklch(0.05 0.03 170)", ).getColors(); expect(bgNeutralHover).toEqual("rgb(16.952% 16.952% 16.952%)"); }); it("should return correct color when lightness is between 0.06 and 0.14", () => { const { bgNeutralHover } = new LightModeTheme( "oklch(0.10 0.03 170)", ).getColors(); expect(bgNeutralHover).toEqual("rgb(12.222% 12.222% 12.222%)"); }); it("should return correct color when lightness is between 0.14 and 0.21", () => { const { bgNeutralHover } = new LightModeTheme( "oklch(0.17 0.03 170)", ).getColors(); expect(bgNeutralHover).toEqual("rgb(12.222% 12.222% 12.222%)"); }); it("should return correct color when lightness is between 0.21 and 0.7", () => { const { bgNeutralHover } = new LightModeTheme( "oklch(0.35 0.03 170)", ).getColors(); expect(bgNeutralHover).toEqual("rgb(17.924% 17.924% 17.924%)"); }); it("should return correct color when lightness is between 0.7 and 0.955", () => { const { bgNeutralHover } = new LightModeTheme( "oklch(0.75 0.03 170)", ).getColors(); expect(bgNeutralHover).toEqual("rgb(62.05% 62.05% 62.05%)"); }); it("should return correct color when lightness > or equal to 0.955", () => { const { bgNeutralHover } = new LightModeTheme( "oklch(0.96 0.03 170)", ).getColors(); expect(bgNeutralHover).toEqual("rgb(92.148% 92.148% 92.148%)"); }); }); describe("bgNeutralActive color", () => { it("should return correct color when lightness < 0.4", () => { const { bgNeutralActive } = new LightModeTheme( "oklch(0.35 0.03 170)", ).getColors(); expect(bgNeutralActive).toEqual("rgb(10.396% 10.396% 10.396%)"); }); it("should return correct color when lightness is between 0.4 and 0.955", () => { const { bgNeutralActive } = new LightModeTheme( "oklch(0.80 0.03 170)", ).getColors(); expect(bgNeutralActive).toEqual("rgb(60.846% 60.846% 60.846%)"); }); it("should return correct color when lightness > or equal to 0.955", () => { const { bgNeutralActive } = new LightModeTheme( "oklch(0.96 0.03 170)", ).getColors(); expect(bgNeutralActive).toEqual("rgb(90.204% 90.204% 90.204%)"); }); }); describe("bgNeutralSubtle color", () => { it("should return correct color when lightness > 0.93", () => { const { bgNeutralSubtle } = new LightModeTheme( "oklch(0.95 0.03 170)", ).getColors(); expect(bgNeutralSubtle).toEqual("rgb(94.099% 94.099% 94.099%)"); }); it("should return correct color when lightness < or equal to 0.93", () => { const { bgNeutralSubtle } = new LightModeTheme( "oklch(0.92 0.03 170)", ).getColors(); expect(bgNeutralSubtle).toEqual("rgb(90.851% 90.851% 90.851%)"); }); it("should return correct color when seedChroma > 0.01", () => { const { bgNeutralSubtle } = new LightModeTheme( "oklch(0.92 0.1 170)", ).getColors(); expect(bgNeutralSubtle).toEqual("rgb(88.517% 91.796% 90.467%)"); }); it("should return correct color when chroma < 0.04", () => { const { bgNeutralSubtle } = new LightModeTheme( "oklch(0.92 0.03 170)", ).getColors(); expect(bgNeutralSubtle).toEqual("rgb(90.851% 90.851% 90.851%)"); }); }); describe("bgNeutralSubtleHover color", () => { it("should return correct color", () => { const { bgNeutralSubtleHover } = new LightModeTheme( "oklch(0.92 0.1 170)", ).getColors(); expect(bgNeutralSubtleHover).toEqual("rgb(91.102% 94.398% 93.061%)"); }); }); describe("bgNeutralSubtleActive color", () => { it("should return correct color", () => { const { bgNeutralSubtleActive } = new LightModeTheme( "oklch(0.92 0.1 170)", ).getColors(); expect(bgNeutralSubtleActive).toEqual("rgb(87.229% 90.5% 89.174%)"); }); }); describe("bgPositive color", () => { it("should return correct color when seed color is green (hue between 116 and 165) and chroma > 0.11", () => { const { bgPositive } = new LightModeTheme( "oklch(0.62 0.19 145)", ).getColors(); expect(bgPositive).toEqual("rgb(30.224% 61.63% 0%)"); }); it("should return correct color when seed color is green (hue between 116 and 165) but chroma is not greater than 0.11", () => { const { bgPositive } = new LightModeTheme( "oklch(0.62 0.1 145)", ).getColors(); expect(bgPositive).toEqual("rgb(6.7435% 63.436% 18.481%)"); }); it("should return correct color when seed color is not green (hue outside 116-165) and chroma > 0.11", () => { const { bgPositive } = new LightModeTheme( "oklch(0.62 0.19 100)", ).getColors(); expect(bgPositive).toEqual("rgb(6.7435% 63.436% 18.481%)"); }); it("should return correct color when seed color is not green (hue outside 116-165) and chroma is not greater than 0.11", () => { const { bgPositive } = new LightModeTheme( "oklch(0.62 0.1 100)", ).getColors(); expect(bgPositive).toEqual("rgb(6.7435% 63.436% 18.481%)"); }); }); describe("bgPositiveHover color", () => { it("should return correct color", () => { const { bgPositiveHover } = new LightModeTheme( "oklch(0.62 0.19 100)", ).getColors(); expect(bgPositiveHover).toEqual("rgb(18.172% 69.721% 25.266%)"); }); }); describe("bgPositiveActive color", () => { it("should return correct color", () => { const { bgPositiveActive } = new LightModeTheme( "oklch(0.62 0.19 100)", ).getColors(); expect(bgPositiveActive).toEqual("rgb(0% 60.947% 15.563%)"); }); }); describe("bgPositiveSubtle color", () => { it("should return correct color", () => { const { bgPositiveSubtle } = new LightModeTheme( "oklch(0.62 0.19 100)", ).getColors(); expect(bgPositiveSubtle).toEqual("rgb(81.329% 100% 81.391%)"); }); }); describe("bgPositiveSubtleHover color", () => { it("should return correct color", () => { const { bgPositiveSubtleHover } = new LightModeTheme( "oklch(0.62 0.19 100)", ).getColors(); expect(bgPositiveSubtleHover).toEqual("rgb(84.848% 100% 84.841%)"); }); }); describe("bgPositiveSubtleActive color", () => { it("should return correct color", () => { const { bgPositiveSubtleActive } = new LightModeTheme( "oklch(0.62 0.19 100)", ).getColors(); expect(bgPositiveSubtleActive).toEqual("rgb(80.049% 98.746% 80.116%)"); }); }); describe("bgNegative color", () => { it("should return correct color when seed color is red (hue between 5 and 49) and chroma > 0.12", () => { const { bgNegative } = new LightModeTheme( "oklch(0.55 0.22 27)", ).getColors(); expect(bgNegative).toEqual("rgb(82.941% 0.9786% 21.484%)"); }); it("should return correct color when seed color is red (hue between 5 and 49) but chroma is not greater than 0.12", () => { const { bgNegative } = new LightModeTheme("oklch(0.55 0.1 27)").getColors(); expect(bgNegative).toEqual("rgb(83.108% 4.6651% 10.252%)"); }); it("should return correct color when seed color is not red (hue outside 5-49) and chroma > 0.12", () => { const { bgNegative } = new LightModeTheme( "oklch(0.55 0.22 60)", ).getColors(); expect(bgNegative).toEqual("rgb(83.108% 4.6651% 10.252%)"); }); it("should return correct color when seed color is not red (hue outside 5-49) and chroma is not greater than 0.12", () => { const { bgNegative } = new LightModeTheme("oklch(0.55 0.1 60)").getColors(); expect(bgNegative).toEqual("rgb(83.108% 4.6651% 10.252%)"); }); }); describe("bgNegativeHover color", () => { it("should return correct color", () => { const { bgNegativeHover } = new LightModeTheme( "oklch(0.55 0.22 27)", ).getColors(); expect(bgNegativeHover).toEqual("rgb(90.138% 15.796% 27.164%)"); }); }); describe("bgNegativeActive color", () => { it("should return correct color", () => { const { bgNegativeActive } = new LightModeTheme( "oklch(0.55 0.22 27)", ).getColors(); expect(bgNegativeActive).toEqual("rgb(80.074% 0% 19.209%)"); }); }); describe("bgNegativeSubtle color", () => { it("should return correct color", () => { const { bgNegativeSubtle } = new LightModeTheme( "oklch(0.55 0.22 27)", ).getColors(); expect(bgNegativeSubtle).toEqual("rgb(80.074% 0% 19.209%)"); }); }); describe("bgNegativeSubtleHover color", () => { it("should return correct color", () => { const { bgNegativeSubtleHover } = new LightModeTheme( "oklch(0.55 0.22 27)", ).getColors(); expect(bgNegativeSubtleHover).toEqual("rgb(100% 93.507% 93.192%)"); }); }); describe("bgNegativeSubtleActive color", () => { it("should return correct color", () => { const { bgNegativeSubtleActive } = new LightModeTheme( "oklch(0.55 0.22 27)", ).getColors(); expect(bgNegativeSubtleActive).toEqual("rgb(100% 88.131% 87.677%)"); }); }); describe("bgWarning color", () => { it("should return correct color when seed color is yellow (hue between 60 and 115) and chroma > 0.09", () => { const { bgWarning } = new LightModeTheme("oklch(0.75 0.15 85)").getColors(); expect(bgWarning).toEqual("rgb(91.527% 60.669% 16.491%)"); }); it("should return correct color when seed color is yellow (hue between 60 and 115) but chroma is not greater than 0.09", () => { const { bgWarning } = new LightModeTheme("oklch(0.75 0.05 85)").getColors(); expect(bgWarning).toEqual("rgb(85.145% 64.66% 8.0286%)"); }); it("should return correct color when seed color is not yellow (hue outside 60-115) and chroma > 0.09", () => { const { bgWarning } = new LightModeTheme("oklch(0.75 0.15 85)").getColors(); expect(bgWarning).toEqual("rgb(91.527% 60.669% 16.491%)"); }); it("should return correct color when seed color is not yellow (hue outside 60-115) and chroma is not greater than 0.09", () => { const { bgWarning } = new LightModeTheme("oklch(0.75 0.05 85)").getColors(); expect(bgWarning).toEqual("rgb(85.145% 64.66% 8.0286%)"); }); }); describe("bgWarningHover color", () => { it("should return correct color", () => { const { bgWarningHover } = new LightModeTheme( "oklch(0.75 0.15 85)", ).getColors(); expect(bgWarningHover).toEqual("rgb(95.533% 64.413% 21.716%)"); }); }); describe("bgWarningActive color", () => { it("should return correct color", () => { const { bgWarningActive } = new LightModeTheme( "oklch(0.75 0.15 85)", ).getColors(); expect(bgWarningActive).toEqual("rgb(90.198% 59.428% 14.545%)"); }); }); describe("bgWarningSubtle color", () => { it("should return correct color", () => { const { bgWarningSubtle } = new LightModeTheme( "oklch(0.75 0.15 85)", ).getColors(); expect(bgWarningSubtle).toEqual("rgb(100% 93.263% 83.925%)"); }); }); describe("bgWarningSubtleHover color", () => { it("should return correct color", () => { const { bgWarningSubtleHover } = new LightModeTheme( "oklch(0.75 0.15 85)", ).getColors(); expect(bgWarningSubtleHover).toEqual("rgb(100% 96.499% 91.027%)"); }); }); describe("bgWarningSubtleActive color", () => { it("should return correct color", () => { const { bgWarningSubtleActive } = new LightModeTheme( "oklch(0.75 0.15 85)", ).getColors(); expect(bgWarningSubtleActive).toEqual("rgb(100% 91.621% 80.174%)"); }); }); describe("fg color", () => { it("should return correct color when chroma < 0.04", () => { const { fg } = new LightModeTheme("oklch(0.45 0.03 60)").getColors(); expect(fg).toEqual("rgb(2.2326% 2.2326% 2.2326%)"); }); it("should return correct color when chroma > 0.04", () => { const { fg } = new LightModeTheme("oklch(0.45 0.1 60)").getColors(); expect(fg).toEqual("rgb(5.4369% 1.2901% 0%)"); }); }); describe("fgAccent color", () => { it("should return correct color when chroma < 0.04", () => { const { fgAccent } = new LightModeTheme("oklch(0.45 0.03 60)").getColors(); expect(fgAccent).toEqual("rgb(38.473% 32.008% 26.943%)"); }); it("should return correct color when chroma > 0.04", () => { const { fgAccent } = new LightModeTheme("oklch(0.45 0.1 60)").getColors(); expect(fgAccent).toEqual("rgb(48.857% 27.291% 4.3335%)"); }); }); describe("fgNeutral color", () => { it("should return correct color when chroma < 0.04", () => { const { fgNeutral } = new LightModeTheme("oklch(0.45 0.03 60)").getColors(); expect(fgNeutral).toEqual("rgb(33.384% 33.384% 33.384%)"); }); it("should return correct color when chroma > 0.04 and hue is between 120 and 300", () => { const { fgNeutral } = new LightModeTheme("oklch(0.45 0.1 150)").getColors(); expect(fgNeutral).toEqual("rgb(25.52% 36.593% 27.669%)"); }); it("should return correct color when chroma > 0.04 and hue is not between 120 and 300", () => { const { fgNeutral } = new LightModeTheme("oklch(0.45 0.1 110)").getColors(); expect(fgNeutral).toEqual("rgb(33.531% 33.77% 30.07%)"); }); }); describe("fgNeutralSubtle color", () => { it("should return correct color", () => { const { fgNeutralSubtle } = new LightModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(fgNeutralSubtle).toEqual("rgb(44.47% 44.47% 44.47%)"); }); }); describe("fgPositive color", () => { it("should return correct color when chroma < 0.04", () => { const { fgPositive } = new LightModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(fgPositive).toEqual("rgb(6.7435% 63.436% 18.481%)"); }); it("should return correct color when lightness > 0.04", () => { const { fgPositive } = new LightModeTheme("oklch(0.45 0.1 60)").getColors(); expect(fgPositive).toEqual("rgb(6.7435% 63.436% 18.481%)"); }); it("should return correct color hue is between 116 and 165", () => { const { fgPositive } = new LightModeTheme( "oklch(0.45 0.1 120)", ).getColors(); expect(fgPositive).toEqual("rgb(6.7435% 63.436% 18.481%)"); }); it("should return correct color hue is not between 116 and 165", () => { const { fgPositive } = new LightModeTheme("oklch(0.45 0.1 30)").getColors(); expect(fgPositive).toEqual("rgb(6.7435% 63.436% 18.481%)"); }); }); describe("fgNegative color", () => { it("should return correct color when chroma < 0.04", () => { const { fgNegative } = new LightModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(fgNegative).toEqual("rgb(100% 0% 28.453%)"); }); it("should return correct color when chroma > 0.04", () => { const { fgNegative } = new LightModeTheme("oklch(0.45 0.1 60)").getColors(); expect(fgNegative).toEqual("rgb(100% 0% 28.453%)"); }); it("should return correct color hue is between 5 and 49", () => { const { fgNegative } = new LightModeTheme("oklch(0.45 0.1 30)").getColors(); expect(fgNegative).toEqual("rgb(100% 0% 28.453%)"); }); it("should return correct color hue is not between 5 and 49", () => { const { fgNegative } = new LightModeTheme( "oklch(0.45 0.1 120)", ).getColors(); expect(fgNegative).toEqual("rgb(100% 0% 28.453%)"); }); }); describe("fgWarning color", () => { it("should return correct color", () => { const { fgWarning } = new LightModeTheme("oklch(0.45 0.03 60)").getColors(); expect(fgWarning).toEqual("rgb(71.79% 51.231% 0%)"); }); }); describe("fgOnAccent color ", () => { it("should return correct color when chroma < 0.04", () => { const { fgOnAccent } = new LightModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(fgOnAccent).toEqual("rgb(94.752% 94.752% 94.752%)"); }); it("should return correct color when chroma > 0.04", () => { const { fgOnAccent } = new LightModeTheme("oklch(0.45 0.1 60)").getColors(); expect(fgOnAccent).toEqual("rgb(100% 92.634% 85.713%)"); }); }); describe("fgOnAssistive color ", () => { it("should return correct color", () => { const { fgOnAssistive } = new LightModeTheme( "oklch(0.45 0.03 110)", ).getColors(); expect(fgOnAssistive).toEqual("rgb(96.059% 96.059% 96.059%)"); }); }); describe("fgOnNeutral color ", () => { it("should return correct color", () => { const { fgOnNeutral } = new LightModeTheme( "oklch(0.45 0.03 110)", ).getColors(); expect(fgOnNeutral).toEqual("rgb(94.752% 94.752% 94.752%)"); }); }); describe("fgOnPositive color ", () => { it("should return correct color", () => { const { fgOnPositive } = new LightModeTheme( "oklch(0.45 0.03 110)", ).getColors(); expect(fgOnPositive).toEqual("rgb(89.702% 100% 89.053%)"); }); }); describe("fgOnNegative color ", () => { it("should return correct color", () => { const { fgOnNegative } = new LightModeTheme( "oklch(0.45 0.03 110)", ).getColors(); expect(fgOnNegative).toEqual("rgb(100% 87.612% 85.249%)"); }); }); describe("fgOnWarning color ", () => { it("should return correct color", () => { const { fgOnWarning } = new LightModeTheme( "oklch(0.45 0.03 110)", ).getColors(); expect(fgOnWarning).toEqual("rgb(21.953% 9.0775% 0%)"); }); }); describe("bd color", () => { it("should return correct color", () => { const { bd } = new LightModeTheme("oklch(0.45 0.5 60)").getColors(); expect(bd).toEqual("rgb(80.718% 72.709% 66.526%)"); }); }); describe("bdAccent color", () => { it("should return correct color when chroma < 0.04", () => { const { bdAccent } = new LightModeTheme("oklch(0.45 0.03 60)").getColors(); expect(bdAccent).toEqual("rgb(38.473% 32.008% 26.943%)"); }); it("should return correct color when chroma > 0.04", () => { const { bdAccent } = new LightModeTheme("oklch(0.45 0.1 60)").getColors(); expect(bdAccent).toEqual("rgb(48.857% 27.291% 4.3335%)"); }); }); describe("bdFocus color", () => { it("should return correct color when lightness < 0.6", () => { const { bdFocus } = new LightModeTheme("oklch(0.45 0.4 60)").getColors(); expect(bdFocus).toEqual("rgb(56.074% 13.73% 0%)"); }); it("should return correct color when lightness > 0.8", () => { const { bdFocus } = new LightModeTheme("oklch(0.85 0.03 60)").getColors(); expect(bdFocus).toEqual("rgb(31.389% 9.8% 0%)"); }); it("should return correct color when chroma < 0.15", () => { const { bdFocus } = new LightModeTheme("oklch(0.85 0.1 60)").getColors(); expect(bdFocus).toEqual("rgb(64.667% 36.271% 0%)"); }); it("should return correct color when hue is between 0 and 55", () => { const { bdFocus } = new LightModeTheme("oklch(0.85 0.1 30)").getColors(); expect(bdFocus).toEqual("rgb(100% 70.125% 64.059%)"); }); it("should return correct color when hue > 340", () => { const { bdFocus } = new LightModeTheme("oklch(0.85 0.1 350)").getColors(); expect(bdFocus).toEqual("rgb(100% 67.07% 84.709%)"); }); }); describe("bdNeutral color", () => { it("should return correct color when chroma < 0.04", () => { const { bdNeutral } = new LightModeTheme("oklch(0.45 0.03 60)").getColors(); expect(bdNeutral).toEqual("rgb(33.384% 33.384% 33.384%)"); }); }); describe("bdNeutralHover", () => { it("should return correct color", () => { const { bdNeutralHover } = new LightModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdNeutralHover).toEqual("rgb(62.05% 62.05% 62.05%)"); }); }); describe("bdPositive", () => { it("should return correct color", () => { const { bdPositive } = new LightModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdPositive).toEqual("rgb(6.7435% 63.436% 18.481%)"); }); }); describe("bdPositiveHover", () => { it("should return correct color", () => { const { bdPositiveHover } = new LightModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdPositiveHover).toEqual("rgb(26.362% 76.094% 31.718%)"); }); }); describe("bdNegative", () => { it("should return correct color", () => { const { bdNegative } = new LightModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdNegative).toEqual("rgb(83.108% 4.6651% 10.252%)"); }); }); describe("bdNegativeHover", () => { it("should return correct color", () => { const { bdNegativeHover } = new LightModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdNegativeHover).toEqual("rgb(97.525% 25.712% 23.78%)"); }); }); describe("bdWarning", () => { it("should return correct color", () => { const { bdWarning } = new LightModeTheme("oklch(0.45 0.03 60)").getColors(); expect(bdWarning).toEqual("rgb(85.145% 64.66% 8.0286%)"); }); }); describe("bdWarningHover", () => { it("should return correct color", () => { const { bdWarningHover } = new LightModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdWarningHover).toEqual("rgb(98.232% 77.293% 27.893%)"); }); }); describe("bdOnAccent", () => { it("should return correct color", () => { const { bdOnAccent } = new LightModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdOnAccent).toEqual("rgb(5.2437% 1.364% 0%)"); }); }); describe("bdOnNeutral", () => { it("should return correct color", () => { const { bdOnNeutral } = new LightModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdOnNeutral).toEqual("rgb(46.751% 46.751% 46.751%)"); }); }); describe("bdOnPositive", () => { it("should return correct color", () => { const { bdOnPositive } = new LightModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdOnPositive).toEqual("rgb(0% 22.552% 3.6201%)"); }); }); describe("bdOnNegative", () => { it("should return correct color", () => { const { bdOnNegative } = new LightModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdOnNegative).toEqual("rgb(21.923% 0% 2.8118%)"); }); }); describe("bdOnWarning", () => { it("should return correct color", () => { const { bdOnWarning } = new LightModeTheme( "oklch(0.45 0.03 60)", ).getColors(); expect(bdOnWarning).toEqual("rgb(39.972% 27.552% 0%)"); }); });
7,494
0
petrpan-code/appsmithorg/appsmith/app/client/packages/design-system/widgets/src/components/Button
petrpan-code/appsmithorg/appsmith/app/client/packages/design-system/widgets/src/components/Button/tests/Button.test.tsx
import React from "react"; import "@testing-library/jest-dom"; import type { ComponentProps } from "react"; import { render, screen } from "@testing-library/react"; import { Button } from "../"; // Adapted from remixicon-react/EmotionHappyLineIcon (https://github.com/Remix-Design/RemixIcon/blob/f88a51b6402562c6c2465f61a3e845115992e4c6/icons/User%20%26%20Faces/emotion-happy-line.svg) const EmotionHappyLineIcon = ({ ...props }: ComponentProps<"svg">) => { return ( <svg fill="currentColor" height={24} viewBox="0 0 24 24" width={24} {...props} > <path d="M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10Zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm-5-7h2a3 3 0 1 0 6 0h2a5 5 0 0 1-10 0Zm1-2a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3Zm8 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3Z" /> </svg> ); }; describe("@design-system/widgets/Button", () => { it("renders children when passed", () => { render(<Button>Click me</Button>); expect(screen.getByRole("button")).toHaveTextContent("Click me"); }); it("passes type to button component", () => { render(<Button type="submit" />); expect(screen.getByRole("button")).toHaveAttribute("type", "submit"); }); it("sets variant based on prop", () => { render(<Button variant="filled" />); expect(screen.getByRole("button")).toHaveAttribute( "data-variant", "filled", ); }); it("sets disabled attribute based on prop", () => { render(<Button isDisabled />); expect(screen.getByRole("button")).toBeDisabled(); expect(screen.getByRole("button")).toHaveAttribute("data-disabled"); }); it("sets data-loading attribute and icon based on loading prop", () => { render(<Button isLoading />); expect(screen.getByRole("button")).toHaveAttribute("data-loading"); const icon = screen.getByRole("button").querySelector("[data-icon]"); expect(icon).toBeInTheDocument(); }); it("renders icon when passed", () => { const { container } = render(<Button icon={EmotionHappyLineIcon} />); const icon = container.querySelector("button [data-icon]") as HTMLElement; expect(icon).toBeInTheDocument(); }); it("sets icon position attribute based on the prop ", () => { render(<Button iconPosition="end" />); const button = screen.getByRole("button"); expect(button).toHaveAttribute("data-icon-position", "end"); }); });
7,503
0
petrpan-code/appsmithorg/appsmith/app/client/packages/design-system/widgets/src/components/ButtonGroup
petrpan-code/appsmithorg/appsmith/app/client/packages/design-system/widgets/src/components/ButtonGroup/tests/ButtonGroup.test.tsx
import React from "react"; import "@testing-library/jest-dom"; import { render, screen } from "@testing-library/react"; import { ButtonGroup, ButtonGroupItem } from "../"; import type { ButtonGroupProps } from "../"; const renderComponent = (props: ButtonGroupProps = {}) => { return render( <ButtonGroup {...props}> <ButtonGroupItem data-testid="Button 1" key="1"> Button 1 </ButtonGroupItem> <ButtonGroupItem data-testid="Button 2" key="2"> Button 2 </ButtonGroupItem> </ButtonGroup>, ); }; describe("@design-system/widgets/Button Group", () => { it("should render the button group", () => { renderComponent(); expect(screen.getByText("Button 1")).toBeInTheDocument(); expect(screen.getByText("Button 2")).toBeInTheDocument(); }); it("should support custom props", () => { const { container } = renderComponent({ "data-testid": "button-group", } as ButtonGroupProps); const buttonGroup = container.querySelector("div") as HTMLElement; expect(buttonGroup).toHaveAttribute("data-testid", "button-group"); }); it("should add variant to button group item", () => { renderComponent({ variant: "ghost", }); expect(screen.getByTestId("Button 1")).toHaveAttribute( "data-variant", "ghost", ); expect(screen.getByTestId("Button 2")).toHaveAttribute( "data-variant", "ghost", ); }); it("should add color to button group item", () => { renderComponent({ color: "neutral", }); expect(screen.getByTestId("Button 1")).toHaveAttribute( "data-color", "neutral", ); expect(screen.getByTestId("Button 2")).toHaveAttribute( "data-color", "neutral", ); }); });
7,510
0
petrpan-code/appsmithorg/appsmith/app/client/packages/design-system/widgets/src/components/Checkbox
petrpan-code/appsmithorg/appsmith/app/client/packages/design-system/widgets/src/components/Checkbox/tests/Checkbox.test.tsx
import React from "react"; import "@testing-library/jest-dom"; import type { ComponentProps } from "react"; import { Checkbox } from "@design-system/widgets"; import userEvent from "@testing-library/user-event"; import { render, screen } from "@testing-library/react"; // Adapted from remixicon-react/EmotionHappyLineIcon (https://github.com/Remix-Design/RemixIcon/blob/f88a51b6402562c6c2465f61a3e845115992e4c6/icons/User%20%26%20Faces/emotion-happy-line.svg) const EmotionHappyLineIcon = (props: ComponentProps<"svg">) => { return ( <svg fill="currentColor" height={24} viewBox="0 0 24 24" width={24} {...props} > <path d="M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10Zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm-5-7h2a3 3 0 1 0 6 0h2a5 5 0 0 1-10 0Zm1-2a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3Zm8 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3Z" /> </svg> ); }; describe("@design-system/widgets/Checkbox", () => { const onChangeSpy = jest.fn(); it("should render the checkbox", () => { render(<Checkbox>Click me</Checkbox>); expect(screen.getByText("Click me")).toBeInTheDocument(); }); it("should render uncontrolled checkbox", () => { render( <Checkbox defaultSelected onChange={onChangeSpy}> Checkbox </Checkbox>, ); const checkbox = screen.getByRole("checkbox"); expect(checkbox).toBeChecked(); userEvent.click(checkbox); expect(onChangeSpy).toHaveBeenCalled(); expect(screen.getByRole("checkbox")).not.toBeChecked(); }); it("should render controlled checkbox", () => { const { rerender } = render(<Checkbox isSelected>Checkbox</Checkbox>); expect(screen.getByRole("checkbox")).toBeChecked(); rerender(<Checkbox isSelected={false}>Checkbox</Checkbox>); expect(screen.getByRole("checkbox")).not.toBeChecked(); }); it("should render disabled checkbox", () => { render(<Checkbox isDisabled>Checkbox</Checkbox>); expect(screen.getByRole("checkbox")).toBeDisabled(); }); it("should render invalid attributes when input is invalid", () => { render(<Checkbox validationState="invalid">Checkbox</Checkbox>); const checkbox = screen.getByRole("checkbox"); expect(checkbox).toHaveAttribute("aria-invalid", "true"); }); it("should render indeterminate checkbox", () => { const { container } = render(<Checkbox isIndeterminate>Checkbox</Checkbox>); const label = container.querySelector("label") as HTMLElement; const checkbox = screen.getByRole("checkbox") as HTMLInputElement; expect(checkbox.indeterminate).toBe(true); expect(label).toHaveAttribute("data-state", "indeterminate"); }); it("should be able to render custom icon", () => { const { container } = render(<Checkbox icon={EmotionHappyLineIcon} />); const icon = container.querySelector("label [data-icon]") as HTMLElement; expect(icon).toBeInTheDocument(); }); });
7,516
0
petrpan-code/appsmithorg/appsmith/app/client/packages/design-system/widgets/src/components/CheckboxGroup
petrpan-code/appsmithorg/appsmith/app/client/packages/design-system/widgets/src/components/CheckboxGroup/tests/CheckboxGroup.test.tsx
import React from "react"; import "@testing-library/jest-dom"; import userEvent from "@testing-library/user-event"; import { render, screen } from "@testing-library/react"; import { CheckboxGroup } from "../"; import { Checkbox } from "../../Checkbox"; describe("@design-system/widgets/CheckboxGroup", () => { it("should render the checkbox group", () => { const { container } = render( <CheckboxGroup label="Checkbox Group"> <Checkbox value="value-1">Value 1</Checkbox> <Checkbox value="value-2">Value 2</Checkbox> </CheckboxGroup>, ); expect(screen.getByText("Value 1")).toBeInTheDocument(); expect(screen.getByText("Value 2")).toBeInTheDocument(); const label = container.querySelector("label") as HTMLElement; expect(label).toHaveTextContent("Checkbox Group"); const checkboxGroup = screen.getByRole("group"); expect(checkboxGroup).toHaveAttribute("aria-labelledby"); expect(checkboxGroup.getAttribute("aria-labelledby")).toBe(label.id); const checkboxes = screen.getAllByRole("checkbox"); expect(checkboxes[0]).toHaveAttribute("value", "value-1"); expect(checkboxes[1]).toHaveAttribute("value", "value-2"); expect(checkboxes[0]).not.toBeChecked(); expect(checkboxes[1]).not.toBeChecked(); userEvent.click(checkboxes[0]); expect(checkboxes[0]).toBeChecked(); userEvent.click(checkboxes[1]); expect(checkboxes[1]).toBeChecked(); }); it("should support custom props", () => { render( <CheckboxGroup data-testid="checkbox-group" label="Checkbox Group Label"> <Checkbox value="value-1">Value 1</Checkbox> <Checkbox value="value-2">Value 2</Checkbox> </CheckboxGroup>, ); const checkboxGroup = screen.getByTestId("checkbox-group"); expect(checkboxGroup).toBeInTheDocument(); }); it("should render checked checkboxes when value is passed", () => { render( <CheckboxGroup label="Checkbox Group Label" value={["value-1", "value-2"]} > <Checkbox value="value-1">Value 1</Checkbox> <Checkbox value="value-2">Value 2</Checkbox> </CheckboxGroup>, ); const checkboxes = screen.getAllByRole("checkbox"); expect(checkboxes[0]).toBeChecked(); expect(checkboxes[1]).toBeChecked(); }); it("should be able to fire onChange event", () => { const onChangeSpy = jest.fn(); render( <CheckboxGroup label="Checkbox Group Label" onChange={onChangeSpy}> <Checkbox value="value-1">Value 1</Checkbox> <Checkbox value="value-2">Value 2</Checkbox> </CheckboxGroup>, ); const checkboxes = screen.getAllByRole("checkbox"); userEvent.click(checkboxes[0]); expect(onChangeSpy).toHaveBeenCalled(); }); it("should be able to render disabled checkboxes", () => { render( <CheckboxGroup isDisabled label="Checkbox Group Label"> <Checkbox value="value-1">Value 1</Checkbox> <Checkbox value="value-2">Value 2</Checkbox> </CheckboxGroup>, ); const checkboxes = screen.getAllByRole("checkbox"); expect(checkboxes[0]).toBeDisabled(); expect(checkboxes[1]).toBeDisabled(); }); });
7,559
0
petrpan-code/appsmithorg/appsmith/app/client/packages/design-system/widgets/src/components/RadioGroup
petrpan-code/appsmithorg/appsmith/app/client/packages/design-system/widgets/src/components/RadioGroup/tests/RadioGroup.test.tsx
import React from "react"; import "@testing-library/jest-dom"; import userEvent from "@testing-library/user-event"; import { render, screen } from "@testing-library/react"; import { RadioGroup } from "../"; import { Radio } from "../../Radio"; describe("@design-system/widgets/RadioGroup", () => { it("should render the Radio group", () => { const { container } = render( <RadioGroup label="Radio Group"> <Radio value="value-1">Value 1</Radio> <Radio value="value-2">Value 2</Radio> </RadioGroup>, ); expect(screen.getByText("Value 1")).toBeInTheDocument(); expect(screen.getByText("Value 2")).toBeInTheDocument(); const label = container.querySelector("label") as HTMLElement; expect(label).toHaveTextContent("Radio Group"); const radioGroup = screen.getByRole("radiogroup"); expect(radioGroup).toHaveAttribute("aria-labelledby"); expect(radioGroup.getAttribute("aria-labelledby")).toBe(label.id); const options = screen.getAllByRole("radio"); expect(options[0]).toHaveAttribute("value", "value-1"); expect(options[1]).toHaveAttribute("value", "value-2"); expect(options[0]).not.toBeChecked(); expect(options[1]).not.toBeChecked(); userEvent.click(options[0]); expect(options[0]).toBeChecked(); userEvent.click(options[1]); expect(options[0]).not.toBeChecked(); expect(options[1]).toBeChecked(); }); it("should support custom props", () => { render( <RadioGroup data-testid="radio-group" label="Radio Group Label"> <Radio value="value-1">Value 1</Radio> <Radio value="value-2">Value 2</Radio> <Radio value="value-3">Value 3</Radio> </RadioGroup>, ); const radioGroup = screen.getByTestId("radio-group"); expect(radioGroup).toBeInTheDocument(); }); it("should render checked checkboxes when value is passed", () => { render( <RadioGroup label="Radio Group Label" value="value-1"> <Radio value="value-1">Value 1</Radio> <Radio value="value-2">Value 2</Radio> </RadioGroup>, ); const options = screen.getAllByRole("radio"); expect(options[0]).toBeChecked(); expect(options[1]).not.toBeChecked(); }); it("should be able to fire onChange event", () => { const onChangeSpy = jest.fn(); render( <RadioGroup label="Radio Group Label" onChange={onChangeSpy}> <Radio value="value-1">Value 1</Radio> <Radio value="value-2">Value 2</Radio> </RadioGroup>, ); const options = screen.getAllByRole("radio"); userEvent.click(options[0]); expect(onChangeSpy).toHaveBeenCalled(); }); it("should be able to render disabled checkboxes", () => { render( <RadioGroup isDisabled label="Radio Group Label"> <Radio value="value-1">Value 1</Radio> <Radio value="value-2">Value 2</Radio> </RadioGroup>, ); const options = screen.getAllByRole("radio"); expect(options[0]).toBeDisabled(); expect(options[1]).toBeDisabled(); }); });
7,579
0
petrpan-code/appsmithorg/appsmith/app/client/packages/design-system/widgets/src/components/Text
petrpan-code/appsmithorg/appsmith/app/client/packages/design-system/widgets/src/components/Text/tests/Text.test.tsx
import React from "react"; import "@testing-library/jest-dom"; import { render, screen } from "@testing-library/react"; import { Text } from "../"; describe("@design-system/widgets/Text", () => { it("should render the text", () => { render(<Text>My Text</Text>); expect(screen.getByText("My Text")).toBeInTheDocument(); }); it("should support custom props", () => { const { container } = render(<Text data-testid="text">My Text</Text>); const text = container.querySelector("div") as HTMLElement; expect(text).toHaveAttribute("data-testid", "text"); }); });
7,629
0
petrpan-code/appsmithorg/appsmith/app/client/packages/dsl
petrpan-code/appsmithorg/appsmith/app/client/packages/dsl/src/index.test.ts
import { nestDSL, flattenDSL } from "./DSL"; import { ROOT_CONTAINER_WIDGET_ID } from "./constants"; describe("Test #1 - Check export types & constant values", () => { it("nestDSL is a function", () => { expect(typeof nestDSL).toBe("function"); }); it("flattenDSL is a function", () => { expect(typeof flattenDSL).toBe("function"); }); it("ROOT_CONTAINER_WIDGET_ID is a string", () => { expect(typeof ROOT_CONTAINER_WIDGET_ID).toBe("string"); }); it("ROOT_CONTAINER_WIDGET_ID remains 0", () => { expect(ROOT_CONTAINER_WIDGET_ID).toBe("0"); }); }); describe("Test #2 - normalize operations on SIMPLE DSL structures", () => { const simple_dsl = { widgetId: "0", widgetName: "MainContainer", isCanvas: true, children: [ { widgetId: "0/0", widgetName: "Text1", isCanvas: false, }, { widgetId: "0/1", widgetName: "Container1", isCanvas: false, children: [ { widgetId: "0/1/0", widgetName: "Canvas1", isCanvas: true, children: [ { widgetId: "0/1/0/0", widgetName: "Button1", isCanvas: false, label: "Click me!", }, ], }, ], }, ], }; const simple_flat_dsl = { "0": { widgetId: "0", widgetName: "MainContainer", isCanvas: true, children: ["0/0", "0/1"], }, "0/0": { widgetId: "0/0", widgetName: "Text1", isCanvas: false, }, "0/1": { widgetId: "0/1", widgetName: "Container1", children: ["0/1/0"], isCanvas: false, }, "0/1/0": { widgetId: "0/1/0", widgetName: "Canvas1", isCanvas: true, children: ["0/1/0/0"], }, "0/1/0/0": { widgetId: "0/1/0/0", widgetName: "Button1", isCanvas: false, label: "Click me!", }, }; it("Test `flattenDSL` for simple_dsl", () => { const flatDSL = flattenDSL<Record<string, unknown>>(simple_dsl); expect(flatDSL).toStrictEqual(simple_flat_dsl); }); it("Test `nestDSL` for simple_flat_dsl", () => { const nestedDSL = nestDSL(simple_flat_dsl); expect(nestedDSL).toStrictEqual(simple_dsl); }); }); export {};
7,656
0
petrpan-code/appsmithorg/appsmith/app/client/packages/rts/src
petrpan-code/appsmithorg/appsmith/app/client/packages/rts/src/test/server.test.ts
import app, { RTS_BASE_API_PATH } from "../server"; import supertest from "supertest"; const singleScript = { script: "(function abc() { let Api2 = { }; return Api2.data ? str.data + Api1.data : [] })()", }; const multipleScripts = { scripts: [ "(function abc() { return Api1.data })() ", "(function abc() { let str = ''; return str ? Api1.data : [] })()", ], }; const entityRefactor = [ { script: "ApiNever", oldName: "ApiNever", newName: "ApiForever", isJSObject: false, evalVersion: 2, }, { script: "ApiNever.data", oldName: "ApiNever", newName: "ApiForever", isJSObject: false, }, { script: "// ApiNever \n function ApiNever(abc) {let foo = \"I'm getting data from ApiNever but don't rename this string\" + ApiNever.data; \n if(true) { return ApiNever }}", oldName: "ApiNever", newName: "ApiForever", isJSObject: false, evalVersion: 2, }, { script: "//ApiNever \n function ApiNever(abc) {let ApiNever = \"I'm getting data from ApiNever but don't rename this string\" + ApiNever.data; \n if(true) { return ApiNever }}", oldName: "ApiNever", newName: "ApiForever", isJSObject: false, }, { script: "export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\t\tsearch: () => {\n\t\tif(Input1Copy.text.length==0){\n\t\t\treturn select_repair_db.data\n\t\t}\n\t\telse{\n\t\t\treturn(select_repair_db.data.filter(word => word.cust_name.toLowerCase().includes(Input1Copy.text.toLowerCase())))\n\t\t}\n\t},\n}", oldName: "Input1Copy", newName: "Input1", isJSObject: true, evalVersion: 2, }, { script: "// ApiNever \n function ApiNever(abc) {let foo = \"I'm getting data from ApiNever but don't rename this string\" + ApiNever.data; \n if(true) { return ApiNever }}", oldName: "ApiNever.data", newName: "ApiNever.input", isJSObject: false, evalVersion: 2, }, { script: "// ApiNever \n function ApiNever(abc) {let foo = \"I'm getting data from ApiNever but don't rename this string\" + ApiNever.data; \n if(true) { return ApiNever }}", oldName: "ApiNever.dat", newName: "ApiNever.input", isJSObject: false, evalVersion: 2, }, { script: "\tApiNever.data", oldName: "ApiNever", newName: "ApiForever", isJSObject: false, evalVersion: 2, }, { script: "ApiNever.data + ApiNever.data", oldName: "ApiNever", newName: "ApiForever", isJSObject: false, evalVersion: 2, }, { script: 'export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\tmyFun1: () => {\n\t\t//write code here\n\t\t// ApiNever.text\n\t\treturn "ApiNever.text" + ApiNever.text\n\t},\n\tmyFun2: async () => {\n\t\t//use async-await or promises\n\t\t// ApiNever.text\n\t\treturn "ApiNever.text" + ApiNever.text\n\t}\n}', oldName: "ApiNever", newName: "ApiForever", isJSObject: true, evalVersion: 2, }, { script: '(function(){\n try{\n ApiNever.run(); \n showAlert("Sucessful Trigger");\n }catch(error){\nshowAlert("Unsucessful Trigger");\n }\n})()', oldName: "ApiNever", newName: "ApiForever", isJSObject: false, evalVersion: 2, }, ]; afterAll((done) => { app.close(); done(); }); describe("AST tests", () => { it("Checks to see if single script is parsed correctly using the API", async () => { const expectedResponse = { references: ["str.data", "Api1.data"], functionalParams: [], variables: ["Api2"], }; await supertest(app) .post(`${RTS_BASE_API_PATH}/ast/single-script-data`, { JSON: true, }) .send(singleScript) .expect(200) .then((response) => { expect(response.body.success).toEqual(true); expect(response.body.data).toEqual(expectedResponse); }); }); it("Checks to see if multiple scripts are parsed correctly using the API", async () => { const expectedResponse = [ { references: ["Api1.data"], functionalParams: [], variables: [], }, { references: ["Api1.data"], functionalParams: [], variables: ["str"], }, ]; await supertest(app) .post(`${RTS_BASE_API_PATH}/ast/multiple-script-data`, { JSON: true, }) .send(multipleScripts) .expect(200) .then((response) => { expect(response.body.success).toEqual(true); expect(response.body.data.length).toBeGreaterThan(1); expect(response.body.data).toEqual(expectedResponse); }); }); entityRefactor.forEach(async (input, index) => { it(`Entity refactor test case ${index + 1}`, async () => { const expectedResponse = [ { script: "ApiForever", refactorCount: 1 }, { script: "ApiForever.data", refactorCount: 1 }, { script: "// ApiNever \n function ApiNever(abc) {let foo = \"I'm getting data from ApiNever but don't rename this string\" + ApiForever.data; \n if(true) { return ApiForever }}", refactorCount: 2, }, { script: "//ApiNever \n function ApiNever(abc) {let ApiNever = \"I'm getting data from ApiNever but don't rename this string\" + ApiNever.data; \n if(true) { return ApiNever }}", refactorCount: 0, }, { script: "export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\t\tsearch: () => {\n\t\tif(Input1.text.length==0){\n\t\t\treturn select_repair_db.data\n\t\t}\n\t\telse{\n\t\t\treturn(select_repair_db.data.filter(word => word.cust_name.toLowerCase().includes(Input1.text.toLowerCase())))\n\t\t}\n\t},\n}", refactorCount: 2, }, { script: "// ApiNever \n function ApiNever(abc) {let foo = \"I'm getting data from ApiNever but don't rename this string\" + ApiNever.input; \n if(true) { return ApiNever }}", refactorCount: 1, }, { script: "// ApiNever \n function ApiNever(abc) {let foo = \"I'm getting data from ApiNever but don't rename this string\" + ApiNever.data; \n if(true) { return ApiNever }}", refactorCount: 0, }, { script: "\tApiForever.data", refactorCount: 1, }, { script: "ApiForever.data + ApiForever.data", refactorCount: 2, }, { script: 'export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\tmyFun1: () => {\n\t\t//write code here\n\t\t// ApiNever.text\n\t\treturn "ApiNever.text" + ApiForever.text\n\t},\n\tmyFun2: async () => {\n\t\t//use async-await or promises\n\t\t// ApiNever.text\n\t\treturn "ApiNever.text" + ApiForever.text\n\t}\n}', refactorCount: 2, }, { script: '(function(){\n try{\n ApiForever.run(); \n showAlert("Sucessful Trigger");\n }catch(error){\nshowAlert("Unsucessful Trigger");\n }\n})()', refactorCount: 1, }, ]; await supertest(app) .post(`${RTS_BASE_API_PATH}/ast/entity-refactor`, { JSON: true, }) .send(input) .expect(200) .then((response) => { expect(response.body.success).toEqual(true); expect(response.body.data.script).toEqual( expectedResponse[index].script, ); expect(response.body.data.refactorCount).toEqual( expectedResponse[index].refactorCount, ); }); }); }); it("Entity refactor syntax error", async () => { const request = { script: "ApiNever++++", oldName: "ApiNever", newName: "ApiForever", isJSObject: true, evalVersion: 2, }; await supertest(app) .post(`${RTS_BASE_API_PATH}/ast/entity-refactor`, { JSON: true, }) .send(request) .expect(200) .then((response) => { expect(response.body.success).toEqual(false); expect(response.body.data.error).toEqual("Syntax Error"); }); }); });
7,720
0
petrpan-code/appsmithorg/appsmith/app/client/src/WidgetQueryGenerators
petrpan-code/appsmithorg/appsmith/app/client/src/WidgetQueryGenerators/GSheets/index.test.ts
import { DatasourceConnectionMode } from "entities/Datasource"; import GSheets from "."; describe("GSheets WidgetQueryGenerator", () => { const initialValues = { actionConfiguration: { formData: { entityType: { data: "ROWS", }, tableHeaderIndex: { data: "1", }, projection: { data: [], }, queryFormat: { data: "ROWS", }, range: { data: "", }, where: { data: { condition: "AND", }, }, pagination: { data: { limit: "{{Table1.pageSize}}", offset: "{{Table1.pageOffset}}", }, }, smartSubstitution: { data: true, }, }, }, }; test("should build select form data correctly", () => { const expr = GSheets.build( { select: { limit: "data_table.pageSize", where: "data_table.searchText", offset: "(data_table.pageNo - 1) * data_table.pageSize", orderBy: "data_table.sortOrder.column || 'genres'", sortOrder: 'data_table.sortOrder.order == "desc" ? -1 : 1', }, totalRecord: false, }, { tableName: "someTableUrl", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "", sheetName: "someSheet", tableHeaderIndex: 1, connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([ { name: "Find_someSheet", payload: { formData: { command: { data: "FETCH_MANY", }, entityType: { data: "ROWS", }, pagination: { data: { limit: "{{data_table.pageSize}}", offset: "{{(data_table.pageNo - 1) * data_table.pageSize}}", }, }, projection: { data: [], }, queryFormat: { data: "ROWS", }, range: { data: "", }, sheetName: { data: "someSheet", }, sheetUrl: { data: "someTableUrl", }, smartSubstitution: { data: true, }, sortBy: { data: [ { column: "{{data_table.sortOrder.column || 'genres'}}", order: 'data_table.sortOrder.order == "desc" ? -1 : 1', }, ], }, tableHeaderIndex: { data: "1", }, where: { data: { children: [ { condition: "CONTAINS", key: '{{data_table.searchText ? "title" : ""}}', value: "{{data_table.searchText}}", }, ], condition: "AND", }, }, }, }, type: "select", dynamicBindingPathList: [ { key: "formData.where.data", }, { key: "formData.sortBy.data", }, { key: "formData.pagination.data", }, ], }, ]); }); test("should build select form data without write permissions", () => { const expr = GSheets.build( { select: { limit: "data_table.pageSize", where: "data_table.searchText", offset: "(data_table.pageNo - 1) * data_table.pageSize", orderBy: "data_table.sortOrder.column || 'genres'", sortOrder: 'data_table.sortOrder.order == "desc" ? -1 : 1', }, totalRecord: false, }, { tableName: "someTableUrl", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "", sheetName: "someSheet", tableHeaderIndex: 1, connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); expect(expr).toEqual([ { name: "Find_someSheet", payload: { formData: { command: { data: "FETCH_MANY", }, entityType: { data: "ROWS", }, pagination: { data: { limit: "{{data_table.pageSize}}", offset: "{{(data_table.pageNo - 1) * data_table.pageSize}}", }, }, projection: { data: [], }, queryFormat: { data: "ROWS", }, range: { data: "", }, sheetName: { data: "someSheet", }, sheetUrl: { data: "someTableUrl", }, smartSubstitution: { data: true, }, sortBy: { data: [ { column: "{{data_table.sortOrder.column || 'genres'}}", order: 'data_table.sortOrder.order == "desc" ? -1 : 1', }, ], }, tableHeaderIndex: { data: "1", }, where: { data: { children: [ { condition: "CONTAINS", key: '{{data_table.searchText ? "title" : ""}}', value: "{{data_table.searchText}}", }, ], condition: "AND", }, }, }, }, type: "select", dynamicBindingPathList: [ { key: "formData.where.data", }, { key: "formData.sortBy.data", }, { key: "formData.pagination.data", }, ], }, ]); }); test("should build update form data correctly ", () => { const expr = GSheets.build( { update: { value: "update_form.formData", }, totalRecord: false, }, { tableName: "someTableUrl", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "", sheetName: "someSheet", tableHeaderIndex: 1, connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([ { name: "Update_someSheet", payload: { formData: { command: { data: "UPDATE_ONE", }, entityType: { data: "ROWS", }, queryFormat: { data: "ROWS", }, rowObjects: { data: "{{update_form.formData}}", }, sheetName: { data: "someSheet", }, sheetUrl: { data: "someTableUrl", }, smartSubstitution: { data: true, }, tableHeaderIndex: { data: "1", }, }, }, dynamicBindingPathList: [ { key: "formData.rowObjects.data", }, ], type: "update", }, ]); }); test("should not build update form data without write permissions ", () => { const expr = GSheets.build( { update: { value: "update_form.formData", }, totalRecord: false, }, { tableName: "someTableUrl", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "", sheetName: "someSheet", tableHeaderIndex: 1, connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); expect(expr).toEqual([]); }); test("should build insert form data correctly ", () => { const expr = GSheets.build( { create: { value: "insert_form.formData", }, totalRecord: false, }, { tableName: "someTableUrl", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "", sheetName: "someSheet", tableHeaderIndex: 1, connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([ { name: "Insert_someSheet", payload: { formData: { command: { data: "INSERT_ONE", }, entityType: { data: "ROWS", }, queryFormat: { data: "ROWS", }, rowObjects: { data: "{{insert_form.formData}}", }, sheetName: { data: "someSheet", }, sheetUrl: { data: "someTableUrl", }, smartSubstitution: { data: true, }, tableHeaderIndex: { data: "1", }, }, }, type: "create", dynamicBindingPathList: [ { key: "formData.rowObjects.data", }, ], }, ]); }); test("should not build insert form data without write permissions ", () => { const expr = GSheets.build( { create: { value: "insert_form.formData", }, totalRecord: false, }, { tableName: "someTableUrl", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "", sheetName: "someSheet", tableHeaderIndex: 1, connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); expect(expr).toEqual([]); }); });
7,722
0
petrpan-code/appsmithorg/appsmith/app/client/src/WidgetQueryGenerators
petrpan-code/appsmithorg/appsmith/app/client/src/WidgetQueryGenerators/MSSQL/index.test.ts
import { DatasourceConnectionMode } from "entities/Datasource"; import MSSQL from "."; describe("MSSQL WidgetQueryGenerator", () => { const initialValues = { actionConfiguration: { pluginSpecifiedTemplates: [{ value: true }], }, }; test("should build select form data correctly", () => { const expr = MSSQL.build( { select: { limit: "data_table.pageSize", where: 'data_table.searchText || ""', offset: "(data_table.pageNo - 1) * data_table.pageSize", orderBy: "data_table.sortOrder.column", sortOrder: "data_table.sortOrder.order || 'ASC'", }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "genres", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); const res = `SELECT * FROM someTable WHERE title LIKE '%{{data_table.searchText || \"\"}}%' ORDER BY {{data_table.sortOrder.column || 'genres'}} {{data_table.sortOrder.order || 'ASC' ? \"\" : \"DESC\"}} OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}} ROWS FETCH NEXT {{data_table.pageSize}} ROWS ONLY`; expect(expr).toEqual([ { name: "Select_someTable", type: "select", dynamicBindingPathList: [ { key: "body", }, ], payload: { pluginSpecifiedTemplates: [{ value: false }], body: res, }, }, ]); }); test("should build select form data correctly without read write permissions", () => { const expr = MSSQL.build( { select: { limit: "data_table.pageSize", where: 'data_table.searchText || ""', offset: "(data_table.pageNo - 1) * data_table.pageSize", orderBy: "data_table.sortOrder.column", sortOrder: "data_table.sortOrder.order || 'ASC'", }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "genres", connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); const res = `SELECT * FROM someTable WHERE title LIKE '%{{data_table.searchText || \"\"}}%' ORDER BY {{data_table.sortOrder.column || 'genres'}} {{data_table.sortOrder.order || 'ASC' ? \"\" : \"DESC\"}} OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}} ROWS FETCH NEXT {{data_table.pageSize}} ROWS ONLY`; expect(expr).toEqual([ { name: "Select_someTable", type: "select", dynamicBindingPathList: [ { key: "body", }, ], payload: { pluginSpecifiedTemplates: [{ value: false }], body: res, }, }, ]); }); test("should build select form data correctly without primary column", () => { const expr = MSSQL.build( { select: { limit: "data_table.pageSize", where: 'data_table.searchText || ""', offset: "(data_table.pageNo - 1) * data_table.pageSize", orderBy: "data_table.sortOrder.column", sortOrder: `data_table.sortOrder.order !== "desc"`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); const res = `SELECT * FROM someTable WHERE title LIKE '%{{data_table.searchText || \"\"}}%' {{data_table.sortOrder.column ? \"ORDER BY \" + data_table.sortOrder.column + \" \" + (data_table.sortOrder.order !== \"desc\" ? \"\" : \"DESC\") : \"\"}} OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}} ROWS FETCH NEXT {{data_table.pageSize}} ROWS ONLY`; expect(expr).toEqual([ { name: "Select_someTable", type: "select", dynamicBindingPathList: [ { key: "body", }, ], payload: { pluginSpecifiedTemplates: [{ value: false }], body: res, }, }, ]); }); test("should not build update form data without primary key ", () => { const expr = MSSQL.build( { update: { value: `update_form.fieldState'`, where: `"id" = {{data_table.selectedRow.id}}`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([]); }); test("should not build update form data without read write permissions", () => { const expr = MSSQL.build( { update: { value: `update_form.fieldState'`, where: `"id" = {{data_table.selectedRow.id}}`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "id", connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); expect(expr).toEqual([]); }); test("should build update form data correctly ", () => { const expr = MSSQL.build( { update: { value: `update_form.fieldState'`, where: `data_table.selectedRow`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "id", connectionMode: DatasourceConnectionMode.READ_WRITE, dataIdentifier: "id", }, initialValues, ); expect(expr).toEqual([ { name: "Update_someTable", type: "update", dynamicBindingPathList: [ { key: "body", }, ], payload: { body: "UPDATE someTable SET name= '{{update_form.fieldState'.name}}' WHERE id= '{{data_table.selectedRow.id}}';", pluginSpecifiedTemplates: [{ value: false }], }, }, ]); }); test("should not build insert form data without primary key ", () => { const expr = MSSQL.build( { create: { value: `update_form.fieldState`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([]); }); test("should not build insert form data without read write permissions", () => { const expr = MSSQL.build( { create: { value: `update_form.fieldState`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "id", connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); expect(expr).toEqual([]); }); test("should build insert form data correctly ", () => { const expr = MSSQL.build( { create: { value: `update_form.fieldState`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "id", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([ { name: "Insert_someTable", type: "create", dynamicBindingPathList: [ { key: "body", }, ], payload: { body: "INSERT INTO someTable (name) VALUES ('{{update_form.fieldState.name}}')", pluginSpecifiedTemplates: [{ value: false }], }, }, ]); }); });
7,724
0
petrpan-code/appsmithorg/appsmith/app/client/src/WidgetQueryGenerators
petrpan-code/appsmithorg/appsmith/app/client/src/WidgetQueryGenerators/MongoDB/index.test.ts
import { DatasourceConnectionMode } from "entities/Datasource"; import MongoDB from "."; describe("Mongo WidgetQueryGenerator", () => { const initialValues = { actionConfiguration: { formData: { command: { data: "FIND" }, aggregate: { limit: { data: "10" } }, delete: { limit: { data: "SINGLE" } }, updateMany: { limit: { data: "SINGLE" } }, smartSubstitution: { data: true }, find: { data: "" }, insert: { data: "" }, count: { data: "" }, }, }, }; test("should build select form data correctly", () => { const expr = MongoDB.build( { select: { limit: "data_table.pageSize", where: 'data_table.searchText||""', offset: "(data_table.pageNo - 1) * data_table.pageSize", orderBy: "data_table.sortOrder.column || 'genres'", sortOrder: 'data_table.sortOrder.order == "desc" ? -1 : 1', }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([ { type: "select", name: "Find_someTable", dynamicBindingPathList: [ { key: "formData.find.skip.data", }, { key: "formData.find.query.data", }, { key: "formData.find.sort.data", }, { key: "formData.find.limit.data", }, ], payload: { formData: { collection: { data: "someTable", }, smartSubstitution: { data: true }, aggregate: { limit: { data: "10" } }, command: { data: "FIND", }, find: { data: "", limit: { data: "{{data_table.pageSize}}", }, query: { data: `{{{ title: {$regex: data_table.searchText||"", '$options' : 'i'} }}}`, }, skip: { data: "{{(data_table.pageNo - 1) * data_table.pageSize}}", }, sort: { data: "{{ data_table.sortOrder.column || 'genres' ? { [data_table.sortOrder.column || 'genres']: data_table.sortOrder.order == \"desc\" ? -1 : 1 ? 1 : -1 } : {}}}", }, }, }, }, }, ]); }); test("should build select form data without write permissions", () => { const expr = MongoDB.build( { select: { limit: "data_table.pageSize", where: 'data_table.searchText||""', offset: "(data_table.pageNo - 1) * data_table.pageSize", orderBy: "data_table.sortOrder.column || 'genres'", sortOrder: 'data_table.sortOrder.order == "desc" ? -1 : 1', }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); expect(expr).toEqual([ { type: "select", name: "Find_someTable", dynamicBindingPathList: [ { key: "formData.find.skip.data", }, { key: "formData.find.query.data", }, { key: "formData.find.sort.data", }, { key: "formData.find.limit.data", }, ], payload: { formData: { collection: { data: "someTable", }, smartSubstitution: { data: true }, aggregate: { limit: { data: "10" } }, command: { data: "FIND", }, find: { data: "", limit: { data: "{{data_table.pageSize}}", }, query: { data: `{{{ title: {$regex: data_table.searchText||"", '$options' : 'i'} }}}`, }, skip: { data: "{{(data_table.pageNo - 1) * data_table.pageSize}}", }, sort: { data: "{{ data_table.sortOrder.column || 'genres' ? { [data_table.sortOrder.column || 'genres']: data_table.sortOrder.order == \"desc\" ? -1 : 1 ? 1 : -1 } : {}}}", }, }, }, }, }, ]); }); test("should build update form data correctly ", () => { const expr = MongoDB.build( { update: { value: "{rating : {$gte : 9}}", where: "{ $inc: { score: 1 } }", }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([ { name: "Update_someTable", type: "update", dynamicBindingPathList: [ { key: "formData.updateMany.query.data", }, { key: "formData.updateMany.update.data", }, ], payload: { formData: { collection: { data: "someTable", }, command: { data: "UPDATE", }, aggregate: { limit: { data: "10" } }, smartSubstitution: { data: true }, updateMany: { query: { data: "{_id: ObjectId('{{{ $inc: { score: 1 } }._id}}')}", }, limit: { data: "SINGLE" }, update: { data: '{{{$set: _.omit({rating : {$gte : 9}}, "_id")}}}', }, }, }, }, }, ]); }); test("should not build update form data without write permissions ", () => { const expr = MongoDB.build( { update: { value: "{rating : {$gte : 9}}", where: "{ $inc: { score: 1 } }", }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); expect(expr).toEqual([]); }); test("should build insert form data correctly ", () => { const expr = MongoDB.build( { create: { value: "insert_form.formData", }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([ { name: "Insert_someTable", type: "create", dynamicBindingPathList: [ { key: "formData.insert.documents.data", }, ], payload: { formData: { collection: { data: "someTable", }, aggregate: { limit: { data: "10" } }, smartSubstitution: { data: true }, command: { data: "INSERT", }, insert: { data: "", documents: { data: "{{insert_form.formData}}", }, }, }, }, }, ]); }); test("should not build insert form data without write permissions ", () => { const expr = MongoDB.build( { create: { value: "insert_form.formData", }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); expect(expr).toEqual([]); }); });
7,726
0
petrpan-code/appsmithorg/appsmith/app/client/src/WidgetQueryGenerators
petrpan-code/appsmithorg/appsmith/app/client/src/WidgetQueryGenerators/MySQL/index.test.ts
import { DatasourceConnectionMode } from "entities/Datasource"; import MySQl from "."; describe("MySQl WidgetQueryGenerator", () => { const initialValues = { actionConfiguration: { pluginSpecifiedTemplates: [{ value: true }], }, }; test("should build select form data correctly", () => { const expr = MySQl.build( { select: { limit: "data_table.pageSize", where: 'data_table.searchText || ""', offset: "(data_table.pageNo - 1) * data_table.pageSize", orderBy: "data_table.sortOrder.column", sortOrder: "data_table.sortOrder.order || 'ASC'", }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "genres", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); const res = `SELECT * FROM someTable WHERE title LIKE '%{{data_table.searchText || \"\"}}%' ORDER BY {{data_table.sortOrder.column || 'genres'}} {{data_table.sortOrder.order || 'ASC' ? \"\" : \"DESC\"}} LIMIT {{data_table.pageSize}} OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}}`; expect(expr).toEqual([ { name: "Select_someTable", type: "select", dynamicBindingPathList: [ { key: "body", }, ], payload: { pluginSpecifiedTemplates: [{ value: false }], body: res, }, }, ]); }); test("should build select form data correctly without read write permissions", () => { const expr = MySQl.build( { select: { limit: "data_table.pageSize", where: 'data_table.searchText || ""', offset: "(data_table.pageNo - 1) * data_table.pageSize", orderBy: "data_table.sortOrder.column", sortOrder: "data_table.sortOrder.order || 'ASC'", }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "genres", connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); const res = `SELECT * FROM someTable WHERE title LIKE '%{{data_table.searchText || \"\"}}%' ORDER BY {{data_table.sortOrder.column || 'genres'}} {{data_table.sortOrder.order || 'ASC' ? \"\" : \"DESC\"}} LIMIT {{data_table.pageSize}} OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}}`; expect(expr).toEqual([ { name: "Select_someTable", type: "select", dynamicBindingPathList: [ { key: "body", }, ], payload: { pluginSpecifiedTemplates: [{ value: false }], body: res, }, }, ]); }); test("should build select form data correctly without primary column", () => { const expr = MySQl.build( { select: { limit: "data_table.pageSize", where: 'data_table.searchText || ""', offset: "(data_table.pageNo - 1) * data_table.pageSize", orderBy: "data_table.sortOrder.column", sortOrder: `data_table.sortOrder.order !== "desc"`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); const res = `SELECT * FROM someTable WHERE title LIKE '%{{data_table.searchText || \"\"}}%' {{data_table.sortOrder.column ? \"ORDER BY \" + data_table.sortOrder.column + \" \" + (data_table.sortOrder.order !== \"desc\" ? \"\" : \"DESC\") : \"\"}} LIMIT {{data_table.pageSize}} OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}}`; expect(expr).toEqual([ { name: "Select_someTable", type: "select", dynamicBindingPathList: [ { key: "body", }, ], payload: { pluginSpecifiedTemplates: [{ value: false }], body: res, }, }, ]); }); test("should not build update form data without primary key ", () => { const expr = MySQl.build( { update: { value: `update_form.fieldState'`, where: `"id" = {{data_table.selectedRow.id}}`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([]); }); test("should not build update form data without read write", () => { const expr = MySQl.build( { update: { value: `update_form.fieldState'`, where: `"id" = {{data_table.selectedRow.id}}`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "id", connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); expect(expr).toEqual([]); }); test("should build update form data correctly ", () => { const expr = MySQl.build( { update: { value: `update_form.fieldState'`, where: `data_table.selectedRow`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "id", connectionMode: DatasourceConnectionMode.READ_WRITE, dataIdentifier: "id", }, initialValues, ); expect(expr).toEqual([ { name: "Update_someTable", type: "update", dynamicBindingPathList: [ { key: "body", }, ], payload: { body: "UPDATE someTable SET name= '{{update_form.fieldState'.name}}' WHERE id= '{{data_table.selectedRow.id}}';", pluginSpecifiedTemplates: [{ value: false }], }, }, ]); }); test("should not build insert form data without primary key ", () => { const expr = MySQl.build( { create: { value: `update_form.fieldState`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([]); }); test("should not build insert form data without read write permissions", () => { const expr = MySQl.build( { create: { value: `update_form.fieldState`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "id", connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); expect(expr).toEqual([]); }); test("should build insert form data correctly ", () => { const expr = MySQl.build( { create: { value: `update_form.fieldState`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "id", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([ { name: "Insert_someTable", type: "create", dynamicBindingPathList: [ { key: "body", }, ], payload: { body: "INSERT INTO someTable (name) VALUES ('{{update_form.fieldState.name}}')", pluginSpecifiedTemplates: [{ value: false }], }, }, ]); }); });
7,728
0
petrpan-code/appsmithorg/appsmith/app/client/src/WidgetQueryGenerators
petrpan-code/appsmithorg/appsmith/app/client/src/WidgetQueryGenerators/PostgreSQL/index.test.ts
import { DatasourceConnectionMode } from "entities/Datasource"; import PostgreSQL from "."; describe("PostgreSQL WidgetQueryGenerator", () => { const initialValues = { actionConfiguration: { pluginSpecifiedTemplates: [{ value: true }], }, }; test("should build select form data correctly", () => { const expr = PostgreSQL.build( { select: { limit: "data_table.pageSize", where: 'data_table.searchText || ""', offset: "(data_table.pageNo - 1) * data_table.pageSize", orderBy: "data_table.sortOrder.column", sortOrder: "data_table.sortOrder.order || 'ASC'", }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "genres", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); const res = `SELECT * FROM someTable WHERE \"title\" ilike '%{{data_table.searchText || \"\"}}%' ORDER BY \"{{data_table.sortOrder.column || 'genres'}}\" {{data_table.sortOrder.order || 'ASC' ? \"\" : \"DESC\"}} LIMIT {{data_table.pageSize}} OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}}`; expect(expr).toEqual([ { name: "Select_someTable", type: "select", dynamicBindingPathList: [ { key: "body", }, ], payload: { pluginSpecifiedTemplates: [{ value: false }], body: res, }, }, ]); }); test("should build select form data correctly without primary column", () => { const expr = PostgreSQL.build( { select: { limit: "data_table.pageSize", where: 'data_table.searchText || ""', offset: "(data_table.pageNo - 1) * data_table.pageSize", orderBy: "data_table.sortOrder.column", sortOrder: `data_table.sortOrder.order !== "desc"`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); const res = `SELECT * FROM someTable WHERE \"title\" ilike '%{{data_table.searchText || \"\"}}%' {{data_table.sortOrder.column ? "ORDER BY " + data_table.sortOrder.column + " " + (data_table.sortOrder.order !== "desc" ? "" : "DESC") : ""}} LIMIT {{data_table.pageSize}} OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}}`; expect(expr).toEqual([ { name: "Select_someTable", type: "select", dynamicBindingPathList: [ { key: "body", }, ], payload: { pluginSpecifiedTemplates: [{ value: false }], body: res, }, }, ]); }); test("should build select form data correctly without write permissions", () => { const expr = PostgreSQL.build( { select: { limit: "data_table.pageSize", where: 'data_table.searchText || ""', offset: "(data_table.pageNo - 1) * data_table.pageSize", orderBy: "data_table.sortOrder.column", sortOrder: "data_table.sortOrder.order || 'ASC'", }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "genres", connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); const res = `SELECT * FROM someTable WHERE \"title\" ilike '%{{data_table.searchText || \"\"}}%' ORDER BY \"{{data_table.sortOrder.column || 'genres'}}\" {{data_table.sortOrder.order || 'ASC' ? \"\" : \"DESC\"}} LIMIT {{data_table.pageSize}} OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}}`; expect(expr).toEqual([ { name: "Select_someTable", type: "select", dynamicBindingPathList: [ { key: "body", }, ], payload: { pluginSpecifiedTemplates: [{ value: false }], body: res, }, }, ]); }); test("should not build update form data without primary key ", () => { const expr = PostgreSQL.build( { update: { value: `update_form.fieldState'`, where: `"id" = {{data_table.selectedRow.id}}`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([]); }); test("should not build update form data without write permissions ", () => { const expr = PostgreSQL.build( { update: { value: `update_form.fieldState'`, where: `"id" = {{data_table.selectedRow.id}}`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "id", connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); expect(expr).toEqual([]); }); test("should build update form data correctly ", () => { const expr = PostgreSQL.build( { update: { value: `update_form.fieldState'`, where: `data_table.selectedRow`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "id", connectionMode: DatasourceConnectionMode.READ_WRITE, dataIdentifier: "id", }, initialValues, ); expect(expr).toEqual([ { name: "Update_someTable", type: "update", dynamicBindingPathList: [ { key: "body", }, ], payload: { body: 'UPDATE someTable SET "name"= \'{{update_form.fieldState\'.name}}\' WHERE "id"= {{data_table.selectedRow.id}};', pluginSpecifiedTemplates: [{ value: false }], }, }, ]); }); test("should not build insert form data without primary key ", () => { const expr = PostgreSQL.build( { create: { value: `update_form.fieldState`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([]); }); test("should not build insert form data without write permissions ", () => { const expr = PostgreSQL.build( { create: { value: `update_form.fieldState`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "id", connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); expect(expr).toEqual([]); }); test("should build insert form data correctly ", () => { const expr = PostgreSQL.build( { create: { value: `update_form.fieldState`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "id", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([ { name: "Insert_someTable", type: "create", dynamicBindingPathList: [ { key: "body", }, ], payload: { body: "INSERT INTO someTable (\"name\") VALUES ('{{update_form.fieldState.name}}')", pluginSpecifiedTemplates: [{ value: false }], }, }, ]); }); });
7,730
0
petrpan-code/appsmithorg/appsmith/app/client/src/WidgetQueryGenerators
petrpan-code/appsmithorg/appsmith/app/client/src/WidgetQueryGenerators/Snowflake/index.test.ts
import { DatasourceConnectionMode } from "entities/Datasource"; import Snowflake from "."; describe("Snowflake WidgetQueryGenerator", () => { const initialValues = { actionConfiguration: { pluginSpecifiedTemplates: [{ value: true }], }, }; test("should build select form data correctly", () => { const expr = Snowflake.build( { select: { limit: "data_table.pageSize", where: 'data_table.searchText || ""', offset: "(data_table.pageNo - 1) * data_table.pageSize", orderBy: "data_table.sortOrder.column", sortOrder: "data_table.sortOrder.order || 'ASC'", }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "genres", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); const res = `SELECT * FROM someTable WHERE title LIKE '%{{data_table.searchText || \"\"}}%' ORDER BY {{data_table.sortOrder.column || 'genres'}} {{data_table.sortOrder.order || 'ASC' ? \"\" : \"DESC\"}} LIMIT {{data_table.pageSize}} OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}}`; expect(expr).toEqual([ { name: "Select_someTable", type: "select", dynamicBindingPathList: [ { key: "body", }, ], payload: { pluginSpecifiedTemplates: [{ value: false }], body: res, }, }, ]); }); test("should build select form data correctly with read permissions", () => { const expr = Snowflake.build( { select: { limit: "data_table.pageSize", where: 'data_table.searchText || ""', offset: "(data_table.pageNo - 1) * data_table.pageSize", orderBy: "data_table.sortOrder.column", sortOrder: "data_table.sortOrder.order || 'ASC'", }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "genres", connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); const res = `SELECT * FROM someTable WHERE title LIKE '%{{data_table.searchText || \"\"}}%' ORDER BY {{data_table.sortOrder.column || 'genres'}} {{data_table.sortOrder.order || 'ASC' ? \"\" : \"DESC\"}} LIMIT {{data_table.pageSize}} OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}}`; expect(expr).toEqual([ { name: "Select_someTable", type: "select", dynamicBindingPathList: [ { key: "body", }, ], payload: { pluginSpecifiedTemplates: [{ value: false }], body: res, }, }, ]); }); test("should build select form data correctly without primary column", () => { const expr = Snowflake.build( { select: { limit: "data_table.pageSize", where: 'data_table.searchText || ""', offset: "(data_table.pageNo - 1) * data_table.pageSize", orderBy: "data_table.sortOrder.column", sortOrder: `data_table.sortOrder.order !== "desc"`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); const res = `SELECT * FROM someTable WHERE title LIKE '%{{data_table.searchText || \"\"}}%' {{data_table.sortOrder.column ? \"ORDER BY \" + data_table.sortOrder.column + \" \" + (data_table.sortOrder.order !== \"desc\" ? \"\" : \"DESC\") : \"\"}} LIMIT {{data_table.pageSize}} OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}}`; expect(expr).toEqual([ { name: "Select_someTable", type: "select", dynamicBindingPathList: [ { key: "body", }, ], payload: { pluginSpecifiedTemplates: [{ value: false }], body: res, }, }, ]); }); test("should not build update form data without primary key ", () => { const expr = Snowflake.build( { update: { value: `update_form.fieldState'`, where: `"id" = {{data_table.selectedRow.id}}`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([]); }); test("should not build update form data without read write ", () => { const expr = Snowflake.build( { update: { value: `update_form.fieldState'`, where: `"id" = {{data_table.selectedRow.id}}`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "id", connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); expect(expr).toEqual([]); }); test("should build update form data correctly ", () => { const expr = Snowflake.build( { update: { value: `update_form.fieldState'`, where: `data_table.selectedRow`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "id", connectionMode: DatasourceConnectionMode.READ_WRITE, dataIdentifier: "id", }, initialValues, ); expect(expr).toEqual([ { name: "Update_someTable", type: "update", dynamicBindingPathList: [ { key: "body", }, ], payload: { body: "UPDATE someTable SET name= '{{update_form.fieldState'.name}}' WHERE id= '{{data_table.selectedRow.id}}';", pluginSpecifiedTemplates: [{ value: false }], }, }, ]); }); test("should not build insert form data without primary key ", () => { const expr = Snowflake.build( { create: { value: `update_form.fieldState`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([]); }); test("should not build insert form data without read write permissions", () => { const expr = Snowflake.build( { create: { value: `update_form.fieldState`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "id", connectionMode: DatasourceConnectionMode.READ_ONLY, }, initialValues, ); expect(expr).toEqual([]); }); test("should build insert form data correctly ", () => { const expr = Snowflake.build( { create: { value: `update_form.fieldState`, }, totalRecord: false, }, { tableName: "someTable", datasourceId: "someId", // ignore columns aliases: [{ name: "someColumn1", alias: "someColumn1" }], widgetId: "someWidgetId", searchableColumn: "title", columns: [ { name: "id", type: "number", isSelected: true }, { name: "name", type: "number", isSelected: true }, ], primaryColumn: "id", connectionMode: DatasourceConnectionMode.READ_WRITE, }, initialValues, ); expect(expr).toEqual([ { name: "Insert_someTable", type: "create", dynamicBindingPathList: [ { key: "body", }, ], payload: { body: "INSERT INTO someTable (name) VALUES ('{{update_form.fieldState.name}}')", pluginSpecifiedTemplates: [{ value: false }], }, }, ]); }); });
9,344
0
petrpan-code/appsmithorg/appsmith/app/client/src/ce
petrpan-code/appsmithorg/appsmith/app/client/src/ce/api/ApiUtils.test.ts
import { apiRequestInterceptor, apiSuccessResponseInterceptor, apiFailureResponseInterceptor, axiosConnectionAbortedCode, } from "./ApiUtils"; import type { AxiosRequestConfig, AxiosResponse } from "axios"; import type { ActionExecutionResponse } from "api/ActionAPI"; import { createMessage, ERROR_0, SERVER_API_TIMEOUT_ERROR, } from "@appsmith/constants/messages"; import { ERROR_CODES } from "@appsmith/constants/ApiConstants"; import * as Sentry from "@sentry/react"; describe("axios api interceptors", () => { describe("Axios api request interceptor", () => { it("adds timer to the request object", () => { const request: AxiosRequestConfig = { url: "https://app.appsmith.com/v1/api/actions/execute", }; const interceptedRequest = apiRequestInterceptor(request); expect(interceptedRequest).toHaveProperty("timer"); }); }); describe("Axios api response success interceptor", () => { it("transforms an action execution response", () => { const response: AxiosResponse = { data: "Test data", headers: { "content-length": 123, "content-type": "application/json", }, config: { url: "https://app.appsmith.com/v1/api/actions/execute", // @ts-expect-error: type mismatch timer: 0, }, }; const interceptedResponse: ActionExecutionResponse = apiSuccessResponseInterceptor(response); expect(interceptedResponse).toHaveProperty("clientMeta"); expect(interceptedResponse.clientMeta).toHaveProperty("size"); expect(interceptedResponse.clientMeta.size).toBe(123); expect(interceptedResponse.clientMeta).toHaveProperty("duration"); }); it("just returns the response data for other requests", () => { const response: AxiosResponse = { data: "Test data", headers: { "content-type": "application/json", }, config: { url: "https://app.appsmith.com/v1/api/actions", //@ts-expect-error: type mismatch timer: 0, }, }; const interceptedResponse: ActionExecutionResponse = apiSuccessResponseInterceptor(response); expect(interceptedResponse).toBe("Test data"); }); }); describe("Api response failure interceptor", () => { beforeEach(() => { jest.restoreAllMocks(); }); it("checks for no internet errors", () => { jest.spyOn(navigator, "onLine", "get").mockReturnValue(false); const interceptedResponse = apiFailureResponseInterceptor({}); expect(interceptedResponse).rejects.toStrictEqual({ message: createMessage(ERROR_0), }); }); it.todo("handles axios cancel gracefully"); it("handles timeout errors", () => { const error = { code: axiosConnectionAbortedCode, message: "timeout of 10000ms exceeded", }; const interceptedResponse = apiFailureResponseInterceptor(error); expect(interceptedResponse).rejects.toStrictEqual({ message: createMessage(SERVER_API_TIMEOUT_ERROR), code: ERROR_CODES.REQUEST_TIMEOUT, }); }); it("checks for response meta", () => { const sentrySpy = jest.spyOn(Sentry, "captureException"); const response: AxiosResponse = { data: "Test data", headers: { "content-type": "application/json", }, config: { url: "https://app.appsmith.com/v1/api/user", //@ts-expect-error: type mismatch timer: 0, }, }; apiSuccessResponseInterceptor(response); expect(sentrySpy).toHaveBeenCalled(); const interceptedFailureResponse = apiFailureResponseInterceptor({ response, }); expect(interceptedFailureResponse).rejects.toStrictEqual("Test data"); expect(sentrySpy).toHaveBeenCalled(); }); }); });
9,370
0
petrpan-code/appsmithorg/appsmith/app/client/src/ce
petrpan-code/appsmithorg/appsmith/app/client/src/ce/constants/messages.test.ts
import { ARE_YOU_SURE, CANNOT_MERGE_DUE_TO_UNCOMMITTED_CHANGES, CANNOT_PULL_WITH_LOCAL_UNCOMMITTED_CHANGES, CHANGES_ONLY_MIGRATION, CHANGES_ONLY_USER, CHANGES_USER_AND_MIGRATION, COMMIT_AND_PUSH, COMMIT_CHANGES, COMMIT_TO, COMMITTING_AND_PUSHING_CHANGES, CONNECT_BTN_LABEL, CONNECT_GIT, CONNECT_GIT_BETA, CONNECT_TO_GIT, CONNECT_TO_GIT_SUBTITLE, CONTACT_SUPPORT, CONTACT_SUPPORT_TO_UPGRADE, COPIED_SSH_KEY, COPY_SSH_KEY, CREATE_NEW_BRANCH, createMessage, DEPLOY, DEPLOY_KEY_USAGE_GUIDE_MESSAGE, DISCARD_CHANGES, DISCARD_CHANGES_WARNING, DISCARD_SUCCESS, DISCARDING_AND_PULLING_CHANGES, DISCONNECT, REVOKE_CAUSE_APPLICATION_BREAK, REVOKE_EXISTING_REPOSITORIES_INFO, REVOKE_GIT, ERROR_GIT_AUTH_FAIL, ERROR_GIT_INVALID_REMOTE, ERROR_WHILE_PULLING_CHANGES, ERROR_WIDGET_COPY_NOT_ALLOWED, FETCH_GIT_STATUS, FETCH_MERGE_STATUS, FETCH_MERGE_STATUS_FAILURE, GENERATE_KEY, GIT_COMMIT_MESSAGE_PLACEHOLDER, GIT_CONFLICTING_INFO, GIT_CONNECTION, GIT_DISCONNECTION_SUBMENU, GIT_SETTINGS, GIT_UPSTREAM_CHANGES, GIT_USER_UPDATED_SUCCESSFULLY, IMPORT_APP_FROM_FILE_MESSAGE, IMPORT_APP_FROM_GIT_MESSAGE, IMPORT_FROM_GIT_REPOSITORY, IMPORTING_APP_FROM_GIT, INVALID_USER_DETAILS_MSG, IS_MERGING, MERGE, MERGE_CHANGES, MERGE_CONFLICT_ERROR, MERGED_SUCCESSFULLY, NO_MERGE_CONFLICT, NONE_REVERSIBLE_MESSAGE, PASTE_SSH_URL_INFO, PULL_CHANGES, REGENERATE_KEY_CONFIRM_MESSAGE, REGENERATE_SSH_KEY, REMOTE_URL, REMOTE_URL_INFO, REMOTE_URL_INPUT_PLACEHOLDER, REMOTE_URL_VIA, REPOSITORY_LIMIT_REACHED, REPOSITORY_LIMIT_REACHED_INFO, RETRY, REVOKE_EXISTING_REPOSITORIES, SELECT_BRANCH_TO_MERGE, SSH_KEY, SUBMIT, UPDATE_CONFIG, UPLOADING_APPLICATION, UPLOADING_JSON, USE_DEFAULT_CONFIGURATION, AUDIT_LOGS, INTRODUCING, AUDIT_LOGS_UPGRADE_PAGE_SUB_HEADING, SECURITY_AND_COMPLIANCE, SECURITY_AND_COMPLIANCE_DETAIL1, SECURITY_AND_COMPLIANCE_DETAIL2, DEBUGGING, DEBUGGING_DETAIL1, INCIDENT_MANAGEMENT, INCIDENT_MANAGEMENT_DETAIL1, AVAILABLE_ON_BUSINESS, EXCLUSIVE_TO_BUSINESS, } from "./messages"; describe("messages", () => { it("checks for ERROR_WIDGET_COPY_NOT_ALLOWED string", () => { expect(ERROR_WIDGET_COPY_NOT_ALLOWED()).toBe( "This selected widget cannot be copied.", ); }); }); describe("messages without input", () => { const expectedMessages = [ { key: "COMMIT_CHANGES", value: "Commit changes" }, { key: "COMMIT_TO", value: "Commit to", }, { key: "COMMIT_AND_PUSH", value: "Commit & push" }, { key: "PULL_CHANGES", value: "Pull changes", }, { key: "SSH_KEY", value: "SSH key" }, { key: "COPY_SSH_KEY", value: "Copy SSH key", }, { key: "REGENERATE_KEY_CONFIRM_MESSAGE", value: "This might cause the application to break. This key needs to be updated in your Git repository too!", }, { key: "DEPLOY_KEY_USAGE_GUIDE_MESSAGE", value: "Paste this key in your repository settings and give it write access.", }, { key: "COMMITTING_AND_PUSHING_CHANGES", value: "Committing and pushing changes...", }, { key: "IS_MERGING", value: "Merging changes..." }, { key: "MERGE_CHANGES", value: "Merge changes", }, { key: "SELECT_BRANCH_TO_MERGE", value: "Select branch to merge" }, { key: "CONNECT_GIT", value: "Connect Git", }, { key: "CONNECT_GIT_BETA", value: "Connect Git (Beta)" }, { key: "RETRY", value: "Retry", }, { key: "CREATE_NEW_BRANCH", value: "Create new branch" }, { key: "ERROR_WHILE_PULLING_CHANGES", value: "ERROR WHILE PULLING CHANGES", }, { key: "SUBMIT", value: "Submit" }, { key: "GIT_USER_UPDATED_SUCCESSFULLY", value: "Git user updated successfully", }, { key: "REMOTE_URL_INPUT_PLACEHOLDER", value: "[email protected]:user/repository.git", }, { key: "COPIED_SSH_KEY", value: "Copied SSH key" }, { key: "INVALID_USER_DETAILS_MSG", value: "Please enter valid user details", }, { key: "PASTE_SSH_URL_INFO", value: "Please enter a valid SSH URL of your repository", }, { key: "GENERATE_KEY", value: "Generate key" }, { key: "UPDATE_CONFIG", value: "Update config", }, { key: "CONNECT_BTN_LABEL", value: "Connect" }, { key: "FETCH_GIT_STATUS", value: "Fetching status...", }, { key: "FETCH_MERGE_STATUS", value: "Checking mergeability..." }, { key: "NO_MERGE_CONFLICT", value: "This branch has no conflicts with the base branch.", }, { key: "MERGE_CONFLICT_ERROR", value: "Merge conflicts found!" }, { key: "FETCH_MERGE_STATUS_FAILURE", value: "Unable to fetch merge status", }, { key: "GIT_UPSTREAM_CHANGES", value: "Looks like there are pending upstream changes. We will pull the changes and push them to your repository.", }, { key: "GIT_CONFLICTING_INFO", value: "Please resolve the merge conflicts manually on your repository.", }, { key: "CANNOT_PULL_WITH_LOCAL_UNCOMMITTED_CHANGES", value: "You have uncommitted changes. Please commit before pulling the remote changes.", }, { key: "CANNOT_MERGE_DUE_TO_UNCOMMITTED_CHANGES", value: "Your current branch has uncommitted changes. Please commit them before proceeding to merge.", }, { key: "REVOKE_EXISTING_REPOSITORIES", value: "Revoke existing repositories", }, { key: "REVOKE_EXISTING_REPOSITORIES_INFO", value: "To make space for newer repositories, you can remove existing repositories.", }, { key: "CONTACT_SUPPORT", value: "Contact support" }, { key: "REPOSITORY_LIMIT_REACHED", value: "Repository limit reached", }, { key: "REPOSITORY_LIMIT_REACHED_INFO", value: "Adding and using upto 3 repositories is free. To add more repositories, kindly upgrade.", }, { key: "NONE_REVERSIBLE_MESSAGE", value: "This action is non-reversible. Please proceed with caution.", }, { key: "CONTACT_SUPPORT_TO_UPGRADE", value: "Please contact support to upgrade. You can add unlimited private repositories in upgraded plan.", }, { key: "REVOKE_CAUSE_APPLICATION_BREAK", value: "Revoking your repository might cause the application to break.", }, { key: "REVOKE_GIT", value: "Revoke access" }, { key: "DISCONNECT", value: "Disconnect", }, { key: "GIT_DISCONNECTION_SUBMENU", value: "Git Connection > Disconnect" }, { key: "USE_DEFAULT_CONFIGURATION", value: "Use default configuration", }, { key: "GIT_COMMIT_MESSAGE_PLACEHOLDER", value: "Your commit message here", }, { key: "GIT_CONNECTION", value: "Git connection" }, { key: "DEPLOY", value: "Deploy" }, { key: "MERGE", value: "Merge", }, { key: "GIT_SETTINGS", value: "Git settings" }, { key: "CONNECT_TO_GIT", value: "Connect to Git repository" }, { key: "CONNECT_TO_GIT_SUBTITLE", value: "Checkout branches, make commits, and deploy your application", }, { key: "REMOTE_URL", value: "Remote URL" }, { key: "REMOTE_URL_INFO", value: `Create an empty Git repository and paste the remote URL here.`, }, { key: "REMOTE_URL_VIA", value: "Remote URL via" }, { key: "ERROR_GIT_AUTH_FAIL", value: "Please make sure that regenerated SSH key is added and has write access to the repository.", }, { key: "ERROR_GIT_INVALID_REMOTE", value: "Either the remote repository doesn't exist or is unreachable.", }, { key: "CHANGES_ONLY_USER", value: "Changes since last commit", }, { key: "CHANGES_ONLY_MIGRATION", value: "Appsmith update changes since last commit", }, { key: "CHANGES_USER_AND_MIGRATION", value: "Appsmith update and user changes since last commit", }, { key: "MERGED_SUCCESSFULLY", value: "Merged successfully" }, { key: "DISCARD_CHANGES_WARNING", value: "This action will replace your local changes with the latest remote version.", }, { key: "DISCARD_SUCCESS", value: "Discarded changes successfully.", }, { key: "DISCARDING_AND_PULLING_CHANGES", value: "Discarding and pulling changes...", }, { key: "ARE_YOU_SURE", value: "Are you sure?", }, { key: "DISCARD_CHANGES", value: "Discard & pull", }, { key: "IMPORTING_APP_FROM_GIT", value: "Importing application from Git", }, { key: "UPLOADING_JSON", value: "Uploading JSON file" }, { key: "UPLOADING_APPLICATION", value: "Uploading application", }, { key: "IMPORT_APP_FROM_FILE_MESSAGE", value: "Drag and drop your file or upload from your computer", }, { key: "IMPORT_APP_FROM_GIT_MESSAGE", value: "Import an application from its Git repository using its SSH URL", }, { key: "IMPORT_FROM_GIT_REPOSITORY", value: "Import from Git repository", }, ]; const functions = [ ARE_YOU_SURE, CANNOT_MERGE_DUE_TO_UNCOMMITTED_CHANGES, CANNOT_PULL_WITH_LOCAL_UNCOMMITTED_CHANGES, CHANGES_ONLY_MIGRATION, CHANGES_ONLY_USER, CHANGES_USER_AND_MIGRATION, COMMITTING_AND_PUSHING_CHANGES, COMMIT_AND_PUSH, COMMIT_CHANGES, COMMIT_TO, CONNECT_BTN_LABEL, CONNECT_GIT, CONNECT_GIT_BETA, CONNECT_TO_GIT, CONNECT_TO_GIT_SUBTITLE, CONTACT_SUPPORT, CONTACT_SUPPORT_TO_UPGRADE, COPIED_SSH_KEY, COPY_SSH_KEY, CREATE_NEW_BRANCH, DEPLOY, DEPLOY_KEY_USAGE_GUIDE_MESSAGE, DISCARDING_AND_PULLING_CHANGES, DISCARD_CHANGES, DISCARD_CHANGES_WARNING, DISCARD_SUCCESS, DISCONNECT, REVOKE_CAUSE_APPLICATION_BREAK, REVOKE_EXISTING_REPOSITORIES, REVOKE_EXISTING_REPOSITORIES_INFO, REVOKE_GIT, ERROR_GIT_AUTH_FAIL, ERROR_GIT_INVALID_REMOTE, ERROR_WHILE_PULLING_CHANGES, FETCH_GIT_STATUS, FETCH_MERGE_STATUS, FETCH_MERGE_STATUS_FAILURE, GENERATE_KEY, GIT_COMMIT_MESSAGE_PLACEHOLDER, GIT_CONFLICTING_INFO, GIT_CONNECTION, GIT_DISCONNECTION_SUBMENU, GIT_SETTINGS, GIT_UPSTREAM_CHANGES, GIT_USER_UPDATED_SUCCESSFULLY, IMPORTING_APP_FROM_GIT, INVALID_USER_DETAILS_MSG, IS_MERGING, MERGE, MERGE_CHANGES, MERGE_CONFLICT_ERROR, NONE_REVERSIBLE_MESSAGE, NO_MERGE_CONFLICT, MERGED_SUCCESSFULLY, PASTE_SSH_URL_INFO, PULL_CHANGES, REGENERATE_KEY_CONFIRM_MESSAGE, REMOTE_URL, REMOTE_URL_INFO, REMOTE_URL_INPUT_PLACEHOLDER, REMOTE_URL_VIA, REPOSITORY_LIMIT_REACHED, REPOSITORY_LIMIT_REACHED_INFO, RETRY, SELECT_BRANCH_TO_MERGE, SSH_KEY, SUBMIT, UPDATE_CONFIG, USE_DEFAULT_CONFIGURATION, UPLOADING_JSON, UPLOADING_APPLICATION, IMPORT_APP_FROM_FILE_MESSAGE, IMPORT_APP_FROM_GIT_MESSAGE, IMPORT_FROM_GIT_REPOSITORY, ]; functions.forEach((fn: () => string) => { it(`${fn.name} returns expected value`, () => { const actual = createMessage(fn); const found = expectedMessages.find((em) => em.key === fn.name); const expected = found && found.value; expect(actual).toEqual(expected); }); }); }); describe("messages with input values", () => { it("REGENERATE_SSH_KEY returns expected value", () => { expect(createMessage(REGENERATE_SSH_KEY)).toEqual( "Regenerate undefined undefined key", ); expect(createMessage(REGENERATE_SSH_KEY, "ECDSA", 256)).toEqual( "Regenerate ECDSA 256 key", ); }); }); describe("Audit logs messages", () => { it("without input strings match successfully", () => { const input = [ AUDIT_LOGS, AUDIT_LOGS_UPGRADE_PAGE_SUB_HEADING, SECURITY_AND_COMPLIANCE, SECURITY_AND_COMPLIANCE_DETAIL1, SECURITY_AND_COMPLIANCE_DETAIL2, DEBUGGING, DEBUGGING_DETAIL1, INCIDENT_MANAGEMENT, INCIDENT_MANAGEMENT_DETAIL1, AVAILABLE_ON_BUSINESS, ]; const expected = [ "Audit logs", "See a timestamped trail of events in your workspace. Filter by type of event, user, resource ID, and time. Drill down into each event to investigate further.", "Security & compliance", "Proactively derisk misconfigured permissions, roll back changes from a critical security event, and keep checks against your compliance policies.", "Exports to popular compliance tools coming soon", "Debugging", "Debug with a timeline of events filtered by user and resource ID, correlate them with end-user and app developer actions, and investigate back to the last known good state of your app.", "Incident management", "Go back in time from an incident to see who did what, correlate events with breaking changes, and run RCAs to remediate incidents for now and the future.", "Available on a business plan only", ]; const actual = input.map((f) => createMessage(f)); expect(actual).toEqual(expected); }); it("with input strings match successfully", () => { const input = [INTRODUCING, EXCLUSIVE_TO_BUSINESS]; const expected = [ `Introducing XYZ`, `The XYZ feature is exclusive to workspaces on the Business Edition`, ]; const actual = input.map((f) => createMessage(f, "XYZ")); expect(actual).toEqual(expected); }); });
9,377
0
petrpan-code/appsmithorg/appsmith/app/client/src/ce/entities
petrpan-code/appsmithorg/appsmith/app/client/src/ce/entities/DataTree/dataTreeJSAction.test.ts
import { PluginType } from "entities/Action"; import { generateDataTreeJSAction } from "./dataTreeJSAction"; import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; describe("generateDataTreeJSAction", () => { it("generate js collection in data tree", () => { const jsCollection: JSCollectionData = { isLoading: false, config: { id: "1234", applicationId: "app123", workspaceId: "workspace123", name: "JSObject2", pageId: "page123", pluginId: "plugin123", pluginType: PluginType.JS, actionIds: [], archivedActionIds: [], actions: [ { id: "abcd", applicationId: "app123", workspaceId: "workspace123", pluginType: 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, 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: "623973054d9aea1b062af87b", 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: {}, }, ], }, data: {}, }; const expectedData = { myVar1: [], myVar2: {}, ENTITY_TYPE: "JSACTION", 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}", myFun2: { data: {}, }, myFun1: { data: {}, }, actionId: "1234", }; const expectedConfig = { name: "JSObject2", actionId: "1234", pluginType: "JS", ENTITY_TYPE: "JSACTION", meta: { myFun2: { arguments: [], confirmBeforeExecute: false, }, myFun1: { arguments: [], confirmBeforeExecute: false, }, }, bindingPaths: { body: "SMART_SUBSTITUTE", myFun2: "SMART_SUBSTITUTE", myFun1: "SMART_SUBSTITUTE", myVar1: "SMART_SUBSTITUTE", myVar2: "SMART_SUBSTITUTE", }, dynamicBindingPathList: [ { key: "body", }, { key: "myVar1", }, { key: "myVar2", }, { key: "myFun2", }, { key: "myFun1", }, ], variables: ["myVar1", "myVar2"], dependencyMap: { body: ["myFun2", "myFun1"], }, reactivePaths: { body: "SMART_SUBSTITUTE", myFun1: "SMART_SUBSTITUTE", myFun2: "SMART_SUBSTITUTE", myVar1: "SMART_SUBSTITUTE", myVar2: "SMART_SUBSTITUTE", }, }; const resultData = generateDataTreeJSAction(jsCollection); expect(resultData.unEvalEntity).toStrictEqual(expectedData); expect(resultData.configEntity).toStrictEqual(expectedConfig); }); it("replaces 'this' in body with js object name", () => { const jsCollection: JSCollectionData = { isLoading: false, config: { id: "1234", applicationId: "app123", workspaceId: "workspace123", name: "JSObject2", pageId: "page123", pluginId: "plugin123", pluginType: PluginType.JS, actionIds: [], archivedActionIds: [], actions: [ { id: "abcd", applicationId: "app123", workspaceId: "workspace123", pluginType: 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, 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: "623973054d9aea1b062af87b", 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 return this.myFun2},\n\tmyFun2: async () => {\n\t\t//use async-await or promises\n\t}\n}", variables: [ { name: "myVar1", value: [], }, { name: "myVar2", value: {}, }, ], }, data: { abcd: { users: [{ id: 1, name: "John" }], }, }, }; const expectedData = { myVar1: [], myVar2: {}, body: "export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\tmyFun1: () => {\n\t\t//write code here\n\t return JSObject2.myFun2},\n\tmyFun2: async () => {\n\t\t//use async-await or promises\n\t}\n}", ENTITY_TYPE: "JSACTION", myFun2: { data: {}, }, myFun1: { data: {}, }, actionId: "1234", }; const expectedConfig = { ENTITY_TYPE: "JSACTION", actionId: "1234", meta: { myFun2: { arguments: [], confirmBeforeExecute: false, }, myFun1: { arguments: [], confirmBeforeExecute: false, }, }, bindingPaths: { body: "SMART_SUBSTITUTE", myFun2: "SMART_SUBSTITUTE", myFun1: "SMART_SUBSTITUTE", myVar1: "SMART_SUBSTITUTE", myVar2: "SMART_SUBSTITUTE", }, dynamicBindingPathList: [ { key: "body", }, { key: "myVar1", }, { key: "myVar2", }, { key: "myFun2", }, { key: "myFun1", }, ], variables: ["myVar1", "myVar2"], dependencyMap: { body: ["myFun2", "myFun1"], }, name: "JSObject2", pluginType: "JS", reactivePaths: { body: "SMART_SUBSTITUTE", myFun1: "SMART_SUBSTITUTE", myFun2: "SMART_SUBSTITUTE", myVar1: "SMART_SUBSTITUTE", myVar2: "SMART_SUBSTITUTE", }, }; const result = generateDataTreeJSAction(jsCollection); expect(result.unEvalEntity).toStrictEqual(expectedData); expect(result.configEntity).toStrictEqual(expectedConfig); }); });
9,384
0
petrpan-code/appsmithorg/appsmith/app/client/src/ce/entities
petrpan-code/appsmithorg/appsmith/app/client/src/ce/entities/URLRedirect/URLAssembly.test.ts
import urlBuilder, { URLBuilder, getQueryStringfromObject, } from "./URLAssembly"; import { APP_MODE } from "entities/App"; describe("URLBuilder", () => { beforeEach(() => { // Reset the URLBuilder instance before each test urlBuilder.resetURLParams(); }); it("should correctly set and use currentPageId in build function when currentPageId is set", () => { const testPageId = "testPageId"; const testMode = APP_MODE.EDIT; urlBuilder.setCurrentPageId(testPageId); const builderParams = { suffix: "testSuffix", branch: "testBranch", hash: "testHash", params: { param1: "value1", param2: "value2" }, persistExistingParams: true, }; URLBuilder.prototype.generateBasePath = jest.fn((pageId, mode) => { expect(pageId).toBe(testPageId); // Ensure the current page id is used expect(mode).toBe(testMode); return `mockedBasePath/${pageId}/${mode}`; }); const result = urlBuilder.build(builderParams, testMode); expect(URLBuilder.prototype.generateBasePath).toHaveBeenCalledWith( testPageId, testMode, ); expect(result).toEqual( "mockedBasePath/testPageId/EDIT/testSuffix?param1=value1&param2=value2&branch=testBranch#testHash", ); }); it("should correctly set and use pageId in build function when currentPageId is set to null", () => { const testPageId = "testPageId"; const testMode = APP_MODE.EDIT; // Set currentPageId to null urlBuilder.setCurrentPageId(null); const builderParams = { suffix: "testSuffix", branch: "testBranch", hash: "testHash", params: { param1: "value1", param2: "value2" }, pageId: testPageId, // Set the pageId to be used persistExistingParams: true, }; URLBuilder.prototype.generateBasePath = jest.fn((pageId, mode) => { expect(pageId).toBe(testPageId); // Ensure the passed pageId is used expect(mode).toBe(testMode); return `mockedBasePath/${pageId}/${mode}`; }); const result = urlBuilder.build(builderParams, testMode); expect(URLBuilder.prototype.generateBasePath).toHaveBeenCalledWith( testPageId, testMode, ); expect(result).toEqual( "mockedBasePath/testPageId/EDIT/testSuffix?param1=value1&param2=value2&branch=testBranch#testHash", ); }); it("should correctly set and use pageId in build function when currentPageId is set", () => { const currentPageId = "currentPageId"; const testPageId = "testPageId"; const testMode = APP_MODE.EDIT; urlBuilder.setCurrentPageId(currentPageId); const builderParams = { suffix: "testSuffix", branch: "testBranch", hash: "testHash", params: { param1: "value1", param2: "value2" }, pageId: testPageId, // This should override the current page id persistExistingParams: true, }; URLBuilder.prototype.generateBasePath = jest.fn((pageId, mode) => { return `mockedBasePath/${pageId}/${mode}`; }); const result = urlBuilder.build(builderParams, testMode); expect(URLBuilder.prototype.generateBasePath).toHaveBeenCalledWith( testPageId, testMode, ); expect(result).toEqual( "mockedBasePath/testPageId/EDIT/testSuffix?param1=value1&param2=value2&branch=testBranch#testHash", ); }); it("should throw an error when pageId is missing", () => { urlBuilder.setCurrentPageId(null); expect(() => { urlBuilder.build({}, APP_MODE.EDIT); }).toThrow(URIError); }); }); describe(".getQueryStringfromObject", () => { const cases = [ { index: 0, input: { id: 0, a: "b&c ltd" }, expected: "?id=0&a=b%26c%20ltd", }, { index: 1, input: {}, expected: "" }, { index: 2, input: { rando: "রিমিল" }, expected: "?rando=%E0%A6%B0%E0%A6%BF%E0%A6%AE%E0%A6%BF%E0%A6%B2", }, { index: 3, input: { a1: "1234*&^%~`<>:';,./?" }, expected: "?a1=1234*%26%5E%25~%60%3C%3E%3A'%3B%2C.%2F%3F", }, { index: 4, input: { isSignedIn: false }, expected: "?isSignedIn=false" }, ]; test.each(cases.map((x) => [x.index, x.input, x.expected]))( "test case %d", (_, input, expected) => { const result = getQueryStringfromObject(input as any); expect(result).toStrictEqual(expected); }, ); });
9,416
0
petrpan-code/appsmithorg/appsmith/app/client/src/ce/pages/Editor
petrpan-code/appsmithorg/appsmith/app/client/src/ce/pages/Editor/Explorer/helpers.test.ts
import { getActionIdFromURL, getJSCollectionIdFromURL, } from "@appsmith/pages/Editor/Explorer/helpers"; describe("getActionIdFromUrl", () => { it("getsApiId", () => { window.history.pushState( {}, "Api", "/app/applicationSlugName/pageSlugName-pageId/edit/api/apiId", ); const response = getActionIdFromURL(); expect(response).toBe("apiId"); }); it("getsQueryId", () => { window.history.pushState( {}, "Query", "/app/applicationSlugName/pageSlugName-pageId/edit/queries/queryId", ); const response = getActionIdFromURL(); expect(response).toBe("queryId"); }); it("getsSaaSActionId", () => { window.history.pushState( {}, "Query", "/app/applicationSlugName/pageSlugName-pageId/edit/saas/:pluginPackageName/api/saasActionId", ); const response = getActionIdFromURL(); expect(response).toBe("saasActionId"); }); }); describe("getJSCollectionIdFromURL", () => { it("returns collectionId from path", () => { window.history.pushState( {}, "Query", "/applications/appId/pages/pageId/edit/jsObjects/collectionId", ); const response = getJSCollectionIdFromURL(); expect(response).toBe("collectionId"); }); it("returns undefined", () => { window.history.pushState( {}, "Query", "/applications/appId/pages/pageId/edit/jsObjects", ); const response = getJSCollectionIdFromURL(); expect(response).toBe(undefined); }); });
9,494
0
petrpan-code/appsmithorg/appsmith/app/client/src/ce/utils
petrpan-code/appsmithorg/appsmith/app/client/src/ce/utils/autocomplete/EntityDefinitions.test.ts
import { PluginType } from "entities/Action"; import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; import { getPropsForJSActionEntity } from "@appsmith/utils/autocomplete/EntityDefinitions"; const jsObject: JSCollectionData = { isLoading: false, config: { id: "1234", applicationId: "app123", workspaceId: "workspace123", name: "JSObject3", pageId: "page123", pluginId: "plugin123", pluginType: PluginType.JS, actionIds: [], archivedActionIds: [], actions: [ { id: "fun1", applicationId: "app123", workspaceId: "workspace123", pluginType: "JS", pluginId: "plugin123", name: "myFun1", fullyQualifiedName: "JSObject3.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: [], isAsync: false, }, 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: "JSObject3.myFun1", }, { id: "fun2", applicationId: "app123", workspaceId: "workspace123", pluginType: PluginType.JS, pluginId: "plugin123", name: "myFun2", fullyQualifiedName: "JSObject3.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: encodeParamsToggle does not exists on JSAction encodeParamsToggle: true, body: "async () => {\n\t\t//use async-await or promises\n\t}", jsArguments: [], isAsync: true, }, 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: "JSObject3.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: {}, }, ], }, data: { fun1: {}, fun2: [], }, isExecuting: {}, }; describe("getPropsForJSActionEntity", () => { it("get properties from js collection to show bindings", () => { const expectedProperties = { "myFun1()": "Function", "myFun2()": "Function", myVar1: [], myVar2: {}, "myFun1.data": {}, "myFun2.data": [], }; const result = getPropsForJSActionEntity(jsObject); expect(expectedProperties).toStrictEqual(result); }); });
9,501
0
petrpan-code/appsmithorg/appsmith/app/client/src/ce/workers
petrpan-code/appsmithorg/appsmith/app/client/src/ce/workers/Evaluation/evaluationUtils.test.ts
import type { DependencyMap, EvaluationError } from "utils/DynamicBindingUtils"; import { PropertyEvaluationErrorType } from "utils/DynamicBindingUtils"; import { RenderModes } from "constants/WidgetConstants"; import { ValidationTypes } from "constants/WidgetValidation"; import type { WidgetEntity, WidgetEntityConfig, PrivateWidgets, JSActionEntity, } from "@appsmith/entities/DataTree/types"; import { ENTITY_TYPE_VALUE, EvaluationSubstitutionType, } from "entities/DataTree/dataTreeFactory"; import type { ConfigTree, DataTreeEntity, DataTree, } from "entities/DataTree/dataTreeTypes"; import type { DataTreeDiff } from "@appsmith/workers/Evaluation/evaluationUtils"; import { addErrorToEntityProperty, convertJSFunctionsToString, DataTreeDiffEvent, getAllPaths, getAllPrivateWidgetsInDataTree, getDataTreeWithoutPrivateWidgets, isPrivateEntityPath, makeParentsDependOnChildren, translateDiffEventToDataTreeDiffEvent, } from "@appsmith/workers/Evaluation/evaluationUtils"; import { warn as logWarn } from "loglevel"; import type { Diff } from "deep-diff"; import _, { flatten, set } from "lodash"; import { overrideWidgetProperties, findDatatype, } from "@appsmith/workers/Evaluation/evaluationUtils"; import type { EvalMetaUpdates } from "@appsmith/workers/common/DataTreeEvaluator/types"; import { generateDataTreeWidget } from "entities/DataTree/dataTreeWidget"; import TableWidget from "widgets/TableWidget"; import InputWidget from "widgets/InputWidgetV2"; import DataTreeEvaluator from "workers/common/DataTreeEvaluator"; import { Severity } from "entities/AppsmithConsole"; import { PluginType } from "entities/Action"; import { registerWidgets } from "WidgetProvider/factory/registrationHelper"; // to check if logWarn was called. // use jest.unmock, if the mock needs to be removed. jest.mock("loglevel"); const BASE_WIDGET: WidgetEntity = { widgetId: "randomID", widgetName: "randomWidgetName", bottomRow: 0, isLoading: false, leftColumn: 0, parentColumnSpace: 0, parentRowSpace: 0, renderMode: RenderModes.CANVAS, rightColumn: 0, topRow: 0, type: "SKELETON_WIDGET", parentId: "0", version: 1, ENTITY_TYPE: ENTITY_TYPE_VALUE.WIDGET, meta: {}, }; const BASE_WIDGET_CONFIG: WidgetEntityConfig = { logBlackList: {}, widgetId: "randomID", type: "SKELETON_WIDGET", bindingPaths: {}, reactivePaths: {}, triggerPaths: {}, validationPaths: {}, ENTITY_TYPE: ENTITY_TYPE_VALUE.WIDGET, privateWidgets: {}, propertyOverrideDependency: {}, overridingPropertyPaths: {}, defaultMetaProps: [], }; const testDataTree: Record<string, WidgetEntity> = { Text1: { ...BASE_WIDGET, widgetName: "Text1", text: "Label", type: "TEXT_WIDGET", }, Text2: { ...BASE_WIDGET, widgetName: "Text2", text: "{{Text1.text}}", type: "TEXT_WIDGET", }, Text3: { ...BASE_WIDGET, widgetName: "Text3", text: "{{Text1.text}}", type: "TEXT_WIDGET", }, Text4: { ...BASE_WIDGET, widgetName: "Text4", text: "{{Text1.text}}", type: "TEXT_WIDGET", }, List1: { ...BASE_WIDGET, }, List2: { ...BASE_WIDGET, }, Button1: { ...BASE_WIDGET, text: "undefined", __evaluation__: { errors: { text: [], }, }, }, }; const testConfigTree: ConfigTree = { Text1: { ...BASE_WIDGET_CONFIG, type: "TEXT_WIDGET", reactivePaths: { text: EvaluationSubstitutionType.TEMPLATE, }, validationPaths: { text: { type: ValidationTypes.TEXT }, }, }, Text2: { ...BASE_WIDGET_CONFIG, type: "TEXT_WIDGET", dynamicBindingPathList: [{ key: "text" }], reactivePaths: { text: EvaluationSubstitutionType.TEMPLATE, }, validationPaths: { text: { type: ValidationTypes.TEXT }, }, }, Text3: { ...BASE_WIDGET_CONFIG, dynamicBindingPathList: [{ key: "text" }], reactivePaths: { text: EvaluationSubstitutionType.TEMPLATE, }, validationPaths: { text: { type: ValidationTypes.TEXT }, }, type: "TEXT_WIDGET", }, Text4: { ...BASE_WIDGET_CONFIG, dynamicBindingPathList: [{ key: "text" }], type: "TEXT_WIDGET", reactivePaths: { text: EvaluationSubstitutionType.TEMPLATE, }, validationPaths: { text: { type: ValidationTypes.TEXT }, }, }, List1: { ...BASE_WIDGET_CONFIG, privateWidgets: { Text2: true, }, }, List2: { ...BASE_WIDGET_CONFIG, privateWidgets: { Text3: true, }, }, Button1: { ...BASE_WIDGET_CONFIG, }, }; describe("1. Correctly handle paths", () => { it("1. getsAllPaths", () => { const myTree = { WidgetName: { 1: "yo", name: "WidgetName", objectProperty: { childObjectProperty: [ "1", 1, { key: "value", 2: 1, }, ["1", "2"], ], }, stringProperty: new String("Hello"), }, }; const result = { WidgetName: true, "WidgetName.1": true, "WidgetName.name": true, "WidgetName.objectProperty": true, "WidgetName.objectProperty.childObjectProperty": true, "WidgetName.objectProperty.childObjectProperty[0]": true, "WidgetName.objectProperty.childObjectProperty[1]": true, "WidgetName.objectProperty.childObjectProperty[2]": true, "WidgetName.objectProperty.childObjectProperty[2].key": true, "WidgetName.objectProperty.childObjectProperty[2].2": true, "WidgetName.objectProperty.childObjectProperty[3]": true, "WidgetName.objectProperty.childObjectProperty[3][0]": true, "WidgetName.objectProperty.childObjectProperty[3][1]": true, "WidgetName.stringProperty": true, }; const actual = getAllPaths(myTree); expect(actual).toStrictEqual(result); }); }); describe("2. privateWidgets", () => { it("1. correctly checks if path is a PrivateEntityPath", () => { const privateWidgets: PrivateWidgets = { Button1: true, Image1: true, Button2: true, Image2: true, }; expect( isPrivateEntityPath(privateWidgets, "List1.template.Button1.text"), ).toBeFalsy(); expect(isPrivateEntityPath(privateWidgets, "Button1.text")).toBeTruthy(); expect( isPrivateEntityPath(privateWidgets, "List2.template.Image2.data"), ).toBeFalsy(); expect(isPrivateEntityPath(privateWidgets, "Image2.data")).toBeTruthy(); }); it("2. Returns list of all privateWidgets", () => { const expectedPrivateWidgetsList = { Text2: true, Text3: true, }; const actualPrivateWidgetsList = getAllPrivateWidgetsInDataTree(testConfigTree); expect(expectedPrivateWidgetsList).toStrictEqual(actualPrivateWidgetsList); }); it("3. Returns data tree without privateWidgets", () => { const expectedDataTreeWithoutPrivateWidgets: Record<string, WidgetEntity> = { Text1: { ...BASE_WIDGET, widgetName: "Text1", text: "Label", type: "TEXT_WIDGET", }, Text4: { ...BASE_WIDGET, widgetName: "Text4", text: "{{Text1.text}}", type: "TEXT_WIDGET", }, List1: { ...BASE_WIDGET, }, List2: { ...BASE_WIDGET, }, Button1: { ...BASE_WIDGET, text: "undefined", __evaluation__: { errors: { text: [], }, }, }, }; const actualDataTreeWithoutPrivateWidgets = getDataTreeWithoutPrivateWidgets(testDataTree, testConfigTree); expect(expectedDataTreeWithoutPrivateWidgets).toStrictEqual( actualDataTreeWithoutPrivateWidgets, ); }); }); describe("3. makeParentsDependOnChildren", () => { it("1. makes parent properties depend on child properties", () => { let depMap: DependencyMap = { Widget1: [], "Widget1.defaultText": [], "Widget1.defaultText.abc": [], }; const allkeys: Record<string, true> = { Widget1: true, "Widget1.defaultText": true, "Widget1.defaultText.abc": true, }; depMap = makeParentsDependOnChildren(depMap, allkeys); expect(depMap).toStrictEqual({ Widget1: ["Widget1.defaultText"], "Widget1.defaultText": ["Widget1.defaultText.abc"], "Widget1.defaultText.abc": [], }); }); it("2. logs warning for child properties not listed in allKeys", () => { const depMap: DependencyMap = { Widget1: [], "Widget1.defaultText": [], }; const allkeys: Record<string, true> = { Widget1: true, }; makeParentsDependOnChildren(depMap, allkeys); expect(logWarn).toBeCalledWith( "makeParentsDependOnChild - Widget1.defaultText is not present in dataTree.", "This might result in a cyclic dependency.", ); }); }); describe("4. translateDiffEvent", () => { it("1. noop when diff path does not exist", () => { const noDiffPath: Diff<any, any> = { kind: "E", lhs: undefined, rhs: undefined, }; const result = translateDiffEventToDataTreeDiffEvent(noDiffPath, {}); expect(result).toStrictEqual({ payload: { propertyPath: "", value: "", }, event: DataTreeDiffEvent.NOOP, }); }); it("2. translates new and delete events", () => { const diffs: Diff<any, any>[] = [ { kind: "N", path: ["Widget1"], rhs: {}, }, { kind: "N", path: ["Widget1", "name"], rhs: "Widget1", }, { kind: "D", path: ["Widget1"], lhs: {}, }, { kind: "D", path: ["Widget1", "name"], lhs: "Widget1", }, { kind: "E", path: ["Widget2", "name"], rhs: "test", lhs: "test2", }, ]; const expectedTranslations: DataTreeDiff[] = [ { payload: { propertyPath: "Widget1", }, event: DataTreeDiffEvent.NEW, }, { payload: { propertyPath: "Widget1.name", }, event: DataTreeDiffEvent.NEW, }, { payload: { propertyPath: "Widget1", }, event: DataTreeDiffEvent.DELETE, }, { payload: { propertyPath: "Widget1.name", }, event: DataTreeDiffEvent.DELETE, }, { payload: { propertyPath: "Widget2.name", value: "", }, event: DataTreeDiffEvent.NOOP, }, ]; const actualTranslations = flatten( diffs.map((diff) => translateDiffEventToDataTreeDiffEvent(diff, {})), ); expect(expectedTranslations).toStrictEqual(actualTranslations); }); it("3. properly categorises the edit events", () => { const diffs: Diff<any, any>[] = [ { kind: "E", path: ["Widget2", "name"], rhs: "test", lhs: "test2", }, ]; const expectedTranslations: DataTreeDiff[] = [ { payload: { propertyPath: "Widget2.name", value: "", }, event: DataTreeDiffEvent.NOOP, }, ]; const actualTranslations = flatten( diffs.map((diff) => translateDiffEventToDataTreeDiffEvent(diff, {})), ); expect(expectedTranslations).toStrictEqual(actualTranslations); }); it("4. handles JsObject function renaming", () => { // cyclic dependency case const lhs = new String("() => {}"); _.set(lhs, "data", {}); const diffs: Diff<any, any>[] = [ { kind: "E", path: ["JsObject", "myFun1"], rhs: "() => {}", lhs, }, ]; const expectedTranslations: DataTreeDiff[] = [ { event: DataTreeDiffEvent.EDIT, payload: { propertyPath: "JsObject.myFun1", value: "() => {}", }, }, ]; const actualTranslations = flatten( diffs.map((diff) => translateDiffEventToDataTreeDiffEvent(diff, { JsObject: { ENTITY_TYPE: ENTITY_TYPE_VALUE.JSACTION, } as unknown as DataTreeEntity, }), ), ); expect(expectedTranslations).toStrictEqual(actualTranslations); }); it("5. lists array accessors when object is replaced by an array", () => { const diffs: Diff<any, any>[] = [ { kind: "E", path: ["Api1", "data"], lhs: {}, rhs: [{ id: 1 }, { id: 2 }], }, ]; const expectedTranslations: DataTreeDiff[] = [ { payload: { propertyPath: "Api1.data[0]", }, event: DataTreeDiffEvent.NEW, }, { payload: { propertyPath: "Api1.data[1]", }, event: DataTreeDiffEvent.NEW, }, ]; const actualTranslations = flatten( diffs.map((diff) => translateDiffEventToDataTreeDiffEvent(diff, {})), ); expect(expectedTranslations).toStrictEqual(actualTranslations); }); it("6. lists array accessors when array is replaced by an object", () => { const diffs: Diff<any, any>[] = [ { kind: "E", path: ["Api1", "data"], lhs: [{ id: 1 }, { id: 2 }], rhs: {}, }, ]; const expectedTranslations: DataTreeDiff[] = [ { payload: { propertyPath: "Api1.data[0]", }, event: DataTreeDiffEvent.DELETE, }, { payload: { propertyPath: "Api1.data[1]", }, event: DataTreeDiffEvent.DELETE, }, ]; const actualTranslations = flatten( diffs.map((diff) => translateDiffEventToDataTreeDiffEvent(diff, {})), ); expect(expectedTranslations).toStrictEqual(actualTranslations); }); it("7. deletes member expressions when Array changes to string", () => { const diffs: Diff<any, any>[] = [ { kind: "E", path: ["Api1", "data"], lhs: [{ id: "{{a}}" }, { id: "{{a}}" }], rhs: `{ id: "{{a}}" }, { id: "{{a}}" }`, }, ]; const expectedTranslations: DataTreeDiff[] = [ { payload: { propertyPath: "Api1.data", value: `{ id: "{{a}}" }, { id: "{{a}}" }`, }, event: DataTreeDiffEvent.EDIT, }, { payload: { propertyPath: "Api1.data[0]", }, event: DataTreeDiffEvent.DELETE, }, { payload: { propertyPath: "Api1.data[1]", }, event: DataTreeDiffEvent.DELETE, }, ]; const actualTranslations = flatten( diffs.map((diff) => translateDiffEventToDataTreeDiffEvent(diff, {})), ); expect(expectedTranslations).toEqual(actualTranslations); }); }); describe("5. overrideWidgetProperties", () => { beforeAll(() => { registerWidgets([TableWidget, InputWidget]); }); describe("1. Input widget ", () => { const currentTree: DataTree = {}; const configTree: ConfigTree = {}; beforeAll(() => { const inputWidgetDataTree = generateDataTreeWidget( { type: InputWidget.type, widgetId: "egwwwfgab", widgetName: "Input1", children: [], bottomRow: 0, isLoading: false, parentColumnSpace: 0, parentRowSpace: 0, version: 1, leftColumn: 0, renderMode: RenderModes.CANVAS, rightColumn: 0, topRow: 0, }, {}, new Set(), ); currentTree["Input1"] = inputWidgetDataTree.unEvalEntity; configTree["Input1"] = inputWidgetDataTree.configEntity; }); // When default text is re-evaluated it will override values of meta.text and text in InputWidget it("1. defaultText updating meta.text and text", () => { const widgetEntity = currentTree.Input1 as WidgetEntity; const evalMetaUpdates: EvalMetaUpdates = []; const overwriteObj = overrideWidgetProperties({ entity: widgetEntity, propertyPath: "defaultText", value: "abcde", currentTree, configTree, evalMetaUpdates, fullPropertyPath: "Input1.defaultText", isNewWidget: false, }); expect(overwriteObj).toStrictEqual(undefined); expect(evalMetaUpdates).toStrictEqual([ { widgetId: widgetEntity.widgetId, metaPropertyPath: ["inputText"], value: "abcde", }, { widgetId: widgetEntity.widgetId, metaPropertyPath: ["text"], value: "abcde", }, ]); expect(widgetEntity.meta).toStrictEqual({ text: "abcde", inputText: "abcde", }); }); // When meta.text is re-evaluated it will override values text in InputWidget it("2. meta.text updating text", () => { const widgetEntity = currentTree.Input1 as WidgetEntity; const evalMetaUpdates: EvalMetaUpdates = []; const overwriteObj = overrideWidgetProperties({ entity: widgetEntity, propertyPath: "meta.text", value: "abcdefg", currentTree, configTree, evalMetaUpdates, fullPropertyPath: "Input1.meta.text", isNewWidget: false, }); expect(overwriteObj).toStrictEqual(undefined); expect(evalMetaUpdates).toStrictEqual([]); expect(widgetEntity.text).toStrictEqual("abcdefg"); }); }); describe("2. Table widget ", () => { const currentTree: DataTree = {}; const configTree: ConfigTree = {}; beforeAll(() => { const tableWidgetDataTree = generateDataTreeWidget( { type: TableWidget.type, widgetId: "random", widgetName: "Table1", children: [], bottomRow: 0, isLoading: false, parentColumnSpace: 0, parentRowSpace: 0, version: 1, leftColumn: 0, renderMode: RenderModes.CANVAS, rightColumn: 0, topRow: 0, }, {}, new Set(), ); currentTree["Table1"] = tableWidgetDataTree.unEvalEntity; configTree["Table1"] = tableWidgetDataTree.configEntity; }); // When default defaultSelectedRow is re-evaluated it will override values of meta.selectedRowIndices, selectedRowIndices, meta.selectedRowIndex & selectedRowIndex. it("1. On change of defaultSelectedRow ", () => { const widgetEntity = currentTree.Table1 as WidgetEntity; const evalMetaUpdates: EvalMetaUpdates = []; const overwriteObj = overrideWidgetProperties({ entity: widgetEntity, propertyPath: "defaultSelectedRow", value: [0, 1], currentTree, configTree, evalMetaUpdates, fullPropertyPath: "Table1.defaultSelectedRow", isNewWidget: false, }); expect(overwriteObj).toStrictEqual(undefined); expect(evalMetaUpdates).toStrictEqual([ { widgetId: widgetEntity.widgetId, metaPropertyPath: ["selectedRowIndex"], value: [0, 1], }, { widgetId: widgetEntity.widgetId, metaPropertyPath: ["selectedRowIndices"], value: [0, 1], }, ]); expect(widgetEntity.meta.selectedRowIndex).toStrictEqual([0, 1]); expect(widgetEntity.meta.selectedRowIndices).toStrictEqual([0, 1]); }); // When meta.selectedRowIndex is re-evaluated it will override values selectedRowIndex it("2. meta.selectedRowIndex updating selectedRowIndex", () => { const widgetEntity = currentTree.Table1 as WidgetEntity; const evalMetaUpdates: EvalMetaUpdates = []; const overwriteObj = overrideWidgetProperties({ entity: widgetEntity, propertyPath: "meta.selectedRowIndex", value: 0, currentTree, configTree, evalMetaUpdates, fullPropertyPath: "Table1.meta.selectedRowIndex", isNewWidget: false, }); expect(overwriteObj).toStrictEqual(undefined); expect(evalMetaUpdates).toStrictEqual([]); expect(widgetEntity.selectedRowIndex).toStrictEqual(0); }); }); }); //A set of test cases to evaluate the logic for finding a given value's datatype describe("6. Evaluated Datatype of a given value", () => { it("1. Numeric datatypes", () => { expect(findDatatype(37)).toBe("number"); expect(findDatatype(3.14)).toBe("number"); expect(findDatatype(Math.LN2)).toBe("number"); expect(findDatatype(Infinity)).toBe("number"); expect(findDatatype(Number(1))).toBe("number"); expect(findDatatype(new Number(1))).toBe("number"); expect(findDatatype("1")).not.toBe("number"); }); it("2. String datatypes", () => { expect(findDatatype("")).toBe("string"); expect(findDatatype("bla")).toBe("string"); expect(findDatatype(String("abc"))).toBe("string"); expect(findDatatype(new String("abc"))).toBe("string"); expect(findDatatype(parseInt("1"))).not.toBe("string"); }); it("3. Boolean datatypes", () => { expect(findDatatype(true)).toBe("boolean"); expect(findDatatype(false)).toBe("boolean"); expect(findDatatype(Boolean(true))).toBe("boolean"); expect(findDatatype(Boolean(false))).toBe("boolean"); expect(findDatatype(new Boolean(false))).toBe("boolean"); expect(findDatatype("true")).not.toBe("boolean"); }); it("4. Objects datatypes", () => { expect(findDatatype(null)).toBe("null"); expect(findDatatype(undefined)).toBe("undefined"); let tempDecVar; expect(findDatatype(tempDecVar)).toBe("undefined"); expect(findDatatype({ a: 1 })).toBe("object"); expect(findDatatype({})).toBe("object"); expect(findDatatype(new Date())).toBe("date"); const func = function () { return "hello world"; }; expect(findDatatype(func)).toBe("function"); expect(findDatatype(Math.sin)).toBe("function"); expect(findDatatype(/test/i)).toBe("regexp"); }); it("5. Array datatypes", () => { expect(findDatatype([1, 2, 3])).toBe("array"); expect(findDatatype([])).toBe("array"); expect(findDatatype(["a", true, 3, null])).toBe("array"); expect(findDatatype([1, 2, 3])).toBe("array"); expect(findDatatype(Array.of("a", "b", "c"))).toBe("array"); expect(findDatatype("a, b, c")).not.toBe("array"); }); }); describe("7. Test addErrorToEntityProperty method", () => { it("Add error to dataTreeEvaluator.evalProps", () => { const dataTreeEvaluator = new DataTreeEvaluator({}); const error = { errorMessage: { name: "", message: "some error" }, errorType: PropertyEvaluationErrorType.VALIDATION, raw: "undefined", severity: Severity.ERROR, originalBinding: "", } as EvaluationError; addErrorToEntityProperty({ errors: [error], evalProps: dataTreeEvaluator.evalProps, fullPropertyPath: "Api1.data", configTree: dataTreeEvaluator.oldConfigTree, }); expect( dataTreeEvaluator.evalProps.Api1.__evaluation__?.errors.data[0], ).toEqual(error); }); }); describe("convertJSFunctionsToString", () => { const JSObject1MyFun1 = new String('() => {\n return "name";\n}'); set(JSObject1MyFun1, "data", {}); const JSObject2MyFun1 = new String("() => {}"); set(JSObject2MyFun1, "data", {}); const JSObject2MyFun2 = new String("async () => {}"); set(JSObject2MyFun2, "data", {}); const configTree = { JSObject1: { variables: [], meta: { myFun1: { arguments: [], isAsync: false, confirmBeforeExecute: false, }, }, name: "JSObject1", actionId: "63ef4cb1a01b764626f2a6e5", ENTITY_TYPE: ENTITY_TYPE_VALUE.JSACTION, pluginType: PluginType.JS, bindingPaths: { body: EvaluationSubstitutionType.SMART_SUBSTITUTE, myFun1: EvaluationSubstitutionType.SMART_SUBSTITUTE, }, reactivePaths: { body: EvaluationSubstitutionType.SMART_SUBSTITUTE, myFun1: EvaluationSubstitutionType.SMART_SUBSTITUTE, }, dynamicBindingPathList: [ { key: "body", }, { key: "myFun1", }, ], dependencyMap: { body: ["myFun1"], }, }, JSObject2: { ENTITY_TYPE: ENTITY_TYPE_VALUE.JSACTION, meta: { myFun1: { arguments: [], isAsync: false, confirmBeforeExecute: false, }, myFun2: { arguments: [], isAsync: true, confirmBeforeExecute: false, }, }, name: "JSObject2", actionId: "63f78437d1a4ef55755952f1", pluginType: PluginType.JS, bindingPaths: { body: EvaluationSubstitutionType.SMART_SUBSTITUTE, myVar1: EvaluationSubstitutionType.SMART_SUBSTITUTE, myVar2: EvaluationSubstitutionType.SMART_SUBSTITUTE, myFun1: EvaluationSubstitutionType.SMART_SUBSTITUTE, myFun2: EvaluationSubstitutionType.SMART_SUBSTITUTE, }, reactivePaths: { body: EvaluationSubstitutionType.SMART_SUBSTITUTE, myVar1: EvaluationSubstitutionType.SMART_SUBSTITUTE, myVar2: EvaluationSubstitutionType.SMART_SUBSTITUTE, myFun1: EvaluationSubstitutionType.SMART_SUBSTITUTE, myFun2: EvaluationSubstitutionType.SMART_SUBSTITUTE, }, dynamicBindingPathList: [ { key: "body", }, { key: "myVar1", }, { key: "myVar2", }, { key: "myFun1", }, { key: "myFun2", }, ], variables: ["myVar1", "myVar2"], dependencyMap: { body: ["myFun1", "myFun2"], }, }, } as unknown as ConfigTree; const jsCollections: Record<string, JSActionEntity> = { JSObject1: { myFun1: JSObject1MyFun1, body: 'export default {\nmyFun1: ()=>{ \n\treturn "name"\n} \n}', ENTITY_TYPE: ENTITY_TYPE_VALUE.JSACTION, actionId: "63ef4cb1a01b764626f2a6e5", }, JSObject2: { myVar1: "[]", myVar2: "{}", myFun1: JSObject2MyFun1, myFun2: JSObject2MyFun2, 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}", ENTITY_TYPE: ENTITY_TYPE_VALUE.JSACTION, actionId: "63f78437d1a4ef55755952f1", }, }; const expectedResult = { JSObject1: { myFun1: '() => {\n return "name";\n}', body: 'export default {\nmyFun1: ()=>{ \n\treturn "name"\n} \n}', ENTITY_TYPE: "JSACTION", "myFun1.data": {}, actionId: "63ef4cb1a01b764626f2a6e5", }, JSObject2: { myVar1: "[]", myVar2: "{}", myFun1: "() => {}", myFun2: "async () => {}", 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}", ENTITY_TYPE: "JSACTION", "myFun1.data": {}, "myFun2.data": {}, actionId: "63f78437d1a4ef55755952f1", }, }; const actualResult = convertJSFunctionsToString(jsCollections, configTree); expect(expectedResult).toStrictEqual(actualResult); });
9,505
0
petrpan-code/appsmithorg/appsmith/app/client/src/ce/workers/Evaluation
petrpan-code/appsmithorg/appsmith/app/client/src/ce/workers/Evaluation/__tests__/dataTreeUtils.test.ts
import type { DataTree } from "entities/DataTree/dataTreeTypes"; import { makeEntityConfigsAsObjProperties } from "@appsmith/workers/Evaluation/dataTreeUtils"; import { smallDataSet } from "workers/Evaluation/__tests__/generateOpimisedUpdates.test"; import produce from "immer"; import { cloneDeep } from "lodash"; const unevalTreeFromMainThread = { Api2: { actionId: "6380b1003a20d922b774eb75", run: {}, clear: {}, isLoading: false, responseMeta: { isExecutionSuccess: false, }, config: {}, ENTITY_TYPE: "ACTION", datasourceUrl: "https://www.facebook.com", }, JSObject1: { actionId: "637cda3b2f8e175c6f5269d5", newFunction: { data: {}, }, storeTest2: { data: {}, }, body: "export default {\n\tstoreTest2: () => {\n\t\tlet values = [\n\t\t\t\t\tstoreValue('val1', 'number 1'),\n\t\t\t\t\tstoreValue('val2', 'number 2'),\n\t\t\t\t\tstoreValue('val3', 'number 3'),\n\t\t\t\t\tstoreValue('val4', 'number 4')\n\t\t\t\t];\n\t\treturn Promise.all(values)\n\t\t\t.then(() => {\n\t\t\tshowAlert(JSON.stringify(appsmith.store))\n\t\t})\n\t\t\t.catch((err) => {\n\t\t\treturn showAlert('Could not store values in store ' + err.toString());\n\t\t})\n\t},\n\tnewFunction: function() {\n\t\tJSObject1.storeTest()\n\t}\n}", ENTITY_TYPE: "JSACTION", }, MainContainer: { ENTITY_TYPE: "WIDGET", widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1224, snapColumns: 64, widgetId: "0", topRow: 0, bottomRow: 1240, containerStyle: "none", snapRows: 124, parentRowSpace: 1, canExtend: true, minHeight: 1250, parentColumnSpace: 1, leftColumn: 0, meta: {}, type: "CANVAS_WIDGET", }, Button2: { ENTITY_TYPE: "WIDGET", resetFormOnClick: false, boxShadow: "none", widgetName: "Button2", buttonColor: "{{appsmith.theme.colors.primaryColor}}", topRow: 3, bottomRow: 7, parentRowSpace: 10, animateLoading: true, parentColumnSpace: 34.5, leftColumn: 31, text: "test", isDisabled: false, key: "oypcoe6gx4", rightColumn: 47, isDefaultClickDisabled: true, widgetId: "vxpz4ta27g", isVisible: true, recaptchaType: "V3", isLoading: false, disabledWhenInvalid: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", buttonVariant: "PRIMARY", placement: "CENTER", meta: {}, type: "BUTTON_WIDGET", }, appsmith: { user: { email: "[email protected]", username: "[email protected]", name: "Some name", enableTelemetry: true, emptyInstance: false, accountNonExpired: true, accountNonLocked: true, credentialsNonExpired: true, isAnonymous: false, isEnabled: true, isSuperUser: false, isConfigurable: true, }, URL: { fullPath: "", host: "dev.appsmith.com", hostname: "dev.appsmith.com", queryParams: {}, protocol: "https:", pathname: "", port: "", hash: "", }, store: { val1: "number 1", val2: "number 2", }, geolocation: { canBeRequested: true, currentPosition: {}, }, mode: "EDIT", theme: { colors: { primaryColor: "#553DE9", backgroundColor: "#F6F6F6", }, borderRadius: { appBorderRadius: "0.375rem", }, boxShadow: { appBoxShadow: "0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)", }, fontFamily: { appFont: "Nunito Sans", }, }, ENTITY_TYPE: "APPSMITH", }, }; describe("7. Test util methods", () => { describe("makeDataTreeEntityConfigAsProperty", () => { it("should not introduce __evaluation__ property", () => { const dataTree = makeEntityConfigsAsObjProperties( unevalTreeFromMainThread as unknown as DataTree, ); expect(dataTree.Api2).not.toHaveProperty("__evaluation__"); }); describe("identicalEvalPathsPatches decompress updates", () => { it("should decompress identicalEvalPathsPatches updates into evalProps and state", () => { const state = { Table1: { filteredTableData: smallDataSet, selectedRows: [], pageSize: 0, __evaluation__: { evaluatedValues: {}, }, }, } as any; const identicalEvalPathsPatches = { "Table1.__evaluation__.evaluatedValues.['filteredTableData']": "Table1.filteredTableData", }; const evalProps = { Table1: { __evaluation__: { evaluatedValues: { someProp: "abc", }, }, }, } as any; const dataTree = makeEntityConfigsAsObjProperties(state as any, { sanitizeDataTree: true, evalProps, identicalEvalPathsPatches, }); const expectedState = produce(state, (draft: any) => { draft.Table1.__evaluation__.evaluatedValues.someProp = "abc"; draft.Table1.__evaluation__.evaluatedValues.filteredTableData = smallDataSet; }); expect(dataTree).toEqual(expectedState); //evalProps should have decompressed updates in it coming from identicalEvalPathsPatches const expectedEvalProps = produce(evalProps, (draft: any) => { draft.Table1.__evaluation__.evaluatedValues.filteredTableData = smallDataSet; }); expect(evalProps).toEqual(expectedEvalProps); }); it("should not make any updates to evalProps when the identicalEvalPathsPatches is empty", () => { const state = { Table1: { filteredTableData: smallDataSet, selectedRows: [], pageSize: 0, __evaluation__: { evaluatedValues: {}, }, }, } as any; const identicalEvalPathsPatches = {}; const initialEvalProps = {} as any; const evalProps = cloneDeep(initialEvalProps); const dataTree = makeEntityConfigsAsObjProperties(state, { sanitizeDataTree: true, evalProps, identicalEvalPathsPatches, }); expect(dataTree).toEqual(dataTree); //evalProps not be mutated with any updates expect(evalProps).toEqual(initialEvalProps); }); it("should ignore non relevant identicalEvalPathsPatches updates into evalProps and state", () => { const state = { Table1: { filteredTableData: smallDataSet, selectedRows: [], pageSize: 0, __evaluation__: { evaluatedValues: {}, }, }, } as any; //ignore non existent widget state const identicalEvalPathsPatches = { "SomeWidget.__evaluation__.evaluatedValues.['filteredTableData']": "SomeWidget.filteredTableData", }; const initialEvalProps = { Table1: { __evaluation__: { evaluatedValues: { someProp: "abc", }, }, }, } as any; const evalProps = cloneDeep(initialEvalProps); const dataTree = makeEntityConfigsAsObjProperties(state, { sanitizeDataTree: true, evalProps, identicalEvalPathsPatches, }); const expectedState = produce(state, (draft: any) => { draft.Table1.__evaluation__.evaluatedValues.someProp = "abc"; }); expect(dataTree).toEqual(expectedState); //evalProps not be mutated with any updates expect(evalProps).toEqual(initialEvalProps); }); }); }); });
9,546
0
petrpan-code/appsmithorg/appsmith/app/client/src/components
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/AutoResizeTextArea.test.tsx
import React from "react"; import "@testing-library/jest-dom"; import "jest-styled-components"; import renderer from "react-test-renderer"; import AutoResizeTextArea from "./AutoResizeTextArea"; describe("<AutoResizeTextArea />", () => { describe("when autoResize is true", () => { it("it should render a proxy textarea", async () => { const tree = renderer.create(<AutoResizeTextArea autoResize />); expect(tree.root.findAllByType("textarea").length).toBe(2); }); }); describe("when autoResize is false", () => { it("it should not render a proxy textarea if autoResize is false", async () => { const tree = renderer.create(<AutoResizeTextArea autoResize={false} />); expect(tree.root.findAllByType("textarea").length).toBe(1); }); }); });
9,556
0
petrpan-code/appsmithorg/appsmith/app/client/src/components
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/EditorContextProvider.test.tsx
import React, { useContext } from "react"; import store from "store"; import TestRenderer from "react-test-renderer"; import { Provider } from "react-redux"; import type { EditorContextType } from "./EditorContextProvider"; import EditorContextProvider, { EditorContext } from "./EditorContextProvider"; interface TestChildProps { editorContext: EditorContextType; } const TestChild = (props: TestChildProps) => { return <div>{Object.keys(props)}</div>; }; const TestParent = () => { const editorContext = useContext(EditorContext); return <TestChild editorContext={editorContext} />; }; describe("EditorContextProvider", () => { it("it checks context methods in Edit mode", () => { const expectedMethods = [ "batchUpdateWidgetProperty", "executeAction", "getWidgetCache", "modifyMetaWidgets", "resetChildrenMetaProperty", "selectWidgetRequest", "setWidgetCache", "updateMetaWidgetProperty", "syncUpdateWidgetMetaProperty", "syncBatchUpdateWidgetMetaProperties", "triggerEvalOnMetaUpdate", "deleteMetaWidgets", "deleteWidgetProperty", "disableDrag", "updateWidget", "updateWidgetProperty", "updateWidgetAutoHeight", "updateWidgetDimension", "checkContainersForAutoHeight", "updatePositionsOnTabChange", "updateOneClickBindingOptionsVisibility", ].sort(); const testRenderer = TestRenderer.create( <Provider store={store}> <EditorContextProvider renderMode="CANVAS"> <TestParent /> </EditorContextProvider> </Provider>, ); const testInstance = testRenderer.root; const result = ( Object.keys(testInstance.findByType(TestChild).props.editorContext) || [] ).sort(); expect(result).toEqual(expectedMethods); }); it("it checks context methods in View mode", () => { const expectedMethods = [ "batchUpdateWidgetProperty", "deleteMetaWidgets", "executeAction", "getWidgetCache", "modifyMetaWidgets", "resetChildrenMetaProperty", "selectWidgetRequest", "setWidgetCache", "updateMetaWidgetProperty", "syncUpdateWidgetMetaProperty", "syncBatchUpdateWidgetMetaProperties", "triggerEvalOnMetaUpdate", "updateWidgetAutoHeight", "updateWidgetDimension", "checkContainersForAutoHeight", "updatePositionsOnTabChange", ].sort(); const testRenderer = TestRenderer.create( <Provider store={store}> <EditorContextProvider renderMode="PAGE"> <TestParent /> </EditorContextProvider> </Provider>, ); const testInstance = testRenderer.root; const result = ( Object.keys(testInstance.findByType(TestChild).props.editorContext) || [] ).sort(); expect(result).toEqual(expectedMethods); }); });
9,584
0
petrpan-code/appsmithorg/appsmith/app/client/src/components
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/utils.test.ts
import { JSResponseState } from "./JSResponseView"; import { getJSResponseViewState } from "./utils"; const TEST_JS_FUNCTION_ID = "627ccff468e1fa5185b7f901"; const TEST_JS_FUNCTION = { id: TEST_JS_FUNCTION_ID, applicationId: "627aaf637e9e9b75e43ad2ff", workspaceId: "61e52bb4847aa804d79fc7c1", pluginType: "JS", pluginId: "6138c786168857325f78ef3e", name: "myFun234y", fullyQualifiedName: "JSObject1.myFun234y", datasource: { userPermissions: [], name: "UNUSED_DATASOURCE", pluginId: "6138c786168857325f78ef3e", workspaceId: "61e52bb4847aa804d79fc7c1", messages: [], isValid: true, new: true, }, pageId: "627aaf637e9e9b75e43ad302", collectionId: "627ccff468e1fa5185b7f904", actionConfiguration: { timeoutInMillisecond: 10000, paginationType: "NONE", encodeParamsToggle: true, body: "async () => {\n\t\t//use async-await or promises here\n\t\t\n\t}", jsArguments: [], isAsync: true, }, executeOnLoad: false, clientSideExecution: true, dynamicBindingPathList: [ { key: "body", }, ], isValid: true, invalids: [], messages: [], jsonPathKeys: [ "async () => {\n\t\t//use async-await or promises here\n\t\t\n\t}", ], confirmBeforeExecute: false, userPermissions: ["read:actions", "execute:actions", "manage:actions"], validName: "JSObject1.myFun234y", cacheResponse: "", }; describe("GetJSResponseViewState", () => { it("1. returns 'NoResponse' at default state", () => { const currentFunction = null, isDirty = {}, isExecuting = {}, isSaving = false, responses = {}; const expectedState = JSResponseState.NoResponse; const actualState = getJSResponseViewState( currentFunction, isDirty, isExecuting, isSaving, responses, ); expect(expectedState).toBe(actualState); }); it("2. returns 'NoResponse' when an entity is still saving but no execution has begun", () => { const currentFunction = TEST_JS_FUNCTION, isDirty = {}, isExecuting = {}, isSaving = true, responses = {}; const expectedState = JSResponseState.NoResponse; const actualState = getJSResponseViewState( currentFunction, isDirty, isExecuting, isSaving, responses, ); expect(expectedState).toBe(actualState); }); it("3. returns 'IsUpdating' when an entity is still saving and execution has started", () => { const currentFunction = TEST_JS_FUNCTION, isDirty = {}, isExecuting = { [TEST_JS_FUNCTION_ID]: true, }, isSaving = true, responses = {}; const expectedState = JSResponseState.IsUpdating; const actualState = getJSResponseViewState( currentFunction, isDirty, isExecuting, isSaving, responses, ); expect(expectedState).toBe(actualState); }); it("4. returns 'IsExecuting' when no entity is saving and execution has begun", () => { const currentFunction = TEST_JS_FUNCTION, isDirty = {}, isExecuting = { [TEST_JS_FUNCTION_ID]: true, }, isSaving = false, responses = {}; const expectedState = JSResponseState.IsExecuting; const actualState = getJSResponseViewState( currentFunction, isDirty, isExecuting, isSaving, responses, ); expect(expectedState).toBe(actualState); }); it("5. returns 'IsDirty' when function has finished executing and there is parse error", () => { const currentFunction = TEST_JS_FUNCTION, isDirty = { [TEST_JS_FUNCTION_ID]: true, }, isExecuting = { [TEST_JS_FUNCTION_ID]: false, }, isSaving = false, responses = { [TEST_JS_FUNCTION_ID]: undefined, }; const expectedState = JSResponseState.IsDirty; const actualState = getJSResponseViewState( currentFunction, isDirty, isExecuting, isSaving, responses, ); expect(expectedState).toBe(actualState); }); it("6. returns 'IsExecuting' when function is still executing and has a previous response", () => { const currentFunction = TEST_JS_FUNCTION, isDirty = {}, isExecuting = { [TEST_JS_FUNCTION_ID]: true, }, isSaving = false, responses = { [TEST_JS_FUNCTION_ID]: "test response", }; const expectedState = JSResponseState.IsExecuting; const actualState = getJSResponseViewState( currentFunction, isDirty, isExecuting, isSaving, responses, ); expect(expectedState).toBe(actualState); }); it("7. returns 'NoReturnValue' when function is done executing and returns 'undefined'", () => { const currentFunction = TEST_JS_FUNCTION, isDirty = {}, isExecuting = { [TEST_JS_FUNCTION_ID]: false, }, isSaving = false, responses = { [TEST_JS_FUNCTION_ID]: undefined, }; const expectedState = JSResponseState.NoReturnValue; const actualState = getJSResponseViewState( currentFunction, isDirty, isExecuting, isSaving, responses, ); expect(expectedState).toBe(actualState); }); it("8. returns 'ShowResponse' when function is done executing and returns a valid response", () => { const currentFunction = TEST_JS_FUNCTION, isDirty = {}, isExecuting = { [TEST_JS_FUNCTION_ID]: false, }, isSaving = false, responses = { [TEST_JS_FUNCTION_ID]: {}, }; const expectedState = JSResponseState.ShowResponse; const actualState = getJSResponseViewState( currentFunction, isDirty, isExecuting, isSaving, responses, ); expect(expectedState).toBe(actualState); }); it("9. returns 'IsExecuting' when no entity is saving ,execution has begun and function has a previous response", () => { const currentFunction = TEST_JS_FUNCTION, isDirty = {}, isExecuting = { [TEST_JS_FUNCTION_ID]: true, }, isSaving = false, responses = { [TEST_JS_FUNCTION_ID]: "previous response", }; const expectedState = JSResponseState.IsExecuting; const actualState = getJSResponseViewState( currentFunction, isDirty, isExecuting, isSaving, responses, ); expect(expectedState).toBe(actualState); }); it("10. returns 'NoResponse' when no entity is saving , execution has not begun and function has a no previous response", () => { const currentFunction = TEST_JS_FUNCTION, isDirty = {}, isExecuting = { [TEST_JS_FUNCTION_ID]: false, }, isSaving = false, responses = {}; const expectedState = JSResponseState.NoResponse; const actualState = getJSResponseViewState( currentFunction, isDirty, isExecuting, isSaving, responses, ); expect(expectedState).toBe(actualState); }); });
9,591
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/ActionCreator/utils.test.ts
import { EMPTY_BINDING_WITH_EMPTY_OBJECT } from "./constants"; jest.mock("sagas/ActionExecution/NavigateActionSaga", () => ({ __esModule: true, default: "", NavigationTargetType: { SAME_WINDOW: "" }, })); import { argsStringToArray, enumTypeSetter, enumTypeGetter, JSToString, modalGetter, modalSetter, stringToJS, textGetter, textSetter, isValueValidURL, objectSetter, sortSubMenuOptions, } from "./utils"; import type { TreeDropdownOption } from "design-system-old"; describe("Test argStringToArray", () => { const cases = [ { index: 0, input: "", expected: [""] }, { index: 1, input: "'a'", expected: ["'a'"] }, { index: 2, input: "a", expected: ["a"] }, { index: 3, input: "'a,b,c'", expected: ["'a,b,c'"] }, { index: 4, input: "a,b,c", expected: ["a", "b", "c"] }, { index: 5, input: "a, b, c", expected: ["a", " b", " c"] }, { index: 6, input: "a , b , c", expected: ["a ", " b ", " c"] }, { index: 7, input: "[a,b,c]", expected: ["[a,b,c]"] }, { index: 8, input: "[a, b, c]", expected: ["[a, b, c]"] }, { index: 9, input: "[\n\ta,\n\tb,\n\tc\n]", expected: ["[\n\ta,\n\tb,\n\tc\n]"], }, { index: 10, input: "{a:1,b:2,c:3}", expected: ["{a:1,b:2,c:3}"] }, { index: 11, input: '{"a":1,"b":2,"c":3}', expected: ['{"a":1,"b":2,"c":3}'], }, { index: 12, input: "{\n\ta:1,\n\tb:2,\n\tc:3}", expected: ["{\n\ta:1,\n\tb:2,\n\tc:3}"], }, { index: 13, input: "()=>{}", expected: ["()=>{}"], }, { index: 14, input: "(a, b)=>{return a+b}", expected: ["(a, b)=>{return a+b}"], }, { index: 15, input: "(a, b)=>{\n\treturn a+b;\n\t}", expected: ["(a, b)=>{\n\treturn a+b;\n\t}"], }, { index: 16, input: "(\n\ta,\n\tb\n)=>{\n\treturn a+b;\n\t}", expected: ["(\n\ta,\n\tb\n)=>{\n\treturn a+b;\n\t}"], }, { index: 17, input: `() => {return 5}`, expected: ["() => {return 5}"], }, { index: 19, input: `(a) => {return a + 1}`, expected: ["(a) => {return a + 1}"], }, { index: 19, input: `(a, b) => {return a + b}`, expected: ["(a, b) => {return a + b}"], }, ]; test.each(cases.map((x) => [x.index, x.input, x.expected]))( "test case %d", (_, input, expected) => { const result = argsStringToArray(input as string); expect(result).toStrictEqual(expected); }, ); }); describe("Test stringToJS", () => { const cases = [ { index: 1, input: "{{'a'}}", expected: "'a'" }, { index: 2, input: "{{a}}", expected: "a" }, { index: 3, input: "{{'a,b,c'}}", expected: "'a,b,c'" }, { index: 4, input: "{{a,b,c}}", expected: "a,b,c" }, { index: 5, input: "{{a, b, c}}", expected: "a, b, c" }, { index: 6, input: "{{a , b , c}}", expected: "a , b , c" }, { index: 7, input: "{{[a,b,c]}}", expected: "[a,b,c]" }, { index: 8, input: "{{[a, b, c]}}", expected: "[a, b, c]" }, { index: 9, input: "{{[\n\ta,\n\tb,\n\tc\n]}}", expected: "[\n\ta,\n\tb,\n\tc\n]", }, { index: 10, input: "{{{a:1,b:2,c:3}}}", expected: "{a:1,b:2,c:3}" }, { index: 11, input: '{{{"a":1,"b":2,"c":3}}}', expected: '{"a":1,"b":2,"c":3}', }, { index: 12, input: "{{{\n\ta:1,\n\tb:2,\n\tc:3}}}", expected: "{\n\ta:1,\n\tb:2,\n\tc:3}", }, { index: 13, input: "{{()=>{}}}", expected: "()=>{}", }, { index: 14, input: "{{(a, b)=>{return a+b}}}", expected: "(a, b)=>{return a+b}", }, { index: 15, input: "{{(a, b)=>{\n\treturn a+b;\n\t}}}", expected: "(a, b)=>{\n\treturn a+b;\n\t}", }, { index: 16, input: "{{(\n\ta,\n\tb\n)=>{\n\treturn a+b;\n\t}}}", expected: "(\n\ta,\n\tb\n)=>{\n\treturn a+b;\n\t}", }, { index: 17, input: "{{() => {return 5}}}", expected: "() => {return 5}", }, { index: 18, input: "{{(a) => {return a + 1}}}", expected: "(a) => {return a + 1}", }, { index: 19, input: "{{(a, b) => {return a + b}}}", expected: "(a, b) => {return a + b}", }, { index: 20, input: "{{Text1}}", expected: "Text1", }, { index: 21, input: "Hello {{Text1}}", expected: "'Hello ' + Text1", }, { index: 22, input: "Hello", expected: "'Hello'", }, ]; test.each(cases.map((x) => [x.index, x.input, x.expected]))( "test case %d", (_, input, expected) => { const result = stringToJS(input as string); expect(result).toStrictEqual(expected); }, ); }); describe("Test JSToString", () => { const cases = [ { index: 1, input: "'a'", expected: "a" }, { index: 2, input: "a", expected: "{{a}}" }, { index: 3, input: "'a,b,c'", expected: "a,b,c" }, { index: 4, input: "a,b,c", expected: "{{a,b,c}}" }, { index: 5, input: "a, b, c", expected: "{{a, b, c}}" }, { index: 6, input: "a , b , c", expected: "{{a , b , c}}" }, { index: 7, input: "[a,b,c]", expected: "{{[a,b,c]}}" }, { index: 8, input: "[a, b, c]", expected: "{{[a, b, c]}}" }, { index: 9, input: "[\n\ta,\n\tb,\n\tc\n]", expected: "{{[\n\ta,\n\tb,\n\tc\n]}}", }, { index: 10, input: "{a:1,b:2,c:3}", expected: "{{{a:1,b:2,c:3}}}" }, { index: 11, input: '{"a":1,"b":2,"c":3}', expected: '{{{"a":1,"b":2,"c":3}}}', }, { index: 12, input: "{\n\ta:1,\n\tb:2,\n\tc:3}", expected: "{{{\n\ta:1,\n\tb:2,\n\tc:3}}}", }, { index: 13, input: "()=>{}", expected: "{{()=>{}}}", }, { index: 14, input: "(a, b)=>{return a+b}", expected: "{{(a, b)=>{return a+b}}}", }, { index: 15, input: "(a, b)=>{\n\treturn a+b;\n\t}", expected: "{{(a, b)=>{\n\treturn a+b;\n\t}}}", }, { index: 16, input: "(\n\ta,\n\tb\n)=>{\n\treturn a+b;\n\t}", expected: "{{(\n\ta,\n\tb\n)=>{\n\treturn a+b;\n\t}}}", }, { index: 17, input: "() => {return 5}", expected: "{{() => {return 5}}}", }, ]; test.each(cases.map((x) => [x.index, x.input, x.expected]))( "test case %d", (_, input, expected) => { const result = JSToString(input as string); expect(result).toStrictEqual(expected); }, ); }); describe("Test modalSetter", () => { const cases = [ { index: 1, input: "{{showModal('')}}", expected: "{{showModal('Modal1');}}", value: "Modal1", }, { index: 2, input: "{{showModal('Modal1')}}", expected: "{{showModal('Modal2');}}", value: "Modal2", }, { index: 3, input: "{{closeModal('')}}", expected: "{{closeModal('Modal1');}}", value: "Modal1", }, { index: 4, input: "{{closeModal('Modal1')}}", expected: "{{closeModal('Modal2');}}", value: "Modal2", }, ]; test.each(cases.map((x) => [x.index, x.input, x.expected, x.value]))( "test case %d", (index, input, expected, value) => { const result = modalSetter(value as string, input as string); expect(result).toStrictEqual(expected); }, ); }); describe("Test modalGetter", () => { const cases = [ { index: 1, input: "{{showModal('')}}", expected: "", }, { index: 2, input: "{{showModal('Modal1')}}", expected: "Modal1", }, { index: 3, input: "{{closeModal('')}}", expected: "", }, { index: 4, input: "{{closeModal('Modal1')}}", expected: "Modal1", }, ]; test.each(cases.map((x) => [x.index, x.input, x.expected]))( "test case %d", (index, input, expected) => { const result = modalGetter(input as string); expect(result).toStrictEqual(expected); }, ); }); describe("Test textSetter", () => { const cases = [ { index: 0, input: '{{navigateTo("", {}, NEW_WINDOW)}}', expected: "{{navigateTo('google.com', {}, NEW_WINDOW);}}", argNum: 0, value: "google.com", }, { index: 1, input: '{{download("image", "", "")}}', expected: '{{download("image", \'img.png\', "");}}', argNum: 1, value: "img.png", }, { index: 2, input: "{{showAlert(1, 'info')}}", expected: "{{showAlert(true, 'info');}}", argNum: 0, value: "{{true}}", }, { index: 3, input: '{{showAlert("hi", "info")}}', expected: "{{showAlert('bye', \"info\");}}", argNum: 0, value: "bye", }, { index: 4, input: '{{showAlert("hi", "")}}', expected: "{{showAlert('', \"\");}}", argNum: 0, value: "", }, { index: 5, input: "{{showAlert('', '')}}", expected: "{{showAlert(1, '');}}", argNum: 0, value: "{{1}}", }, { index: 6, input: "{{showAlert(true, '')}}", expected: "{{showAlert(appsmith.mode, '');}}", argNum: 0, value: "{{appsmith.mode}}", }, { index: 7, input: "{{showAlert(appsmith.mode, '')}}", expected: "{{showAlert('', '');}}", argNum: 0, value: "", }, { index: 8, input: "{{showAlert(JSobj1.myText, '')}}", expected: "{{showAlert(JSobj1.myText, '');}}", argNum: 0, value: "{{JSobj1.myText}}", }, { index: 9, input: '{{showAlert("", "");}}', expected: '{{showAlert("r" + "p" + "rdpp", "");}}', argNum: 0, value: '{{"r" + "p" + "rdpp"}}', }, { index: 10, input: '{{showAlert("", "");}}', expected: '{{showAlert(JSObject1.myVar1 + "dfd", "");}}', argNum: 0, value: '{{JSObject1.myVar1 + "dfd"}}', }, { index: 11, input: '{{showAlert(true, "");}}', expected: '{{showAlert(() => {\n return "hi";\n}, "");}}', argNum: 0, value: '{{() => {\n return "hi";\n}}}', }, { index: 12, input: "{{JSObject1.myFun1();}}", expected: "{{JSObject1.myFun1('Hello');}}", argNum: 0, value: "Hello", }, { index: 13, input: '{{setInterval(() => {\n // add code here\n console.log("hello");\n}, 5000, "");}}', expected: "{{setInterval(() => {\n // add code here\n console.log(\"hello\");\n}, 5000, 'hello-id');}}", argNum: 2, value: "hello-id", }, ]; test.each( cases.map((x) => [x.index, x.input, x.expected, x.value, x.argNum]), )("test case %d", (index, input, expected, value, argNum) => { const result = textSetter( value as string, input as string, argNum as number, ); expect(result).toStrictEqual(expected); }); }); describe("Test textGetter", () => { const cases = [ { index: 0, input: "{{navigateTo('google.com', {}, NEW_WINDOW)}}", expected: "google.com", argNum: 0, }, { index: 1, input: "{{navigateTo('google.com', {}, NEW_WINDOW)}}", expected: EMPTY_BINDING_WITH_EMPTY_OBJECT, argNum: 1, }, { index: 2, input: "{{showAlert('', 'info')}}", expected: "", argNum: 0, }, { index: 3, input: "{{showAlert('hi', 'info')}}", expected: "hi", argNum: 0, }, { index: 4, input: "{{showAlert('hi', '')}}", expected: "hi", argNum: 0, }, { index: 5, input: "{{showAlert(1, '')}}", expected: "{{1}}", argNum: 0, }, { index: 6, input: "{{showAlert(true, '')}}", expected: "{{true}}", argNum: 0, }, { index: 7, input: "{{showAlert(appsmith.mode, '')}}", expected: "{{appsmith.mode}}", argNum: 0, }, { index: 8, input: "{{showAlert(JSobj1.myText, '')}}", expected: "{{JSobj1.myText}}", argNum: 0, }, { index: 9, input: '{{showAlert("r" + "p" + "rdpp", "");}}', expected: '{{"r" + "p" + "rdpp"}}', argNum: 0, }, { index: 10, input: '{{showAlert(JSObject1.myVar1 + "dfd", "");}}', expected: '{{JSObject1.myVar1 + "dfd"}}', argNum: 0, }, { index: 11, input: '{{showAlert(() =>{return "hi"}, "");}}', expected: '{{() => {\n return "hi";\n}}}', argNum: 0, }, { index: 12, input: '{{storeValue("a", 1).then(showAlert("yo"))}}', expected: "a", argNum: 0, }, { index: 13, input: '{{storeValue("a", 1).then(() => showAlert("yo"))}}', expected: "a", argNum: 0, }, { index: 14, input: "{{navigateTo('Page1', {a:1}, 'SAME_WINDOW');}}", expected: "{{{\n a: 1\n}}}", argNum: 1, }, { index: 15, input: "{{navigateTo('Page1', {a:1, b:3}, 'SAME_WINDOW');}}", expected: "{{{\n a: 1,\n b: 3\n}}}", argNum: 1, }, { index: 16, input: "{{navigateTo('Page1', {}, 'SAME_WINDOW');}}", expected: EMPTY_BINDING_WITH_EMPTY_OBJECT, argNum: 1, }, ]; test.each(cases.map((x) => [x.index, x.input, x.expected, x.argNum]))( "test case %d", (index, input, expected, argNum) => { const result = textGetter(input as string, argNum as number); expect(result).toStrictEqual(expected); }, ); }); describe("Test enumTypeSetter", () => { const cases = [ { index: 0, value: "'info'", input: "{{showAlert('hi')}}", expected: "{{showAlert('hi', 'info');}}", argNum: 1, }, { index: 1, value: "'info'", input: "{{showAlert('hi','error')}}", expected: "{{showAlert('hi', 'info');}}", argNum: 1, }, { index: 2, value: "'info'", input: "{{showAlert('','')}}", expected: "{{showAlert('', 'info');}}", argNum: 1, }, { index: 3, value: "'NEW_WINDOW'", input: "{{navigateTo('', {}, 'SAME_WINDOW')}}", expected: "{{navigateTo('', {}, 'NEW_WINDOW');}}", argNum: 2, }, { index: 4, value: "'SAME_WINDOW'", input: "{{navigateTo('', {}, 'NEW_WINDOW')}}", expected: "{{navigateTo('', {}, 'SAME_WINDOW');}}", argNum: 2, }, ]; test.each( cases.map((x) => [x.index, x.input, x.expected, x.value, x.argNum]), )("test case %d", (index, input, expected, value, argNum) => { const result = enumTypeSetter( value as string, input as string, argNum as number, ); expect(result).toStrictEqual(expected); }); }); describe("Test enumTypeGetter", () => { const cases = [ { index: 0, input: "{{showAlert('hi','info')}}", expected: "'info'", argNum: 1, }, { index: 1, input: "{{showAlert('','error')}}", expected: "'error'", argNum: 1, }, { index: 2, input: "{{navigateTo('Page1', {}, 'SAME_WINDOW');}}", expected: "'Page1'", argNum: 0, }, ]; test.each(cases.map((x) => [x.index, x.input, x.expected, x.argNum]))( "test case %d", (index, input, expected, argNum) => { const result = enumTypeGetter(input as string, argNum as number); expect(result).toStrictEqual(expected); }, ); }); describe("Test objectSetter", () => { const cases = [ { index: 0, value: "{{{a:1}}}", input: "{{navigateTo('', {}, 'SAME_WINDOW')}}", expected: "{{navigateTo('', {a:1}, 'SAME_WINDOW');}}", argNum: 1, }, { index: 1, value: "{{{a:1, b:2}}}", input: "{{navigateTo('', {}, 'SAME_WINDOW')}}", expected: "{{navigateTo('', {a:1, b:2}, 'SAME_WINDOW');}}", argNum: 1, }, { index: 2, value: "{{{a:1, b:2}}}", input: "{{navigateTo('', {c:6}, 'SAME_WINDOW')}}", expected: "{{navigateTo('', {a:1, b:2}, 'SAME_WINDOW');}}", argNum: 1, }, ]; test.each( cases.map((x) => [x.index, x.input, x.expected, x.value, x.argNum]), )("test case %d", (index, input, expected, value, argNum) => { const result = objectSetter( value as string, input as string, argNum as number, ); expect(result).toStrictEqual(expected); }); }); describe("Test isValueValidURL", () => { const cases = [ { index: 1, input: "{{navigateTo('google.com', {}, 'SAME_WINDOW')}}", expected: true, }, { index: 2, input: "{{navigateTo('www.google.com', {}, 'SAME_WINDOW')}}", expected: true, }, { index: 3, input: "{{navigateTo('https://google.com', {}, 'NEW_WINDOW')}}", expected: true, }, { index: 4, input: "{{navigateTo('http://localhost.com', {}, 'NEW_WINDOW')}}", expected: true, }, { index: 5, input: "{{navigateTo('mailTo:[email protected]', {}, 'NEW_WINDOW')}}", expected: true, }, { index: 6, input: "{{navigateTo('1234', {}, 'NEW_WINDOW')}}", expected: false, }, { index: 7, input: "{{navigateTo('hi', {}, 'NEW_WINDOW')}}", expected: false, }, { index: 8, input: "{{navigateTo('[]', {}, 'NEW_WINDOW')}}", expected: false, }, ]; test.each(cases.map((x) => [x.index, x.input, x.expected]))( "test case %d", (_, input, expected) => { const result = isValueValidURL(input as string); expect(result).toStrictEqual(expected); }, ); }); describe("sortSubMenuOptions", () => { const cases = [ { index: 0, input: [ { label: "1", id: "6433b0017bd3732ec082375c", value: "'1'", }, { id: "ndsf3edjw7", label: "adc", value: "adc", }, { id: "a3bvr4ybt1", label: "fsfsdg", value: "fsfsdg", }, { label: "Page1", id: "6398aba6b8c4dd68403825a3", value: "'Page1'", }, { label: "12", id: "6433b0017bd3732ec082375csdsdsds", value: "'12'", }, { label: "2", id: "6433b0017bd3732ec082375csdsdsdssdsds", value: "'2'", }, { label: "Page10", id: "6426cd4646c8f921c25eb1b3", value: "'Page10'", }, { label: "Page2", id: "6399a035b8c4dd684038282e", value: "'Page2'", }, ], expected: [ { label: "1", id: "6433b0017bd3732ec082375c", value: "'1'", }, { label: "2", id: "6433b0017bd3732ec082375csdsdsdssdsds", value: "'2'", }, { label: "12", id: "6433b0017bd3732ec082375csdsdsds", value: "'12'", }, { id: "ndsf3edjw7", label: "adc", value: "adc", }, { id: "a3bvr4ybt1", label: "fsfsdg", value: "fsfsdg", }, { label: "Page1", id: "6398aba6b8c4dd68403825a3", value: "'Page1'", }, { label: "Page2", id: "6399a035b8c4dd684038282e", value: "'Page2'", }, { label: "Page10", id: "6426cd4646c8f921c25eb1b3", value: "'Page10'", }, ], }, { index: 1, input: [ { label: "New window", value: "'NEW_WINDOW'", id: "NEW_WINDOW", }, { label: "Same window", value: "'SAME_WINDOW'", id: "SAME_WINDOW", }, ], expected: [ { label: "New window", value: "'NEW_WINDOW'", id: "NEW_WINDOW", }, { label: "Same window", value: "'SAME_WINDOW'", id: "SAME_WINDOW", }, ], }, { index: 2, input: [ { label: "Error", value: "'error'", id: "error", }, { label: "Info", value: "'info'", id: "info", }, { label: "Success", value: "'success'", id: "success", }, { label: "Warning", value: "'warning'", id: "warning", }, ], expected: [ { label: "Error", value: "'error'", id: "error", }, { label: "Info", value: "'info'", id: "info", }, { label: "Success", value: "'success'", id: "success", }, { label: "Warning", value: "'warning'", id: "warning", }, ], }, { index: 3, input: [ { label: "CSV", value: "'text/csv'", id: "text/csv", }, { label: "Select file type (optional)", value: "", id: "", }, { label: "HTML", value: "'text/html'", id: "text/html", }, { label: "Plain text", value: "'text/plain'", id: "text/plain", }, { label: "PNG", value: "'image/png'", id: "image/png", }, { label: "JPEG", value: "'image/jpeg'", id: "image/jpeg", }, { label: "SVG", value: "'image/svg+xml'", id: "image/svg+xml", }, { label: "JSON", value: "'application/json'", id: "application/json", }, ], expected: [ { label: "Select file type (optional)", value: "", id: "", }, { label: "CSV", value: "'text/csv'", id: "text/csv", }, { label: "HTML", value: "'text/html'", id: "text/html", }, { label: "JPEG", value: "'image/jpeg'", id: "image/jpeg", }, { label: "JSON", value: "'application/json'", id: "application/json", }, { label: "Plain text", value: "'text/plain'", id: "text/plain", }, { label: "PNG", value: "'image/png'", id: "image/png", }, { label: "SVG", value: "'image/svg+xml'", id: "image/svg+xml", }, ], }, { index: 4, input: [ { id: "a3bvr4ybt1", label: "fsfsdg", value: "fsfsdg", }, { label: "New Modal", value: "Modal", id: "create", icon: "plus", className: "t--create-modal-btn", }, { id: "lz8id1xnk7", label: "Modal1", value: "Modal1", }, { id: "j5gg12lloy", label: "Modal2", value: "Modal2", }, { id: "ndsf3edjw7", label: "adc", value: "adc", }, { id: "bfv7i1qt72", label: "Modal10", value: "Modal10", }, ], expected: [ { label: "New Modal", value: "Modal", id: "create", icon: "plus", className: "t--create-modal-btn", }, { id: "ndsf3edjw7", label: "adc", value: "adc", }, { id: "a3bvr4ybt1", label: "fsfsdg", value: "fsfsdg", }, { id: "lz8id1xnk7", label: "Modal1", value: "Modal1", }, { id: "j5gg12lloy", label: "Modal2", value: "Modal2", }, { id: "bfv7i1qt72", label: "Modal10", value: "Modal10", }, ], }, ]; test.each(cases.map((x) => [x.index, x.input, x.expected]))( "test case %d", (_, input, expected) => { const result = sortSubMenuOptions(input as TreeDropdownOption[]); expect(result).toStrictEqual(expected); }, ); });
9,593
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/ActionCreator
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/ActionCreator/Field/Field.test.tsx
import { render, screen } from "test/testUtils"; import "@testing-library/jest-dom"; import React from "react"; import { ThemeProvider } from "styled-components"; import { Field } from "./index"; import { lightTheme } from "selectors/themeSelectors"; import { FieldType } from "../constants"; import { FIELD_CONFIG } from "./FieldConfig"; describe("Field component", () => { const commonProps = { activeNavigateToTab: { action: () => { return null; }, id: "page-name", text: "Page name", }, activeTabApiAndQueryCallback: { action: () => { return null; }, id: "onSuccess", text: "On Success", }, depth: 1, integrationOptions: [], maxDepth: 0, modalDropdownList: [], navigateToSwitches: [ { id: "page-name", text: "Page name", action: () => { return null; }, }, { id: "url", text: "URL", action: () => { return null; }, }, ], apiAndQueryCallbackTabSwitches: [ { id: "onSuccess", text: "onSuccess", action: () => { return null; }, }, { id: "onFailure", text: "onFailure", action: () => { return null; }, }, ], onValueChange: () => { return null; }, pageDropdownOptions: [ { id: "62d8f2ed3e80f46c3ac16df6", label: "Page1", value: "'Page1'" }, ], widgetOptionTree: [], }; const tests = [ { field: FieldType.ALERT_TEXT_FIELD, value: "{{showAlert()}}", testId: "text-view-label", }, { field: FieldType.ALERT_TYPE_SELECTOR_FIELD, value: "{{showAlert()}}", testId: "selector-view-label", }, { field: FieldType.KEY_TEXT_FIELD_STORE_VALUE, value: "{{storeValue()}}", testId: "text-view-label", }, { field: FieldType.VALUE_TEXT_FIELD, value: "{{storeValue()}}", testId: "text-view-label", }, { field: FieldType.QUERY_PARAMS_FIELD, value: "{{navigateTo('', {}, 'SAME_WINDOW')}}", testId: "text-view-label", }, { field: FieldType.DOWNLOAD_DATA_FIELD, value: "{{download()}}", testId: "text-view-label", }, { field: FieldType.DOWNLOAD_FILE_NAME_FIELD, value: "{{download()}}", testId: "text-view-label", }, { field: FieldType.COPY_TEXT_FIELD, value: "{{copyToClipboard()}}", testId: "text-view-label", }, { field: FieldType.NAVIGATION_TARGET_FIELD, value: "{{navigateTo('', {}, 'SAME_WINDOW')}}", testId: "selector-view-label", }, { field: FieldType.WIDGET_NAME_FIELD, value: "{{resetWidget()}}", testId: "selector-view-label", }, { field: FieldType.RESET_CHILDREN_FIELD, value: "{{resetWidget()}}", testId: "selector-view-label", }, { field: FieldType.CALLBACK_FUNCTION_FIELD_SET_INTERVAL, value: "{{setInterval()}}", testId: "text-view-label", }, { field: FieldType.DELAY_FIELD, value: "{{setInterval()}}", testId: "text-view-label", }, { field: FieldType.ID_FIELD, value: "{{setInterval()}}", testId: "text-view-label", }, { field: FieldType.CLEAR_INTERVAL_ID_FIELD, value: "{{clearInterval()}}", testId: "text-view-label", }, { field: FieldType.PAGE_NAME_AND_URL_TAB_SELECTOR_FIELD, value: "{{navigateTo('', {}, 'SAME_WINDOW')}}", testId: "tabs-label", }, { field: FieldType.URL_FIELD, value: "{{navigateTo('', {}, 'SAME_WINDOW')}}", testId: "text-view-label", }, { field: FieldType.DOWNLOAD_FILE_TYPE_FIELD, value: "{{download()}}", testId: "selector-view-label", }, { field: FieldType.PAGE_SELECTOR_FIELD, value: "{{navigateTo('', {}, 'SAME_WINDOW')}}", testId: "selector-view-label", }, { field: FieldType.CLOSE_MODAL_FIELD, value: "{{closeModal()}}", testId: "selector-view-label", }, { field: FieldType.SHOW_MODAL_FIELD, value: "{{showModal()}}", testId: "selector-view-label", }, ]; it("renders the component", () => { const props = { value: "{{download()}}", ...commonProps, field: { field: FieldType.DOWNLOAD_FILE_TYPE_FIELD, }, }; render( <ThemeProvider theme={lightTheme}> <Field {...props} /> </ThemeProvider>, ); }); test.each(tests.map((x, index) => [index, x.field, x.value, x.testId]))( "test case %d", (index, field, value, testId) => { const props = { ...commonProps, field: { field: field as FieldType, }, value: value as string, }; const expectedLabel = FIELD_CONFIG[field as FieldType].label(props); const expectedDefaultText = FIELD_CONFIG[field as FieldType].defaultText; render( <ThemeProvider theme={lightTheme}> <Field {...props} /> </ThemeProvider>, ); if (testId && expectedLabel) { expect(screen.getByTestId(testId)).toHaveTextContent(expectedLabel); } if (expectedDefaultText) { expect(screen.getByText(expectedDefaultText)).toBeInTheDocument(); } }, ); });
9,596
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/ActionCreator
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/ActionCreator/FieldGroup/FieldGroupConfig.test.ts
import { FIELD_GROUP_CONFIG } from "./FieldGroupConfig"; import { AppsmithFunction, FieldType } from "../constants"; describe("Test Field Group Config", () => { const cases = [ { index: 0, input: AppsmithFunction.none, expectedLabel: "No action", expectedFields: [], }, { index: 1, input: AppsmithFunction.integration, expectedLabel: "Execute a query", expectedFields: [FieldType.PARAMS_FIELD], }, { index: 2, input: AppsmithFunction.jsFunction, expectedLabel: "Execute a JS function", expectedFields: [], }, { index: 3, input: AppsmithFunction.navigateTo, expectedLabel: "Navigate to", expectedFields: [ FieldType.PAGE_NAME_AND_URL_TAB_SELECTOR_FIELD, FieldType.PAGE_SELECTOR_FIELD, FieldType.QUERY_PARAMS_FIELD, FieldType.NAVIGATION_TARGET_FIELD, ], }, { index: 4, input: AppsmithFunction.showAlert, expectedLabel: "Show alert", expectedFields: [ FieldType.ALERT_TEXT_FIELD, FieldType.ALERT_TYPE_SELECTOR_FIELD, ], }, { index: 5, input: AppsmithFunction.showModal, expectedLabel: "Show modal", expectedFields: [FieldType.SHOW_MODAL_FIELD], }, { index: 6, input: AppsmithFunction.closeModal, expectedLabel: "Close modal", expectedFields: [FieldType.CLOSE_MODAL_FIELD], }, { index: 7, input: AppsmithFunction.storeValue, expectedLabel: "Store value", expectedFields: [ FieldType.KEY_TEXT_FIELD_STORE_VALUE, FieldType.VALUE_TEXT_FIELD, ], }, { index: 8, input: AppsmithFunction.download, expectedLabel: "Download", expectedFields: [ FieldType.DOWNLOAD_DATA_FIELD, FieldType.DOWNLOAD_FILE_NAME_FIELD, FieldType.DOWNLOAD_FILE_TYPE_FIELD, ], }, { index: 9, input: AppsmithFunction.copyToClipboard, expectedLabel: "Copy to clipboard", expectedFields: [FieldType.COPY_TEXT_FIELD], }, { index: 10, input: AppsmithFunction.resetWidget, expectedLabel: "Reset widget", expectedFields: [ FieldType.WIDGET_NAME_FIELD, FieldType.RESET_CHILDREN_FIELD, ], }, { index: 11, input: AppsmithFunction.setInterval, expectedLabel: "Set interval", expectedFields: [ FieldType.CALLBACK_FUNCTION_FIELD_SET_INTERVAL, FieldType.DELAY_FIELD, FieldType.ID_FIELD, ], }, { index: 12, input: AppsmithFunction.clearInterval, expectedLabel: "Clear interval", expectedFields: [FieldType.CLEAR_INTERVAL_ID_FIELD], }, { index: 13, input: AppsmithFunction.getGeolocation, expectedLabel: "Get geolocation", expectedFields: [FieldType.CALLBACK_FUNCTION_FIELD_GEOLOCATION], }, { index: 14, input: AppsmithFunction.watchGeolocation, expectedLabel: "Watch geolocation", expectedFields: [], }, { index: 15, input: AppsmithFunction.stopWatchGeolocation, expectedLabel: "Stop watching geolocation", expectedFields: [], }, ]; test.each( cases.map((x) => [x.index, x.input, x.expectedLabel, x.expectedFields]), )("test case %d", (index, input, expectedLabel, expectedFields) => { const result = FIELD_GROUP_CONFIG[input as string]; expect(result.label).toStrictEqual(expectedLabel as string); expect(result.fields).toStrictEqual(expectedFields as string[]); }); });
9,601
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/ActionCreator/viewComponents
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/ActionCreator/viewComponents/Action/ActionTree.test.tsx
import React from "react"; import { Provider } from "react-redux"; import { testStore } from "store"; import { ThemeProvider } from "styled-components"; import { lightTheme } from "selectors/themeSelectors"; import { render } from "@testing-library/react"; import ActionTree from "./ActionTree"; import type { TActionBlock } from "../../types"; import { APPSMITH_GLOBAL_FUNCTIONS } from "../../constants"; describe("tests for Action Tree in Action Selector", () => { const store = testStore({}); it("callback button is rendered for chainable actions", function () { const actionBlock: TActionBlock = { code: "showAlert('Hello')", actionType: APPSMITH_GLOBAL_FUNCTIONS.showAlert, success: { blocks: [], }, error: { blocks: [], }, }; const component = render( <Provider store={store}> <ThemeProvider theme={lightTheme}> <ActionTree actionBlock={actionBlock} dataTreePath="" id="xyz" level={0} onChange={() => { return; }} propertyName="" widgetName="" widgetType="" /> </ThemeProvider> </Provider>, ); const callbackBtn = component.queryByTestId("t--callback-btn-xyz"); expect(callbackBtn).not.toBeNull(); }); it("callback button should not be rendered for actions that are not chainable", function () { const actionBlock: TActionBlock = { code: "setInterval(() => showAlert('Hello'), 1000, 'test')", actionType: APPSMITH_GLOBAL_FUNCTIONS.setInterval, success: { blocks: [], }, error: { blocks: [], }, }; const component = render( <Provider store={store}> <ThemeProvider theme={lightTheme}> <ActionTree actionBlock={actionBlock} dataTreePath="" id="xyz" level={0} onChange={() => { return; }} propertyName="" widgetName="" widgetType="" /> </ThemeProvider> </Provider>, ); const callbackBtn = component.queryByTestId("t--callback-btn-xyz"); expect(callbackBtn).toBeNull(); }); });
9,607
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/ActionCreator/viewComponents
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/ActionCreator/viewComponents/SelectorView/SelectorView.test.tsx
import React from "react"; import "@testing-library/jest-dom"; import { render, screen } from "test/testUtils"; import type { SelectorViewProps } from "../../types"; import { SelectorView } from "./index"; describe("Selector view component", () => { const props: SelectorViewProps = { options: [ { label: "Page1", id: "632c1d6244562f5051a7f36b", value: "'Page1'", }, ], label: "Choose page", value: "{{navigateTo('Page1', {}, 'SAME_WINDOW')}}", defaultText: "Select page", displayValue: "", get: () => { return 1; }, set: () => { return 1; }, }; test("Renders selector view component correctly", () => { render(<SelectorView {...props} />); expect(screen.getByTestId("selector-view-label")).toHaveTextContent( "Choose page", ); }); });
9,609
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/ActionCreator/viewComponents
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/ActionCreator/viewComponents/TabView/TabView.test.tsx
import React from "react"; import "@testing-library/jest-dom"; import { render, screen } from "test/testUtils"; import { TabView } from "./index"; import type { TabViewProps } from "../../types"; describe("Tab View component", () => { const props: TabViewProps = { label: "Type", activeObj: { id: "page-name", text: "Page name", action: () => { return 1; }, }, switches: [ { id: "page-name", text: "Page name", action: () => { return 1; }, }, { id: "url", text: "URL", // eslint-disable-next-line @typescript-eslint/no-empty-function action: () => {}, }, ], value: "{{navigateTo('Page1', {}, 'SAME_WINDOW'}}", }; test("Renders Tab view component correctly", () => { render(<TabView {...props} />); expect(screen.getByTestId("tabs-label")).toHaveTextContent("Type"); }); });
9,611
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/ActionCreator/viewComponents
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/ActionCreator/viewComponents/TextView/TextView.test.tsx
import React from "react"; import "@testing-library/jest-dom"; import { render, screen } from "test/testUtils"; import { TextView } from "./index"; import type { TextViewProps } from "../../types"; describe("Text view component", () => { const props: TextViewProps = { label: "Key", value: "{{storeValue(,'1')}}", get: () => { return ""; }, set: () => { return 1; }, exampleText: "storeValue('a','1')", }; test("Renders Text view component correctly", () => { render(<TextView {...props} />); expect(screen.getByTestId("text-view-label")).toHaveTextContent("Key"); }); });
9,617
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/CodeEditor/BindingPromptHelper.test.ts
import { showBindingPrompt } from "./BindingPromptHelper"; describe("Test to check conditons for showing binding prompt", () => { it("Show binding prompt", () => { const testCases = [ { showEvaluatedValue: true, inputValue: "{" }, { showEvaluatedValue: true, inputValue: "Some value" }, { showEvaluatedValue: true, inputValue: "1" }, { showEvaluatedValue: true, inputValue: "[1, 2, 3]" }, { showEvaluatedValue: true, inputValue: "" }, { showEvaluatedValue: true, inputValue: [1, 2, 3] }, { showEvaluatedValue: true, inputValue: 1 }, { showEvaluatedValue: true, inputValue: null }, { showEvaluatedValue: true, inputValue: undefined }, ]; testCases.forEach((testCase) => { expect( showBindingPrompt( testCase.showEvaluatedValue, testCase.inputValue, false, ), ).toBeTruthy(); }); }); it("Hide binding prompt", () => { const testCases = [ { showEvaluatedValue: false, inputValue: "" }, { showEvaluatedValue: false, inputValue: 1 }, { showEvaluatedValue: false, inputValue: null }, { showEvaluatedValue: false, inputValue: undefined }, { showEvaluatedValue: true, inputValue: "Name: {{Widget.name}}" }, { showEvaluatedValue: true, inputValue: "{{}}" }, ]; testCases.forEach((testCase) => { expect( showBindingPrompt( testCase.showEvaluatedValue, testCase.inputValue, false, ), ).toBeFalsy(); }); }); });
9,619
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/CodeEditor/CodeEditor.test.tsx
import CodeEditor from "./index"; import store from "store"; import TestRenderer from "react-test-renderer"; import React from "react"; import { Provider } from "react-redux"; import EvaluatedValuePopup from "./EvaluatedValuePopup"; import { ThemeProvider } from "styled-components"; import { theme, light } from "constants/DefaultTheme"; import { EditorSize, EditorTheme, TabBehaviour, EditorModes, } from "./EditorConfig"; describe("CodeEditor", () => { it("should check EvaluatedValuePopup's hideEvaluatedValue is false when hideEvaluatedValue is passed as false to codeditor", () => { const finalTheme = { ...theme, colors: { ...theme.colors, ...light } }; const testRenderer = TestRenderer.create( <Provider store={store}> <ThemeProvider theme={finalTheme}> <CodeEditor additionalDynamicData={{}} hideEvaluatedValue={false} input={{ value: "", onChange: () => { // }, }} mode={EditorModes.TEXT} size={EditorSize.COMPACT} tabBehaviour={TabBehaviour.INDENT} theme={EditorTheme.LIGHT} /> </ThemeProvider> </Provider>, ); const testInstance = testRenderer.root; expect( testInstance.findByType(EvaluatedValuePopup).props.hideEvaluatedValue, ).toBe(false); }); it("should check EvaluatedValuePopup's hideEvaluatedValue is true when hideEvaluatedValue is passed as true to codeditor", () => { const finalTheme = { ...theme, colors: { ...theme.colors, ...light } }; const testRenderer = TestRenderer.create( <Provider store={store}> <ThemeProvider theme={finalTheme}> <CodeEditor additionalDynamicData={{}} hideEvaluatedValue input={{ value: "", onChange: () => { // }, }} mode={EditorModes.TEXT} size={EditorSize.COMPACT} tabBehaviour={TabBehaviour.INDENT} theme={EditorTheme.LIGHT} /> </ThemeProvider> </Provider>, ); const testInstance = testRenderer.root; expect( testInstance.findByType(EvaluatedValuePopup).props.hideEvaluatedValue, ).toBe(true); }); });
9,621
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/CodeEditor/EvaluatedValuePopup.test.tsx
import store from "store"; import React from "react"; import { ThemeProvider } from "styled-components"; import { Provider } from "react-redux"; import { render, screen } from "@testing-library/react"; import EvaluatedValuePopup from "./EvaluatedValuePopup"; import { theme } from "constants/DefaultTheme"; import { EditorTheme } from "./EditorConfig"; describe("EvaluatedValuePopup", () => { it("should render evaluated popup when hideEvaluatedValue is false", () => { render( <Provider store={store}> <ThemeProvider theme={theme}> <EvaluatedValuePopup errors={[]} hasError={false} hideEvaluatedValue={false} isOpen theme={EditorTheme.LIGHT} > <div>children</div> </EvaluatedValuePopup> </ThemeProvider> </Provider>, ); const input = screen.queryByTestId("evaluated-value-popup-title"); expect(input).toBeTruthy(); }); it("should not render evaluated popup when hideEvaluatedValue is true", () => { render( <Provider store={store}> <ThemeProvider theme={theme}> <EvaluatedValuePopup errors={[]} hasError={false} hideEvaluatedValue isOpen theme={EditorTheme.LIGHT} > <div>children</div> </EvaluatedValuePopup> </ThemeProvider> </Provider>, ); const input = screen.queryByTestId("evaluated-value-popup-title"); expect(input).toBeNull(); }); });
9,625
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/CodeEditor/codeEditorUtils.test.ts
import { removeNewLineChars, getInputValue, removeNewLineCharsIfRequired, } from "./codeEditorUtils"; import { EditorSize } from "./EditorConfig"; describe("remove new line code", () => { it("removed new lines", () => { const input = `ab\ncd`; const output = "abcd"; expect(removeNewLineChars(input)).toEqual(output); }); }); describe("input has to be in string", () => { it("convert input value into string", () => { const inputObject = { name: "apeksha", lastname: "bhosale", }; const outputOfObject = getInputValue(inputObject); expect(typeof outputOfObject).toEqual("string"); const inputNumber = 1234; const outputOfNumber = getInputValue(inputNumber); expect(typeof outputOfNumber).toEqual("string"); const inputString = "abcd"; const outputOfString = getInputValue(inputString); expect(typeof outputOfString).toEqual("string"); }); }); describe("Bug 18709: remove new line code if required", () => { it("dont remove new lines in case of header/param values", () => { const input = `{{\nInput1.text\n}}`; const output = "{{\nInput1.text\n}}"; expect( removeNewLineCharsIfRequired(input, EditorSize.COMPACT_RETAIN_FORMATTING), ).toEqual(output); }); it("remove new lines if required", () => { const input = `{{\nInput1.text\n}}`; const output = "{{Input1.text}}"; expect(removeNewLineCharsIfRequired(input, EditorSize.COMPACT)).toEqual( output, ); }); });
9,630
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/CodeEditor/hintHelpers.test.ts
import { bindingHintHelper, SqlHintHelper, } from "components/editorComponents/CodeEditor/hintHelpers"; import { MockCodemirrorEditor } from "../../../../test/__mocks__/CodeMirrorEditorMock"; import { random } from "lodash"; import "codemirror/addon/hint/sql-hint"; import { MAX_NUMBER_OF_SQL_HINTS } from "./utils/sqlHint"; jest.mock("./codeEditorUtils", () => { const actualExports = jest.requireActual("./codeEditorUtils"); return { __esModule: true, ...actualExports, isCursorOnEmptyToken: jest.fn(() => false), }; }); function generateRandomTable() { const table: Record<string, string> = {}; for (let i = 0; i < 500; i++) { table[`T${random(0, 1000)}`] = "string"; } return table; } jest.mock("utils/getCodeMirrorNamespace", () => { const actual = jest.requireActual("utils/getCodeMirrorNamespace"); return { ...actual, getCodeMirrorNamespaceFromDoc: jest.fn((doc) => ({ ...actual.getCodeMirrorNamespaceFromDoc(doc), innerMode: jest.fn(() => ({ mode: { name: "", }, state: { lexical: {}, }, })), })), }; }); describe("hint helpers", () => { describe("binding hint helper", () => { it("is initialized correctly", () => { // @ts-expect-error: Types are not available const helper = bindingHintHelper(MockCodemirrorEditor, {}); expect(MockCodemirrorEditor.setOption).toBeCalled(); expect(helper).toHaveProperty("showHint"); }); it("opens hint correctly", () => { // Setup interface Case { value: string; cursor: { ch: number; line: number }; toCall: "closeHint" | "showHint"; getLine?: string[]; } const cases: Case[] = [ { value: "ABC", cursor: { ch: 3, line: 0 }, toCall: "closeHint" }, { value: "{{ }}", cursor: { ch: 3, line: 0 }, toCall: "showHint" }, { value: '{ name: "{{}}" }', cursor: { ch: 11, line: 0 }, toCall: "showHint", }, { value: '{ name: "{{}}" }', cursor: { ch: 12, line: 0 }, toCall: "closeHint", }, { value: "{somethingIsHere }}", cursor: { ch: 18, line: 0 }, toCall: "closeHint", }, { value: `{\n\tname: "{{}}"\n}`, getLine: ["{", `\tname: "{{}}`, "}"], cursor: { ch: 10, line: 1 }, toCall: "showHint", }, { value: "{test(", cursor: { ch: 1, line: 0 }, toCall: "closeHint", }, { value: "justanystring {{}}", cursor: { ch: 16, line: 0 }, toCall: "showHint", }, ]; cases.forEach((testCase) => { MockCodemirrorEditor.getValue.mockReturnValueOnce(testCase.value); MockCodemirrorEditor.getCursor.mockReturnValue(testCase.cursor); if (testCase.getLine) { testCase.getLine.forEach((line) => { MockCodemirrorEditor.getLine.mockReturnValueOnce(line); }); } MockCodemirrorEditor.getTokenAt.mockReturnValueOnce({ type: "string", string: "", }); MockCodemirrorEditor.getDoc.mockReturnValueOnce({ getCursor: () => testCase.cursor, somethingSelected: () => false, getValue: () => testCase.value, getEditor: () => MockCodemirrorEditor, } as unknown as CodeMirror.Doc); // @ts-expect-error: Types are not available const helper = bindingHintHelper(MockCodemirrorEditor, {}); // @ts-expect-error: Types are not available helper.showHint(MockCodemirrorEditor); }); // Assert const showHintCount = cases.filter((c) => c.toCall === "showHint").length; expect(MockCodemirrorEditor.showHint).toHaveBeenCalledTimes( showHintCount, ); const closeHintCount = cases.filter( (c) => c.toCall === "closeHint", ).length; expect(MockCodemirrorEditor.closeHint).toHaveBeenCalledTimes( closeHintCount, ); }); }); describe("SQL hinter", () => { const hinter = new SqlHintHelper(); const randomTable = generateRandomTable(); hinter.setDatasourceTableKeys(randomTable); jest.spyOn(hinter, "getCompletions").mockImplementation(() => ({ from: { line: 1, ch: 1 }, to: { line: 1, ch: 1 }, list: Object.keys(randomTable), })); it("returns no hint when not in SQL mode", () => { jest.spyOn(hinter, "isSqlMode").mockImplementationOnce(() => false); // @ts-expect-error: actual editor is not required const response = hinter.handleCompletions({}); expect(response.completions).toBe(null); }); it("returns hints when in SQL mode", () => { jest.spyOn(hinter, "isSqlMode").mockImplementationOnce(() => true); // @ts-expect-error: actual editor is not required const response = hinter.handleCompletions({}); expect(response.completions?.list).toBeTruthy(); }); it("Doesn't return hints greater than the threshold", () => { jest.spyOn(hinter, "isSqlMode").mockImplementationOnce(() => true); // @ts-expect-error: actual editor is not required const response = hinter.handleCompletions({}); expect(response.completions?.list.length).toBeLessThanOrEqual( MAX_NUMBER_OF_SQL_HINTS, ); }); }); });
9,632
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/CodeEditor/index.test.tsx
import React from "react"; import { Provider } from "react-redux"; import { ThemeProvider } from "styled-components"; import "@testing-library/jest-dom"; import { render, screen } from "@testing-library/react"; import { lightTheme } from "selectors/themeSelectors"; import userEvent from "@testing-library/user-event"; import store from "store"; import CodeEditor from "./index"; import { EditorSize, EditorTheme, TabBehaviour, EditorModes, } from "./EditorConfig"; describe("<CodeEditor /> - Keyboard navigation", () => { // To avoid warning "Error: Not implemented: window.focus" window.focus = jest.fn(); const getTestComponent = (handleOnSelect: any = undefined) => ( <Provider store={store}> <ThemeProvider theme={lightTheme}> <CodeEditor additionalDynamicData={{}} hideEvaluatedValue={false} input={{ value: "", onChange: handleOnSelect, }} mode={EditorModes.TEXT} size={EditorSize.COMPACT} tabBehaviour={TabBehaviour.INDENT} theme={EditorTheme.LIGHT} /> </ThemeProvider> </Provider> ); it("Pressing tab should focus the component", () => { render(getTestComponent()); userEvent.tab(); expect(screen.getByTestId("code-editor-target")).toHaveFocus(); }); });
9,634
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/CodeEditor/lintHelpers.test.ts
import { Severity } from "entities/AppsmithConsole"; import type { LintError } from "utils/DynamicBindingUtils"; import { PropertyEvaluationErrorType } from "utils/DynamicBindingUtils"; import { INVALID_JSOBJECT_START_STATEMENT, INVALID_JSOBJECT_START_STATEMENT_ERROR_CODE, } from "plugins/Linting/constants"; import { CODE_EDITOR_START_POSITION } from "./constants"; import { getKeyPositionInString, getLintAnnotations, getAllWordOccurrences, getFirstNonEmptyPosition, } from "./lintHelpers"; describe("getAllWordOccurences()", function () { it("should get all the indexes", () => { const res = getAllWordOccurrences("this is a `this` string", "this"); expect(res).toEqual([0, 11]); }); it("should return empty array", () => { expect(getAllWordOccurrences("this is a string", "number")).toEqual([]); }); }); describe("getKeyPositionsInString()", () => { it("should return results for single line string", () => { const res = getKeyPositionInString("this is a `this` string", "this"); expect(res).toEqual([ { line: 0, ch: 0 }, { line: 0, ch: 11 }, ]); }); it("should return results for multiline string", () => { const res = getKeyPositionInString("this is a \n`this` string", "this"); expect(res).toEqual([ { line: 0, ch: 0 }, { line: 1, ch: 1 }, ]); }); }); describe("getLintAnnotations()", () => { const { LINT } = PropertyEvaluationErrorType; const { ERROR, WARNING } = Severity; it("should return proper annotations", () => { const value1 = `Hello {{ world == test }}`; const errors1: LintError[] = [ { errorType: LINT, raw: "\n function closedFunction () {\n const result = world == test \n return result;\n }\n closedFunction()\n ", severity: WARNING, errorMessage: { name: "LintingError", message: "Expected '===' and instead saw '=='.", }, errorSegment: " const result = world == test ", originalBinding: " world == test ", variables: ["===", "==", null, null], code: "W116", line: 0, ch: 8, }, { errorType: LINT, raw: "\n function closedFunction () {\n const result = world == test \n return result;\n }\n closedFunction()\n ", severity: WARNING, errorMessage: { name: "LintingError", message: "'world' is not defined.", }, errorSegment: " const result = world == test ", originalBinding: " world == test ", variables: ["world", null, null, null], code: "W117", line: 0, ch: 2, }, { errorMessage: { name: "LintingError", message: "'test' is not defined.", }, severity: WARNING, raw: "\n function closedFunction () {\n const result = world == test \n return result;\n }\n closedFunction()\n ", errorType: LINT, originalBinding: " world == test ", errorSegment: " const result = world == test ", variables: ["test", null, null, null], code: "W117", line: 0, ch: 11, }, ]; const res1 = getLintAnnotations(value1, errors1, {}); expect(res1).toEqual([ { from: { line: 0, ch: 15, }, to: { line: 0, ch: 17, }, message: "Expected '===' and instead saw '=='.", severity: "warning", }, { from: { line: 0, ch: 9, }, to: { line: 0, ch: 14, }, message: "'world' is not defined.", severity: "warning", }, { from: { line: 0, ch: 18, }, to: { line: 0, ch: 22, }, message: "'test' is not defined.", severity: "warning", }, ]); /// 2 const value2 = `hss{{hss}}`; const errors2: LintError[] = [ { errorType: LINT, raw: "\n function closedFunction () {\n const result = hss\n return result;\n }\n closedFunction.call(THIS_CONTEXT)\n ", severity: ERROR, errorMessage: { name: "LintingError", message: "'hss' is not defined.", }, errorSegment: " const result = hss", originalBinding: "{{hss}}", variables: ["hss", null, null, null], code: "W117", line: 0, ch: 1, }, ]; const res2 = getLintAnnotations(value2, errors2, {}); expect(res2).toEqual([ { from: { line: 0, ch: 5, }, to: { line: 0, ch: 8, }, message: "'hss' is not defined.", severity: "error", }, ]); }); it("should return correct annotation with newline in original binding", () => { const value = `Hello {{ world }}`; const errors: LintError[] = [ { errorType: LINT, raw: "\n function closedFunction () {\n const result = world\n\n return result;\n }\n closedFunction()\n ", severity: ERROR, errorMessage: { name: "LintingError", message: "'world' is not defined.", }, errorSegment: " const result = world", originalBinding: " world\n", variables: ["world", null, null, null], code: "W117", line: 0, ch: 2, }, ]; const res = getLintAnnotations(value, errors, {}); expect(res).toEqual([ { from: { line: 0, ch: 9, }, to: { line: 0, ch: 14, }, message: "'world' is not defined.", severity: "error", }, ]); }); it("should return proper annotation when jsobject does not start with expected statement", () => { const value = `// An invalid JS Object export default { } `; const errors: LintError[] = [ { errorType: PropertyEvaluationErrorType.LINT, errorSegment: "", originalBinding: value, line: 0, ch: 0, code: INVALID_JSOBJECT_START_STATEMENT_ERROR_CODE, variables: [], raw: value, errorMessage: { name: "LintingError", message: INVALID_JSOBJECT_START_STATEMENT, }, severity: Severity.ERROR, }, ]; const res = getLintAnnotations(value, errors, { isJSObject: true }); expect(res).toEqual([ { from: { line: 0, ch: 0, }, to: { line: 0, ch: 23, }, message: "JSObject must start with 'export default'", severity: "error", }, ]); }); }); describe("getFirstNonEmptyPosition", () => { it("should return valid first non-empty position", () => { const lines1 = ["", "export default{", "myFun1:()=> 1"]; const lines2 = ["export default{", "myFun1:()=> 1"]; const lines3: string[] = []; const expectedPosition1 = { line: 1, ch: 15, }; const expectedPosition2 = { line: 0, ch: 15, }; const expectedPosition3 = CODE_EDITOR_START_POSITION; const actualPosition1 = getFirstNonEmptyPosition(lines1); const actualPosition2 = getFirstNonEmptyPosition(lines2); const actualPosition3 = getFirstNonEmptyPosition(lines3); expect(expectedPosition1).toEqual(actualPosition1); expect(expectedPosition2).toEqual(actualPosition2); expect(expectedPosition3).toEqual(actualPosition3); }); });
9,650
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/CodeEditor
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/CodeEditor/utils/codeComments.test.ts
import CodeMirror from "codemirror"; import "components/editorComponents/CodeEditor/modes"; import "codemirror/addon/comment/comment"; import { EditorModes } from "../EditorConfig"; import { handleCodeComment } from "./codeComment"; const JS_LINE_COMMENT = "//"; const SQL_LINE_COMMENT = "--"; describe("handleCodeComment", () => { it("should handle code comment for single line", () => { const editor = CodeMirror(document.body, { mode: EditorModes.JAVASCRIPT }); const code = `const a = 1;`; editor.setValue(code); // Select the code before commenting editor.setSelection( { line: 0, ch: 0 }, { line: editor.lastLine() + 1, ch: 0 }, ); handleCodeComment(JS_LINE_COMMENT)(editor); expect(editor.getValue()).toEqual(`// const a = 1;`); }); it("should handle code comment for multiple lines", () => { const editor = CodeMirror(document.body, { mode: EditorModes.JAVASCRIPT }); const code = `const a = 1; const b = 2;`; editor.setValue(code); // Select the code before commenting editor.setSelection( { line: 0, ch: 0 }, { line: editor.lastLine() + 1, ch: 0 }, ); handleCodeComment(JS_LINE_COMMENT)(editor); expect(editor.getValue()).toEqual(`// const a = 1; // const b = 2;`); }); it("should handle code uncomment for multiple lines", () => { const editor = CodeMirror(document.body, { mode: EditorModes.JAVASCRIPT }); const code = `// const a = 1; // const b = 2;`; editor.setValue(code); // Select the code before commenting editor.setSelection( { line: 0, ch: 0 }, { line: editor.lastLine() + 1, ch: 0 }, ); handleCodeComment(JS_LINE_COMMENT)(editor); expect(editor.getValue()).toEqual(`const a = 1; const b = 2;`); }); it("should handle code comment for multiple lines in between", () => { const editor = CodeMirror(document.body, { mode: EditorModes.JAVASCRIPT }); const code = `const a = 1; const b = 2; const c = 3; const d = 4;`; editor.setValue(code); // Select the code before commenting editor.setSelection({ line: 1, ch: 0 }, { line: 3, ch: 0 }); handleCodeComment(JS_LINE_COMMENT)(editor); expect(editor.getValue()).toEqual(`const a = 1; // const b = 2; // const c = 3; const d = 4;`); }); it("should not code comment for JS fields with plain text only", () => { const editor = CodeMirror(document.body, { mode: EditorModes.TEXT_WITH_BINDING, }); const code = `hello world`; editor.setValue(code); // Select the code before commenting editor.setSelection( { line: 0, ch: 0 }, { line: editor.lastLine() + 1, ch: 0 }, ); handleCodeComment(JS_LINE_COMMENT)(editor); expect(editor.getValue()).toEqual(`hello world`); }); it("should handle code uncomment for JS fields with plain text", () => { const editor = CodeMirror(document.body, { mode: EditorModes.TEXT_WITH_BINDING, }); const code = `// hello world`; editor.setValue(code); // Select the code before commenting editor.setSelection( { line: 0, ch: 0 }, { line: editor.lastLine() + 1, ch: 0 }, ); handleCodeComment(JS_LINE_COMMENT)(editor); expect(editor.getValue()).toEqual(`hello world`); }); it("should handle code comment in JS fields with single line", () => { const editor = CodeMirror(document.body, { mode: EditorModes.JAVASCRIPT }); const code = `{{ appsmith.store.id }}`; editor.setValue(code); // Select the code before commenting editor.setSelection( { line: 0, ch: 0 }, { line: editor.lastLine() + 1, ch: 0 }, ); handleCodeComment(JS_LINE_COMMENT)(editor); expect(editor.getValue()).toEqual(`{{// appsmith.store.id }}`); }); it("should handle code comment in JS fields with text", () => { const editor = CodeMirror(document.body, { mode: EditorModes.JAVASCRIPT, }); const code = `Hello {{ appsmith.store.id }}`; editor.setValue(code); // Select the code before commenting editor.setSelection( { line: 0, ch: 0 }, { line: editor.lastLine() + 1, ch: 0 }, ); handleCodeComment(JS_LINE_COMMENT)(editor); expect(editor.getValue()).toEqual(`Hello {{// appsmith.store.id }}`); }); it("should handle code uncomment in JS fields with text", () => { const editor = CodeMirror(document.body, { mode: EditorModes.JAVASCRIPT, }); const code = `Hello {{// appsmith.store.id }}`; editor.setValue(code); // Select the code before commenting editor.setSelection( { line: 0, ch: 0 }, { line: editor.lastLine() + 1, ch: 0 }, ); handleCodeComment(JS_LINE_COMMENT)(editor); expect(editor.getValue()).toEqual(`Hello {{ appsmith.store.id }}`); }); it("should handle code comment in TEXT_WITH_BINDING fields with text", () => { const editor = CodeMirror(document.body, { mode: EditorModes.TEXT_WITH_BINDING, }); const code = `"label": {{ appsmith.store.id }}`; editor.setValue(code); // Select the code before commenting editor.setSelection( { line: 0, ch: 0 }, { line: editor.lastLine() + 1, ch: 0 }, ); handleCodeComment(JS_LINE_COMMENT)(editor); expect(editor.getValue()).toEqual(`"label": {{// appsmith.store.id }}`); }); it("should handle code comment in TEXT_WITH_BINDING fields with text in multiple lines", () => { const editor = CodeMirror(document.body, { mode: EditorModes.TEXT_WITH_BINDING, }); const code = `"label": {{ 2 + 2 }}`; editor.setValue(code); // Select the code before commenting editor.setSelection( { line: 1, ch: 0 }, { line: editor.lastLine() + 1, ch: 0 }, ); handleCodeComment(JS_LINE_COMMENT)(editor); expect(editor.getValue()).toEqual(`"label": {{ 2 // + 2 }}`); }); it("should handle code comment in JS fields with multiple lines", () => { const editor = CodeMirror(document.body, { mode: EditorModes.JAVASCRIPT }); const code = ` {{ (() => { const a = "hello"; return "Text"; })()}}`; editor.setValue(code); // Select the code before commenting editor.setSelection( { line: 0, ch: 0 }, { line: editor.lastLine() + 1, ch: 0 }, ); handleCodeComment(JS_LINE_COMMENT)(editor); expect(editor.getValue()).toEqual(` {{// (() => { // const a = "hello"; // return "Text"; // })()}}`); }); it("should handle code uncomment in JS fields with multiple lines", () => { const editor = CodeMirror(document.body, { mode: EditorModes.JAVASCRIPT }); const code = ` {{// (() => { // const a = "hello"; // return "Text"; // })()}}`; editor.setValue(code); // Select the code before commenting editor.setSelection( { line: 0, ch: 0 }, { line: editor.lastLine() + 1, ch: 0 }, ); handleCodeComment(JS_LINE_COMMENT)(editor); expect(editor.getValue()).toEqual(` {{(() => { const a = "hello"; return "Text"; })()}}`); }); it("should handle code comment for SQL queries", () => { const editor = CodeMirror(document.body, { mode: EditorModes.SQL, }); const code = `Select * from users;`; editor.setValue(code); // Select the code before commenting editor.setSelection( { line: 0, ch: 0 }, { line: editor.lastLine() + 1, ch: 0 }, ); handleCodeComment(SQL_LINE_COMMENT)(editor); expect(editor.getValue()).toEqual(`-- Select * from users;`); }); it("should handle code comment for SQL queries with JS bindings when cursor is placed outside JS bindings", () => { const editor = CodeMirror(document.body, { mode: EditorModes.SQL, }); const code = `Select * from users where name={{Select.selectedOptionValue}};`; editor.setValue(code); // Select the code before commenting editor.setSelection( { line: 0, ch: 0 }, { line: editor.lastLine() + 1, ch: 0 }, ); handleCodeComment(SQL_LINE_COMMENT)(editor); expect(editor.getValue()).toEqual( `-- Select * from users where name={{Select.selectedOptionValue}};`, ); }); it("should handle code comment for SQL queries with JS bindings when cursor is placed inside JS bindings", () => { const editor = CodeMirror(document.body, { mode: EditorModes.SQL, }); const code = `Select * from users where name={{Select.selectedOptionValue}};`; editor.setValue(code); // Select the code before commenting editor.setSelection( { line: 0, ch: 18 }, { line: editor.lastLine() + 1, ch: 0 }, ); handleCodeComment(SQL_LINE_COMMENT)(editor); expect(editor.getValue()).toEqual( `-- Select * from users where name={{Select.selectedOptionValue}};`, ); }); });
9,672
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/Debugger/helpers.test.ts
import type { DependencyMap } from "utils/DynamicBindingUtils"; import { getDependenciesFromInverseDependencies, getDependencyChain, } from "./helpers"; describe("getDependencies", () => { it("Check if getDependencies returns in a correct format", () => { const input = { "Button1.text": ["Input1.defaultText", "Button1"], "Input1.defaultText": ["Input1.text", "Input1"], "Input1.inputType": ["Input1.isValid", "Input1"], "Input1.text": ["Input1.isValid", "Input1.value", "Input1"], "Input1.isRequired": ["Input1.isValid", "Input1"], "Input1.isValid": ["Button1.isVisible", "Input1"], "Button1.isVisible": ["Button1"], Button1: ["Chart1.chartName"], "Chart1.chartName": ["Chart1"], "Input1.value": ["Input1"], }; const output = { directDependencies: ["Input1"], inverseDependencies: ["Input1", "Chart1"], }; expect( getDependenciesFromInverseDependencies(input, "Button1"), ).toStrictEqual(output); }); it("Check if getDependencies returns correct dependencies when widget names are overlapping", () => { const input = { "SelectQuery.data": ["SelectQuery", "data_table.tableData"], "Input1.defaultText": ["Input1.text", "Input1"], "Input1.text": ["Input1.value", "Input1.isValid", "Input1"], "Input1.inputType": ["Input1.isValid", "Input1"], "Input1.isRequired": ["Input1.isValid", "Input1"], "Input1.isValid": ["Input1"], "Input1.value": ["Input1"], "data_table.defaultSelectedRow": [ "data_table.selectedRowIndex", "data_table.selectedRowIndices", "data_table", ], "data_table.selectedRowIndex": [ "Form1.isVisible", "data_table.selectedRow", "data_table", ], "Form1.isVisible": ["Form1"], "col_text_2.text": ["col_text_2.value", "col_text_2"], "col_text_2.value": ["col_text_2"], "col_text_1.text": ["col_text_1.value", "col_text_1"], "col_text_1.value": ["col_text_1"], "data_table.tableData": [ "data_table.sanitizedTableData", "insert_col_input5.placeholderText", "insert_col_input2.placeholderText", "insert_col_input1.placeholderText", "data_table", ], "data_table.defaultSearchText": ["data_table.searchText", "data_table"], "data_table.sanitizedTableData": [ "data_table.primaryColumns.Description.computedValue", "data_table.primaryColumns.Name.computedValue", "data_table.primaryColumns.rowIndex.computedValue", "data_table.primaryColumns.customColumn1.buttonLabel", "data_table.tableColumns", "data_table.filteredTableData", "data_table.selectedRow", "data_table.selectedRows", "data_table", ], "data_table.primaryColumns.Description.computedValue": [ "data_table.primaryColumns.Description", ], "data_table.primaryColumns.Name.computedValue": [ "data_table.primaryColumns.Name", ], "data_table.primaryColumns.rowIndex.computedValue": [ "data_table.primaryColumns.rowIndex", ], "data_table.primaryColumns.customColumn1.buttonLabel": [ "data_table.primaryColumns.customColumn1", ], "data_table.primaryColumns.customColumn1": ["data_table.primaryColumns"], "data_table.primaryColumns.rowIndex": ["data_table.primaryColumns"], "data_table.primaryColumns.Name": ["data_table.primaryColumns"], "data_table.primaryColumns.Description": ["data_table.primaryColumns"], "data_table.primaryColumns": [ "data_table.tableColumns", "data_table.filteredTableData", "data_table", ], "data_table.sortOrder.column": [ "data_table.tableColumns", "data_table.filteredTableData", "data_table.sortOrder", ], "data_table.sortOrder.order": [ "data_table.tableColumns", "data_table.filteredTableData", "data_table.sortOrder", ], "data_table.columnOrder": ["data_table.tableColumns", "data_table"], "data_table.derivedColumns": [ "data_table.filteredTableData", "data_table", ], "data_table.tableColumns": ["data_table.filteredTableData", "data_table"], "data_table.searchText": ["data_table.filteredTableData", "data_table"], "data_table.filters": ["data_table.filteredTableData", "data_table"], "data_table.filteredTableData": [ "data_table.selectedRow", "data_table.selectedRows", "data_table", ], "data_table.selectedRow": ["colInput1.defaultText", "data_table"], "colInput1.defaultText": ["colInput1.text", "colInput1"], "colInput1.text": ["colInput1.value", "colInput1.isValid", "colInput1"], "colInput1.validation": ["colInput1.isValid", "colInput1"], "colInput1.inputType": ["colInput1.isValid", "colInput1"], "colInput1.isRequired": ["colInput1.isValid", "colInput1"], "colInput1.isValid": ["colInput1"], "colInput1.value": ["colInput1"], "Text13.text": ["Text13.value", "Text13"], "Text13.value": ["Text13"], "insert_col_input5.defaultText": [ "insert_col_input5.text", "insert_col_input5", ], "insert_col_input5.text": [ "insert_col_input5.value", "insert_col_input5.isValid", "insert_col_input5", ], "insert_col_input5.validation": [ "insert_col_input5.isValid", "insert_col_input5", ], "insert_col_input5.inputType": [ "insert_col_input5.isValid", "insert_col_input5", ], "insert_col_input5.isRequired": [ "insert_col_input5.isValid", "insert_col_input5", ], "insert_col_input5.placeholderText": ["insert_col_input5"], "insert_col_input5.isValid": ["insert_col_input5"], "insert_col_input5.value": ["insert_col_input5"], "Text24.text": ["Text24.value", "Text24"], "Text24.value": ["Text24"], "insert_col_input2.defaultText": [ "insert_col_input2.text", "insert_col_input2", ], "insert_col_input2.text": [ "insert_col_input2.value", "insert_col_input2.isValid", "insert_col_input2", ], "insert_col_input2.validation": [ "insert_col_input2.isValid", "insert_col_input2", ], "insert_col_input2.inputType": [ "insert_col_input2.isValid", "insert_col_input2", ], "insert_col_input2.isRequired": [ "insert_col_input2.isValid", "insert_col_input2", ], "insert_col_input2.placeholderText": ["insert_col_input2"], "insert_col_input2.isValid": ["insert_col_input2"], "insert_col_input2.value": ["insert_col_input2"], "Text22.text": ["Text22.value", "Text22"], "Text22.value": ["Text22"], "insert_col_input1.defaultText": [ "insert_col_input1.text", "insert_col_input1", ], "insert_col_input1.text": [ "insert_col_input1.value", "insert_col_input1.isValid", "insert_col_input1", ], "insert_col_input1.validation": [ "insert_col_input1.isValid", "insert_col_input1", ], "insert_col_input1.inputType": [ "insert_col_input1.isValid", "insert_col_input1", ], "insert_col_input1.isRequired": [ "insert_col_input1.isValid", "insert_col_input1", ], "insert_col_input1.placeholderText": ["insert_col_input1"], "insert_col_input1.isValid": ["insert_col_input1"], "insert_col_input1.value": ["insert_col_input1"], "Text21.text": ["Text21.value", "Text21"], "Text21.value": ["Text21"], "Text12.text": ["Text12.value", "Text12"], "Text12.value": ["Text12"], "delete_button.buttonStyle": [ "delete_button.prevButtonStyle", "delete_button", ], "delete_button.prevButtonStyle": ["delete_button"], "Button1.buttonStyle": ["Button1.prevButtonStyle", "Button1"], "Button1.prevButtonStyle": ["Button1"], "Text11.text": ["Text11.value", "Text11"], "Text11.value": ["Text11"], "Text16.text": ["Text16.value", "Text16"], "Text16.value": ["Text16"], "data_table.bottomRow": ["data_table.pageSize", "data_table"], "data_table.topRow": ["data_table.pageSize", "data_table"], "data_table.parentRowSpace": ["data_table.pageSize", "data_table"], "data_table.selectedRowIndices": [ "data_table.selectedRows", "data_table", ], "data_table.selectedRows": ["data_table"], "data_table.pageSize": ["data_table"], "data_table.triggerRowSelection": ["data_table"], "data_table.sortOrder": ["data_table"], }; const output = { directDependencies: [], inverseDependencies: [], }; expect( getDependenciesFromInverseDependencies(input, "Input1"), ).toStrictEqual(output); }); it("Get dependency chain", () => { const inputs: string[] = [ "Button1.text", "DatePicker1.value", "regulationsTable.tableData", ]; const inverseDependencies: DependencyMap[] = [ { "Button1.text": ["Input1.defaultText", "Button1"], "Input1.defaultText": ["Checkbox1.label", "Input1.text", "Input1"], "Checkbox1.LEFT": ["Checkbox1.alignWidget", "Checkbox1"], "Checkbox1.defaultCheckedState": ["Checkbox1.isChecked", "Checkbox1"], "Checkbox1.isRequired": ["Checkbox1.isValid", "Checkbox1"], "Checkbox1.isChecked": [ "Checkbox1.isValid", "Checkbox1.value", "Checkbox1", ], "Checkbox1.value": ["Checkbox1"], "Checkbox1.isValid": ["Checkbox1"], "Checkbox1.alignWidget": ["Checkbox1"], "Checkbox1.label": ["Checkbox1"], "Input1.text": ["Input1.value", "Input1.isValid", "Input1"], "Input1.inputType": ["Input1.isValid", "Input1"], "Input1.isRequired": ["Input1.isValid", "Input1"], "Input1.isValid": ["Input1"], "Input1.value": ["Input1"], }, { "DatePicker1.defaultDate": [ "DatePicker1.value", "DatePicker1.selectedDate", "DatePicker1.formattedDate", "DatePicker1", ], "DatePicker1.value": [ "DatePicker1.selectedDate", "DatePicker1.formattedDate", "DatePicker1", ], "DatePicker1.selectedDate": [ "Text1.text", "DatePicker1.isValid", "DatePicker1", ], "Text1.text": ["Text1.value", "Text1"], "Text1.value": ["Text1"], "DatePicker1.dateFormat": ["DatePicker1.formattedDate", "DatePicker1"], "DatePicker1.isRequired": ["DatePicker1.isValid", "DatePicker1"], "DatePicker1.isValid": ["DatePicker1"], "DatePicker1.formattedDate": ["DatePicker1"], }, { "get_cert_scopes.data": ["get_cert_scopes", "certScopeSelect.options"], "appsmith.store": [ "Tabs1.defaultTab", "regionOrCountry.defaultOptionValue", "regulationsTable.defaultSelectedRow", "regionOrCountrySelect.defaultOptionValue", "appsmith", "certScopeSelect.defaultOptionValue", ], "Tabs1.selectedTabWidgetId": ["Tabs1.selectedTab", "Tabs1"], "Tabs1.tabsObj": ["Tabs1.selectedTab", "Tabs1"], "Tabs1.defaultTab": ["Tabs1.selectedTab", "Tabs1"], "regionOrCountry.meta.selectedOptionValue": [ "regionOrCountry.selectedOptionValue", "regionOrCountry.meta", ], "regionOrCountry.defaultOptionValue": [ "regionOrCountry.selectedOptionValue", "regionOrCountry", ], "regionOrCountry.selectedOptionValue": [ "regulationsTable.tableData", "Button3CopyCopyCopy1.isDisabled", "Button3CopyCopy.isDisabled", "regionOrCountrySelect.defaultOptionValue", "regionOrCountrySelect.options", "Button8.isDisabled", "Button6Copy.isDisabled", "Button5Copy.isDisabled", "regionOrCountry.value", "regionOrCountry.isValid", "regionOrCountry.selectedOption", "regionOrCountry", "Default.update_regulations", "Default.add_regulation", "regionOrCountrySelect.isVisible", "regionOrCountrySelect.placeholderText", ], "get_regulation_by_country.data": [ "regulationsTable.tableData", "get_regulation_by_country", ], "get_regulation_by_region.data": [ "regulationsTable.tableData", "get_regulation_by_region", ], "regulationsTable.tableData": [ "regulationsTable.sanitizedTableData", "regulationsTable", ], "regulationsTable.meta.searchText": [ "regulationsTable.searchText", "regulationsTable.meta", ], "regulationsTable.defaultSearchText": [ "regulationsTable.searchText", "regulationsTable", ], "regulationsTable.sanitizedTableData": [ "regulationsTable.primaryColumns.region.isCellVisible", "regulationsTable.primaryColumns.region.computedValue", "regulationsTable.primaryColumns.parameters.computedValue", "regulationsTable.primaryColumns.country.computedValue", "regulationsTable.primaryColumns.external_version.computedValue", "regulationsTable.primaryColumns.status.computedValue", "regulationsTable.primaryColumns.reqs.computedValue", "regulationsTable.primaryColumns._rev.computedValue", "regulationsTable.primaryColumns.name.computedValue", "regulationsTable.primaryColumns.description.computedValue", "regulationsTable.primaryColumns.created_at.computedValue", "regulationsTable.primaryColumns._id.computedValue", "regulationsTable.primaryColumns._key.computedValue", "regulationsTable.tableColumns", "regulationsTable.filteredTableData", "regulationsTable.selectedRow", "regulationsTable.selectedRows", "regulationsTable.triggeredRow", "regulationsTable", ], "regulationsTable.primaryColumns.region.computedValue": [ "regulationsTable.primaryColumns.region", ], "regulationsTable.primaryColumns.region.isCellVisible": [ "regulationsTable.primaryColumns.region", ], "regulationsTable.primaryColumns.parameters.computedValue": [ "regulationsTable.primaryColumns.parameters", ], "regulationsTable.primaryColumns.country.computedValue": [ "regulationsTable.primaryColumns.country", ], "regulationsTable.primaryColumns.external_version.computedValue": [ "regulationsTable.primaryColumns.external_version", ], "regulationsTable.primaryColumns.status.computedValue": [ "regulationsTable.primaryColumns.status", ], "regulationsTable.primaryColumns.reqs.computedValue": [ "regulationsTable.primaryColumns.reqs", ], "regulationsTable.primaryColumns._rev.computedValue": [ "regulationsTable.primaryColumns._rev", ], "regulationsTable.primaryColumns.name.computedValue": [ "regulationsTable.primaryColumns.name", ], "regulationsTable.primaryColumns.description.computedValue": [ "regulationsTable.primaryColumns.description", ], "regulationsTable.primaryColumns.created_at.computedValue": [ "regulationsTable.primaryColumns.created_at", ], "regulationsTable.primaryColumns._id.computedValue": [ "regulationsTable.primaryColumns._id", ], "regulationsTable.primaryColumns._key.computedValue": [ "regulationsTable.primaryColumns._key", ], "regulationsTable.primaryColumns._key": [ "regulationsTable.primaryColumns", ], "regulationsTable.primaryColumns._id": [ "regulationsTable.primaryColumns", ], "regulationsTable.primaryColumns.created_at": [ "regulationsTable.primaryColumns", ], "regulationsTable.primaryColumns.description": [ "regulationsTable.primaryColumns", ], "regulationsTable.primaryColumns.name": [ "regulationsTable.primaryColumns", ], "regulationsTable.primaryColumns._rev": [ "regulationsTable.primaryColumns", ], "regulationsTable.primaryColumns.reqs": [ "regulationsTable.primaryColumns", ], "regulationsTable.primaryColumns.status": [ "regulationsTable.primaryColumns", ], "regulationsTable.primaryColumns.external_version": [ "regulationsTable.primaryColumns", ], "regulationsTable.primaryColumns.country": [ "regulationsTable.primaryColumns", ], "regulationsTable.primaryColumns.parameters": [ "regulationsTable.primaryColumns", ], "regulationsTable.primaryColumns.region": [ "regulationsTable.primaryColumns", ], "regulationsTable.primaryColumns": [ "regulationsTable.tableColumns", "regulationsTable.filteredTableData", "regulationsTable", ], "regulationsTable.sortOrder.column": [ "regulationsTable.tableColumns", "regulationsTable.filteredTableData", "regulationsTable.sortOrder", ], "regulationsTable.sortOrder.order": [ "regulationsTable.tableColumns", "regulationsTable.filteredTableData", "regulationsTable.sortOrder", ], "regulationsTable.columnOrder": [ "regulationsTable.tableColumns", "regulationsTable", ], "regulationsTable.derivedColumns": [ "regulationsTable.filteredTableData", "regulationsTable", ], "regulationsTable.primaryColumnId": [ "regulationsTable.filteredTableData", "regulationsTable", ], "regulationsTable.tableColumns": [ "regulationsTable.filteredTableData", "regulationsTable", ], "regulationsTable.searchText": [ "regulationsTable.filteredTableData", "regulationsTable", ], "regulationsTable.enableClientSideSearch": [ "regulationsTable.filteredTableData", "regulationsTable", ], "regulationsTable.filters": [ "regulationsTable.filteredTableData", "regulationsTable", ], "regulationsTable.meta.selectedRowIndex": [ "regulationsTable.selectedRowIndex", "regulationsTable.meta", ], "regulationsTable.defaultSelectedRow": [ "regulationsTable.selectedRowIndex", "regulationsTable.selectedRowIndices", "regulationsTable", ], "regulationsTable.meta.selectedRowIndices": [ "regulationsTable.selectedRowIndices", "regulationsTable.meta", ], "regulationsTable.selectedRowIndices": [ "regulationsTable.selectedRow", "regulationsTable.selectedRows", "regulationsTable", ], "regulationsTable.multiRowSelection": [ "regulationsTable.selectedRow", "regulationsTable", ], "regulationsTable.selectedRowIndex": [ "regulationsTable.selectedRow", "regulationsTable", ], "regulationsTable.filteredTableData": [ "regulationsTable.selectedRow", "regulationsTable.selectedRows", "regulationsTable", ], "regulationsTable.selectedRow": [ "Tabs1.isVisible", "Button3CopyCopyCopy1.isDisabled", "ParamsTable.tableData", "Button3CopyCopyCopy1Copy.isDisabled", "Button5CopyCopy1.isDisabled", "Button3CopyCopy.isDisabled", "Button8.isDisabled", "Button6Copy.isDisabled", "Button5Copy.isDisabled", "Default.add_requirement", "Default.delete_regulation_parameter", "Default.edit_parameter", "Default.add_parameter", "edit_regulation_params.config.body", "extVersionEditRegulation.defaultText", "descEditRegulation.defaultText", "nameEditRegulation.defaultText", "edit_regulation.config.body", "get_requirements.config.body", "regulationsTable", "get_system_approvals.config.body", ], "appsmith.theme.boxShadow.appBoxShadow": [ "Tabs1.boxShadow", "Container1.boxShadow", "RegulationsContaiter.boxShadow", "headerCopy2.boxShadow", "appsmith.theme.boxShadow", "ParamsTable.boxShadow", "regulationsTable.boxShadow", "RequirementsTable.boxShadow", ], "appsmith.theme.borderRadius.appBorderRadius": [ "Tabs1.borderRadius", "Canvas12.borderRadius", "Button3CopyCopyCopy1.borderRadius", "Button3CopyCopyCopy1Copy.borderRadius", "Button5CopyCopy1.borderRadius", "Canvas10.borderRadius", "Button3CopyCopy.borderRadius", "Button8Copy1.borderRadius", "Button5CopyCopy.borderRadius", "Button6CopyCopy.borderRadius", "Container1.borderRadius", "Canvas8.borderRadius", "Image1.borderRadius", "CreateTypeFormCopy.borderRadius", "Button4.borderRadius", "descCreateCertScope.borderRadius", "nameCreateCertScope.borderRadius", "IconButton3CopyCopyCopyCopy.borderRadius", "CreateTypeFormCopyCopy.borderRadius", "Button10.borderRadius", "IconButton3CopyCopyCopyCopyCopy.borderRadius", "CreateTypeFormCopyCopy1.borderRadius", "submitCopyCopy1.borderRadius", "IconButton3CopyCopyCopyCopyCopy1.borderRadius", "EditRegulationModal.borderRadius", "IconButton3Copy1CopyCopy2.borderRadius", "EditTypeFormCopy2.borderRadius", "Button9.borderRadius", "CreateTypeFormCopyCopy3.borderRadius", "label.borderRadius", "descCreateCertScopeCopy.borderRadius", "nameCreateCertScopeCopy.borderRadius", "submitCopyCopy3.borderRadius", "IconButton3CopyCopyCopyCopyCopy3.borderRadius", "CreateTypeFormCopyCopy1Copy.borderRadius", "Button11.borderRadius", "closeSystemApprovalModal.borderRadius", "RegulationsContaiter.borderRadius", "Button8.borderRadius", "Button6Copy.borderRadius", "Button5Copy.borderRadius", "Button3Copy.borderRadius", "CreateTypeFormCopyCopyCopy.borderRadius", "Button10Copy.borderRadius", "IconButton3CopyCopyCopyCopyCopyCopy.borderRadius", "CreateTypeFormCopyCopyCopy1.borderRadius", "Button10Copy1.borderRadius", "kindCreateRequirementCopy.borderRadius", "descCreateRequirementCopy.borderRadius", "nameCreateRequirementCopy.borderRadius", "IconButton3CopyCopyCopyCopyCopyCopy1.borderRadius", "CreateTypeFormCopyCopy1CopyCopy.borderRadius", "Button11Copy.borderRadius", "closeSystemApprovalModalCopy.borderRadius", "headerCopy2.borderRadius", "Canvas9.borderRadius", "Button2Copy24.borderRadius", "Button2Copy12.borderRadius", "Button2Copy23.borderRadius", "Button2Copy22.borderRadius", "Button2Copy2Copy2.borderRadius", "Button2CopyCopy.borderRadius", "Button2CopyCopyCopy.borderRadius", "Button2Copy25.borderRadius", "CreateTypeFormCopyCopyCopy2.borderRadius", "Button10Copy2.borderRadius", "IconButton3CopyCopyCopyCopyCopyCopy2.borderRadius", "CreateTypeFormCopyCopyCopy2Copy.borderRadius", "Button10Copy2Copy.borderRadius", "IconButton3CopyCopyCopyCopyCopyCopy2Copy.borderRadius", "appsmith.theme.borderRadius", "unitEditParameter.borderRadius", "descEditParameter.borderRadius", "nameEditParameter.borderRadius", "ParamsTable.borderRadius", "unitCreateParameter.borderRadius", "descCreateParameter.borderRadius", "nameCreateParameter.borderRadius", "extVersionEditRegulation.borderRadius", "descEditRegulation.borderRadius", "nameEditRegulation.borderRadius", "descEditSystemApproval.borderRadius", "nameEditSystemApproval.borderRadius", "kindEditRequirement.borderRadius", "descEditRequirement.borderRadius", "nameEditRequirement.borderRadius", "regionOrCountrySelect.borderRadius", "certScopeSelect.borderRadius", "descCreateSystemApproval.borderRadius", "nameCreateSystemApproval.borderRadius", "extVersionCreateRegulation.borderRadius", "descCreateRegulation.borderRadius", "nameCreateRegulation.borderRadius", "kindCreateRequirement.borderRadius", "descCreateRequirement.borderRadius", "nameCreateRequirement.borderRadius", "regulationsTable.borderRadius", "RequirementsTable.borderRadius", ], "appsmith.theme.colors.primaryColor": [ "Tabs1.accentColor", "Canvas12.accentColor", "Canvas10.accentColor", "Button6CopyCopy.buttonColor", "Canvas8.accentColor", "Button4.buttonColor", "descCreateCertScope.accentColor", "nameCreateCertScope.accentColor", "IconButton3CopyCopyCopyCopy.buttonColor", "Button10.buttonColor", "IconButton3CopyCopyCopyCopyCopy.buttonColor", "submitCopyCopy1.buttonColor", "IconButton3CopyCopyCopyCopyCopy1.buttonColor", "IconButton3Copy1CopyCopy2.buttonColor", "Button9.buttonColor", "label.accentColor", "descCreateCertScopeCopy.accentColor", "nameCreateCertScopeCopy.accentColor", "submitCopyCopy3.buttonColor", "IconButton3CopyCopyCopyCopyCopy3.buttonColor", "Button11.buttonColor", "closeSystemApprovalModal.buttonColor", "Button6Copy.buttonColor", "Button10Copy.buttonColor", "IconButton3CopyCopyCopyCopyCopyCopy.buttonColor", "Button10Copy1.buttonColor", "kindCreateRequirementCopy.accentColor", "descCreateRequirementCopy.accentColor", "nameCreateRequirementCopy.accentColor", "IconButton3CopyCopyCopyCopyCopyCopy1.buttonColor", "Button11Copy.buttonColor", "closeSystemApprovalModalCopy.buttonColor", "Canvas9.accentColor", "Button2Copy24.buttonColor", "Button2Copy12.buttonColor", "Button2Copy23.buttonColor", "Button2Copy22.buttonColor", "Button2Copy2Copy2.buttonColor", "Button2CopyCopy.buttonColor", "Button2CopyCopyCopy.buttonColor", "Button2Copy25.buttonColor", "Button10Copy2.buttonColor", "IconButton3CopyCopyCopyCopyCopyCopy2.buttonColor", "Button10Copy2Copy.buttonColor", "IconButton3CopyCopyCopyCopyCopyCopy2Copy.buttonColor", "appsmith.theme.colors", "unitEditParameter.accentColor", "descEditParameter.accentColor", "nameEditParameter.accentColor", "ParamsTable.accentColor", "regionOrCountry.accentColor", "unitCreateParameter.accentColor", "descCreateParameter.accentColor", "nameCreateParameter.accentColor", "extVersionEditRegulation.accentColor", "descEditRegulation.accentColor", "nameEditRegulation.accentColor", "descEditSystemApproval.accentColor", "nameEditSystemApproval.accentColor", "kindEditRequirement.accentColor", "descEditRequirement.accentColor", "nameEditRequirement.accentColor", "regionOrCountrySelect.accentColor", "certScopeSelect.accentColor", "descCreateSystemApproval.accentColor", "nameCreateSystemApproval.accentColor", "extVersionCreateRegulation.accentColor", "descCreateRegulation.accentColor", "nameCreateRegulation.accentColor", "kindCreateRequirement.accentColor", "descCreateRequirement.accentColor", "nameCreateRequirement.accentColor", "regulationsTable.accentColor", "RequirementsTable.accentColor", ], "Tabs1.onTabSelected": ["Tabs1"], "Tabs1.accentColor": ["Tabs1"], "Tabs1.borderRadius": ["Tabs1"], "Tabs1.boxShadow": ["Tabs1"], "Tabs1.isVisible": ["Tabs1"], "Tabs1.selectedTab": ["Tabs1"], "Canvas12.borderRadius": ["Canvas12"], "Canvas12.accentColor": ["Canvas12"], "Button3CopyCopyCopy1.onClick": ["Button3CopyCopyCopy1"], "Button3CopyCopyCopy1.borderRadius": ["Button3CopyCopyCopy1"], "Button3CopyCopyCopy1.isDisabled": ["Button3CopyCopyCopy1"], "ParamsTable.tableData": [ "ParamsTable.sanitizedTableData", "ParamsTable", ], "ParamsTable.sanitizedTableData": [ "ParamsTable.derivedColumns.customColumn1.computedValue", "ParamsTable.primaryColumns.unit.computedValue", "ParamsTable.primaryColumns.customColumn1.computedValue", "ParamsTable.primaryColumns.unit_doc.computedValue", "ParamsTable.primaryColumns.id.computedValue", "ParamsTable.primaryColumns.name.computedValue", "ParamsTable.primaryColumns.description.computedValue", "ParamsTable.tableColumns", "ParamsTable.filteredTableData", "ParamsTable.selectedRow", "ParamsTable.selectedRows", "ParamsTable.triggeredRow", "ParamsTable", ], "ParamsTable.derivedColumns.customColumn1.computedValue": [ "ParamsTable.derivedColumns.customColumn1", ], "ParamsTable.primaryColumns.unit.computedValue": [ "ParamsTable.primaryColumns.unit", ], "ParamsTable.primaryColumns.customColumn1.computedValue": [ "ParamsTable.primaryColumns.customColumn1", ], "ParamsTable.primaryColumns.unit_doc.computedValue": [ "ParamsTable.primaryColumns.unit_doc", ], "ParamsTable.primaryColumns.id.computedValue": [ "ParamsTable.primaryColumns.id", ], "ParamsTable.primaryColumns.name.computedValue": [ "ParamsTable.primaryColumns.name", ], "ParamsTable.primaryColumns.description.computedValue": [ "ParamsTable.primaryColumns.description", ], "ParamsTable.meta.searchText": [ "ParamsTable.searchText", "ParamsTable.meta", ], "ParamsTable.defaultSearchText": [ "ParamsTable.searchText", "ParamsTable", ], "ParamsTable.primaryColumns.description": [ "ParamsTable.primaryColumns", ], "ParamsTable.primaryColumns.name": ["ParamsTable.primaryColumns"], "ParamsTable.primaryColumns.id": ["ParamsTable.primaryColumns"], "ParamsTable.primaryColumns.unit_doc": ["ParamsTable.primaryColumns"], "ParamsTable.primaryColumns.customColumn1": [ "ParamsTable.primaryColumns", ], "ParamsTable.primaryColumns.unit": ["ParamsTable.primaryColumns"], "ParamsTable.primaryColumns": [ "ParamsTable.tableColumns", "ParamsTable.filteredTableData", "ParamsTable", ], "ParamsTable.sortOrder.column": [ "ParamsTable.tableColumns", "ParamsTable.filteredTableData", "ParamsTable.sortOrder", ], "ParamsTable.sortOrder.order": [ "ParamsTable.tableColumns", "ParamsTable.filteredTableData", "ParamsTable.sortOrder", ], "ParamsTable.columnOrder": ["ParamsTable.tableColumns", "ParamsTable"], "ParamsTable.derivedColumns.customColumn1": [ "ParamsTable.derivedColumns", ], "ParamsTable.derivedColumns": [ "ParamsTable.filteredTableData", "ParamsTable", ], "ParamsTable.primaryColumnId": [ "ParamsTable.filteredTableData", "ParamsTable", ], "ParamsTable.tableColumns": [ "ParamsTable.filteredTableData", "ParamsTable", ], "ParamsTable.searchText": [ "ParamsTable.filteredTableData", "ParamsTable", ], "ParamsTable.enableClientSideSearch": [ "ParamsTable.filteredTableData", "ParamsTable", ], "ParamsTable.filters": ["ParamsTable.filteredTableData", "ParamsTable"], "ParamsTable.meta.selectedRowIndex": [ "ParamsTable.selectedRowIndex", "ParamsTable.meta", ], "ParamsTable.defaultSelectedRow": [ "ParamsTable.selectedRowIndex", "ParamsTable.selectedRowIndices", "ParamsTable", ], "ParamsTable.meta.selectedRowIndices": [ "ParamsTable.selectedRowIndices", "ParamsTable.meta", ], "ParamsTable.selectedRowIndices": [ "ParamsTable.selectedRow", "ParamsTable.selectedRows", "ParamsTable", ], "ParamsTable.multiRowSelection": [ "ParamsTable.selectedRow", "ParamsTable", ], "ParamsTable.selectedRowIndex": [ "ParamsTable.selectedRow", "ParamsTable", ], "ParamsTable.filteredTableData": [ "ParamsTable.selectedRow", "ParamsTable.selectedRows", "ParamsTable", ], "ParamsTable.selectedRow": [ "Button3CopyCopyCopy1Copy.isDisabled", "Button5CopyCopy1.isDisabled", "Text5CopyCopy1CopyCopyCopy2Copy.text", "unitEditParameter.defaultOptionValue", "descEditParameter.defaultText", "nameEditParameter.defaultText", "ParamsTable", "Default.delete_regulation_parameter", "Default.edit_parameter", ], "Button3CopyCopyCopy1Copy.onClick": ["Button3CopyCopyCopy1Copy"], "Button3CopyCopyCopy1Copy.borderRadius": ["Button3CopyCopyCopy1Copy"], "Button3CopyCopyCopy1Copy.isDisabled": ["Button3CopyCopyCopy1Copy"], "Button5CopyCopy1.onClick": ["Button5CopyCopy1"], "Button5CopyCopy1.borderRadius": ["Button5CopyCopy1"], "Button5CopyCopy1.isDisabled": ["Button5CopyCopy1"], "Canvas10.borderRadius": ["Canvas10"], "Canvas10.accentColor": ["Canvas10"], "get_requirements.data": [ "RequirementsTable.tableData", "get_requirements", ], "RequirementsTable.tableData": [ "RequirementsTable.sanitizedTableData", "RequirementsTable", ], "RequirementsTable.sanitizedTableData": [ "RequirementsTable.primaryColumns.kind.computedValue", "RequirementsTable.primaryColumns.status.computedValue", "RequirementsTable.primaryColumns._rev.computedValue", "RequirementsTable.primaryColumns.name.computedValue", "RequirementsTable.primaryColumns.description.computedValue", "RequirementsTable.primaryColumns.created_at.computedValue", "RequirementsTable.primaryColumns._id.computedValue", "RequirementsTable.primaryColumns._key.computedValue", "RequirementsTable.tableColumns", "RequirementsTable.filteredTableData", "RequirementsTable.selectedRow", "RequirementsTable.selectedRows", "RequirementsTable.triggeredRow", "RequirementsTable", ], "RequirementsTable.primaryColumns.kind.computedValue": [ "RequirementsTable.primaryColumns.kind", ], "RequirementsTable.primaryColumns.status.computedValue": [ "RequirementsTable.primaryColumns.status", ], "RequirementsTable.primaryColumns._rev.computedValue": [ "RequirementsTable.primaryColumns._rev", ], "RequirementsTable.primaryColumns.name.computedValue": [ "RequirementsTable.primaryColumns.name", ], "RequirementsTable.primaryColumns.description.computedValue": [ "RequirementsTable.primaryColumns.description", ], "RequirementsTable.primaryColumns.created_at.computedValue": [ "RequirementsTable.primaryColumns.created_at", ], "RequirementsTable.primaryColumns._id.computedValue": [ "RequirementsTable.primaryColumns._id", ], "RequirementsTable.primaryColumns._key.computedValue": [ "RequirementsTable.primaryColumns._key", ], "Button3CopyCopy.onClick": ["Button3CopyCopy"], "Button3CopyCopy.borderRadius": ["Button3CopyCopy"], "Button3CopyCopy.isDisabled": ["Button3CopyCopy"], "RequirementsTable.meta.searchText": [ "RequirementsTable.searchText", "RequirementsTable.meta", ], "RequirementsTable.defaultSearchText": [ "RequirementsTable.searchText", "RequirementsTable", ], "RequirementsTable.primaryColumns._key": [ "RequirementsTable.primaryColumns", ], "RequirementsTable.primaryColumns._id": [ "RequirementsTable.primaryColumns", ], "RequirementsTable.primaryColumns.created_at": [ "RequirementsTable.primaryColumns", ], "RequirementsTable.primaryColumns.description": [ "RequirementsTable.primaryColumns", ], "RequirementsTable.primaryColumns.name": [ "RequirementsTable.primaryColumns", ], "RequirementsTable.primaryColumns._rev": [ "RequirementsTable.primaryColumns", ], "RequirementsTable.primaryColumns.status": [ "RequirementsTable.primaryColumns", ], "RequirementsTable.primaryColumns.kind": [ "RequirementsTable.primaryColumns", ], "RequirementsTable.primaryColumns": [ "RequirementsTable.tableColumns", "RequirementsTable.filteredTableData", "RequirementsTable", ], "RequirementsTable.sortOrder.column": [ "RequirementsTable.tableColumns", "RequirementsTable.filteredTableData", "RequirementsTable.sortOrder", ], "RequirementsTable.sortOrder.order": [ "RequirementsTable.tableColumns", "RequirementsTable.filteredTableData", "RequirementsTable.sortOrder", ], "RequirementsTable.columnOrder": [ "RequirementsTable.tableColumns", "RequirementsTable", ], "RequirementsTable.derivedColumns": [ "RequirementsTable.filteredTableData", "RequirementsTable", ], "RequirementsTable.primaryColumnId": [ "RequirementsTable.filteredTableData", "RequirementsTable", ], "RequirementsTable.tableColumns": [ "RequirementsTable.filteredTableData", "RequirementsTable", ], "RequirementsTable.searchText": [ "RequirementsTable.filteredTableData", "RequirementsTable", ], "RequirementsTable.enableClientSideSearch": [ "RequirementsTable.filteredTableData", "RequirementsTable", ], "RequirementsTable.filters": [ "RequirementsTable.filteredTableData", "RequirementsTable", ], "RequirementsTable.meta.selectedRowIndex": [ "RequirementsTable.selectedRowIndex", "RequirementsTable.meta", ], "RequirementsTable.defaultSelectedRow": [ "RequirementsTable.selectedRowIndex", "RequirementsTable.selectedRowIndices", "RequirementsTable", ], "RequirementsTable.meta.selectedRowIndices": [ "RequirementsTable.selectedRowIndices", "RequirementsTable.meta", ], "RequirementsTable.selectedRowIndices": [ "RequirementsTable.selectedRow", "RequirementsTable.selectedRows", "RequirementsTable", ], "RequirementsTable.multiRowSelection": [ "RequirementsTable.selectedRow", "RequirementsTable", ], "RequirementsTable.selectedRowIndex": [ "RequirementsTable.selectedRow", "Button8Copy1.isDisabled", "Button5CopyCopy.isDisabled", "Button6CopyCopy.isDisabled", "RequirementsTable", ], "RequirementsTable.filteredTableData": [ "RequirementsTable.selectedRow", "RequirementsTable.selectedRows", "RequirementsTable", ], "RequirementsTable.selectedRow": [ "Button8Copy1.isDisabled", "Button5CopyCopy.isDisabled", "Button6CopyCopy.isDisabled", "kindEditRequirement.defaultOptionValue", "descEditRequirement.defaultText", "nameEditRequirement.defaultText", "edit_requirement.config.body", "RequirementsTable", ], "Button8Copy1.onClick": ["Button8Copy1"], "Button8Copy1.borderRadius": ["Button8Copy1"], "Button8Copy1.isDisabled": ["Button8Copy1"], "Button5CopyCopy.onClick": ["Button5CopyCopy"], "Button5CopyCopy.borderRadius": ["Button5CopyCopy"], "Button5CopyCopy.isDisabled": ["Button5CopyCopy"], "Button6CopyCopy.onClick": ["Button6CopyCopy"], "Button6CopyCopy.buttonColor": ["Button6CopyCopy"], "Button6CopyCopy.borderRadius": ["Button6CopyCopy"], "Button6CopyCopy.isDisabled": ["Button6CopyCopy"], "Container1.borderRadius": ["Container1"], "Container1.boxShadow": ["Container1"], "Canvas8.borderRadius": ["Canvas8"], "Canvas8.accentColor": ["Canvas8"], "Image1.borderRadius": ["Image1"], "CreateCertScopeModal.onClose": ["CreateCertScopeModal"], "CreateTypeFormCopy.borderRadius": ["CreateTypeFormCopy"], "descCreateCertScope.meta.text": [ "descCreateCertScope.text", "descCreateCertScope.meta", ], "descCreateCertScope.defaultText": [ "descCreateCertScope.text", "descCreateCertScope.inputText", "descCreateCertScope", ], "nameCreateCertScope.meta.text": [ "nameCreateCertScope.text", "nameCreateCertScope.meta", ], "nameCreateCertScope.defaultText": [ "nameCreateCertScope.text", "nameCreateCertScope.inputText", "nameCreateCertScope", ], "nameCreateCertScope.text": [ "Button4.isDisabled", "nameCreateCertScope.value", "nameCreateCertScope", ], "descCreateCertScope.text": [ "Button4.isDisabled", "descCreateCertScope.value", "descCreateCertScope", ], "Button4.onClick": ["Button4"], "Button4.buttonColor": ["Button4"], "Button4.borderRadius": ["Button4"], "Button4.isDisabled": ["Button4"], "descCreateCertScope.meta.inputText": [ "descCreateCertScope.meta", "descCreateCertScope.inputText", ], "descCreateCertScope.inputType": [ "descCreateCertScope.isValid", "descCreateCertScope", ], "descCreateCertScope.inputText": [ "descCreateCertScope.isValid", "descCreateCertScope", ], "descCreateCertScope.isRequired": [ "descCreateCertScope.isValid", "descCreateCertScope", ], "descCreateCertScope.meta": ["descCreateCertScope"], "descCreateCertScope.accentColor": ["descCreateCertScope"], "descCreateCertScope.borderRadius": ["descCreateCertScope"], "descCreateCertScope.value": ["descCreateCertScope"], "descCreateCertScope.isValid": ["descCreateCertScope"], "nameCreateCertScope.meta.inputText": [ "nameCreateCertScope.meta", "nameCreateCertScope.inputText", ], "nameCreateCertScope.inputType": [ "nameCreateCertScope.isValid", "nameCreateCertScope", ], "nameCreateCertScope.inputText": [ "nameCreateCertScope.isValid", "nameCreateCertScope", ], "nameCreateCertScope.isRequired": [ "nameCreateCertScope.isValid", "nameCreateCertScope", ], "nameCreateCertScope.meta": ["nameCreateCertScope"], "nameCreateCertScope.accentColor": ["nameCreateCertScope"], "nameCreateCertScope.borderRadius": ["nameCreateCertScope"], "nameCreateCertScope.value": ["nameCreateCertScope"], "nameCreateCertScope.isValid": ["nameCreateCertScope"], "Text5CopyCopy1Copy.text": [ "Text5CopyCopy1Copy.value", "Text5CopyCopy1Copy", ], "appsmith.theme.fontFamily.appFont": [ "Text5CopyCopy1Copy.fontFamily", "Text5CopyCopy1CopyCopy.fontFamily", "Text5CopyCopy1CopyCopy1.fontFamily", "Text5CopyCopyCopyCopy2.fontFamily", "Text5CopyCopy1CopyCopy3.fontFamily", "CreateSystemApprText.fontFamily", "Text5CopyCopy1CopyCopyCopy.fontFamily", "Text5CopyCopy1CopyCopyCopy1.fontFamily", "CreateSystemApprTextCopy.fontFamily", "Text5CopyCopy1CopyCopyCopy2.fontFamily", "Text5CopyCopy1CopyCopyCopy2Copy.fontFamily", "appsmith.theme.fontFamily", ], "Text5CopyCopy1Copy.fontFamily": ["Text5CopyCopy1Copy"], "Text5CopyCopy1Copy.value": ["Text5CopyCopy1Copy"], "IconButton3CopyCopyCopyCopy.buttonColor": [ "IconButton3CopyCopyCopyCopy", ], "IconButton3CopyCopyCopyCopy.borderRadius": [ "IconButton3CopyCopyCopyCopy", ], "CreateRequirementModal.onClose": ["CreateRequirementModal"], "CreateTypeFormCopyCopy.borderRadius": ["CreateTypeFormCopyCopy"], "kindCreateRequirement.meta.value": [ "kindCreateRequirement.value", "kindCreateRequirement.meta", ], "kindCreateRequirement.defaultOptionValue": [ "kindCreateRequirement.value", "kindCreateRequirement.label", "kindCreateRequirement", ], "kindCreateRequirement.serverSideFiltering": [ "kindCreateRequirement.selectedOptionValue", "kindCreateRequirement.selectedOptionLabel", "kindCreateRequirement", ], "kindCreateRequirement.options": [ "kindCreateRequirement.selectedOptionValue", "kindCreateRequirement.selectedOptionLabel", "kindCreateRequirement", ], "kindCreateRequirement.value": [ "kindCreateRequirement.selectedOptionValue", "kindCreateRequirement", ], "kindCreateRequirement.isDirty": [ "kindCreateRequirement.selectedOptionValue", "kindCreateRequirement", ], "descCreateRequirement.meta.text": [ "descCreateRequirement.text", "descCreateRequirement.meta", ], "descCreateRequirement.defaultText": [ "descCreateRequirement.text", "descCreateRequirement.inputText", "descCreateRequirement", ], "nameCreateRequirement.meta.text": [ "nameCreateRequirement.text", "nameCreateRequirement.meta", ], "nameCreateRequirement.defaultText": [ "nameCreateRequirement.text", "nameCreateRequirement.inputText", "nameCreateRequirement", ], "nameCreateRequirement.text": [ "Button10.isDisabled", "Button10Copy1.isDisabled", "nameCreateRequirement.value", "nameCreateRequirement", "add_requirement.config.body", ], "descCreateRequirement.text": [ "Button10.isDisabled", "Button10Copy1.isDisabled", "descCreateRequirement.value", "descCreateRequirement", "add_requirement.config.body", ], "kindCreateRequirement.selectedOptionValue": [ "Button10.isDisabled", "Button10Copy1.isDisabled", "kindCreateRequirement.selectedOptionLabel", "kindCreateRequirement.isValid", "kindCreateRequirement", "add_requirement.config.body", ], "Button10.onClick": ["Button10"], "Button10.buttonColor": ["Button10"], "Button10.borderRadius": ["Button10"], "Button10.isDisabled": ["Button10"], "Text5CopyCopy1CopyCopy.text": [ "Text5CopyCopy1CopyCopy.value", "Text5CopyCopy1CopyCopy", ], "Text5CopyCopy1CopyCopy.fontFamily": ["Text5CopyCopy1CopyCopy"], "Text5CopyCopy1CopyCopy.value": ["Text5CopyCopy1CopyCopy"], "IconButton3CopyCopyCopyCopyCopy.buttonColor": [ "IconButton3CopyCopyCopyCopyCopy", ], "IconButton3CopyCopyCopyCopyCopy.borderRadius": [ "IconButton3CopyCopyCopyCopyCopy", ], "CreateRegulationModal.onClose": ["CreateRegulationModal"], "CreateTypeFormCopyCopy1.borderRadius": ["CreateTypeFormCopyCopy1"], "submitCopyCopy1.onClick": ["submitCopyCopy1"], "submitCopyCopy1.buttonColor": ["submitCopyCopy1"], "submitCopyCopy1.borderRadius": ["submitCopyCopy1"], "Text5CopyCopy1CopyCopy1.text": [ "Text5CopyCopy1CopyCopy1.value", "Text5CopyCopy1CopyCopy1", ], "Text5CopyCopy1CopyCopy1.fontFamily": ["Text5CopyCopy1CopyCopy1"], "Text5CopyCopy1CopyCopy1.value": ["Text5CopyCopy1CopyCopy1"], "IconButton3CopyCopyCopyCopyCopy1.buttonColor": [ "IconButton3CopyCopyCopyCopyCopy1", ], "IconButton3CopyCopyCopyCopyCopy1.borderRadius": [ "IconButton3CopyCopyCopyCopyCopy1", ], "EditRegulationModal.onClose": ["EditRegulationModal"], "EditRegulationModal.borderRadius": ["EditRegulationModal"], "IconButton3Copy1CopyCopy2.buttonColor": ["IconButton3Copy1CopyCopy2"], "IconButton3Copy1CopyCopy2.borderRadius": ["IconButton3Copy1CopyCopy2"], "EditTypeFormCopy2.borderRadius": ["EditTypeFormCopy2"], "Button9.onClick": ["Button9"], "Button9.buttonColor": ["Button9"], "Button9.borderRadius": ["Button9"], "Text5CopyCopyCopyCopy2.text": [ "Text5CopyCopyCopyCopy2.value", "Text5CopyCopyCopyCopy2", ], "Text5CopyCopyCopyCopy2.fontFamily": ["Text5CopyCopyCopyCopy2"], "Text5CopyCopyCopyCopy2.value": ["Text5CopyCopyCopyCopy2"], "CreateProductModal.onClose": ["CreateProductModal"], "CreateTypeFormCopyCopy3.borderRadius": ["CreateTypeFormCopyCopy3"], "label.meta.value": ["label.meta", "label.value"], "label.meta.label": ["label.meta", "label.label"], "label.meta.filterText": ["label.meta", "label.filterText"], "label.defaultOptionValue": ["label.value", "label.label", "label"], "label.serverSideFiltering": [ "label.selectedOptionValue", "label.selectedOptionLabel", "label", ], "label.options": [ "label.selectedOptionValue", "label.selectedOptionLabel", "label", ], "label.value": ["label.selectedOptionValue", "label"], "label.isDirty": ["label.selectedOptionValue", "label"], "label.label": ["label.selectedOptionLabel", "label"], "label.selectedOptionValue": [ "label.selectedOptionLabel", "label.isValid", "label", ], "label.isRequired": ["label.isValid", "label"], "label.meta": ["label"], "label.filterText": ["label"], "label.accentColor": ["label"], "label.borderRadius": ["label"], "label.isValid": ["label"], "label.selectedOptionLabel": ["label"], "descCreateCertScopeCopy.meta.inputText": [ "descCreateCertScopeCopy.meta", "descCreateCertScopeCopy.inputText", ], "descCreateCertScopeCopy.meta.text": [ "descCreateCertScopeCopy.meta", "descCreateCertScopeCopy.text", ], "descCreateCertScopeCopy.defaultText": [ "descCreateCertScopeCopy.inputText", "descCreateCertScopeCopy.text", "descCreateCertScopeCopy", ], "descCreateCertScopeCopy.inputType": [ "descCreateCertScopeCopy.isValid", "descCreateCertScopeCopy", ], "descCreateCertScopeCopy.inputText": [ "descCreateCertScopeCopy.isValid", "descCreateCertScopeCopy", ], "descCreateCertScopeCopy.isRequired": [ "descCreateCertScopeCopy.isValid", "descCreateCertScopeCopy", ], "descCreateCertScopeCopy.text": [ "descCreateCertScopeCopy.value", "descCreateCertScopeCopy", ], "descCreateCertScopeCopy.meta": ["descCreateCertScopeCopy"], "descCreateCertScopeCopy.accentColor": ["descCreateCertScopeCopy"], "descCreateCertScopeCopy.borderRadius": ["descCreateCertScopeCopy"], "descCreateCertScopeCopy.value": ["descCreateCertScopeCopy"], "descCreateCertScopeCopy.isValid": ["descCreateCertScopeCopy"], "nameCreateCertScopeCopy.meta.inputText": [ "nameCreateCertScopeCopy.meta", "nameCreateCertScopeCopy.inputText", ], "nameCreateCertScopeCopy.meta.text": [ "nameCreateCertScopeCopy.meta", "nameCreateCertScopeCopy.text", ], "nameCreateCertScopeCopy.defaultText": [ "nameCreateCertScopeCopy.inputText", "nameCreateCertScopeCopy.text", "nameCreateCertScopeCopy", ], "nameCreateCertScopeCopy.inputType": [ "nameCreateCertScopeCopy.isValid", "nameCreateCertScopeCopy", ], "nameCreateCertScopeCopy.inputText": [ "nameCreateCertScopeCopy.isValid", "nameCreateCertScopeCopy", ], "nameCreateCertScopeCopy.isRequired": [ "nameCreateCertScopeCopy.isValid", "nameCreateCertScopeCopy", ], "nameCreateCertScopeCopy.text": [ "nameCreateCertScopeCopy.value", "nameCreateCertScopeCopy", ], "nameCreateCertScopeCopy.meta": ["nameCreateCertScopeCopy"], "nameCreateCertScopeCopy.accentColor": ["nameCreateCertScopeCopy"], "nameCreateCertScopeCopy.borderRadius": ["nameCreateCertScopeCopy"], "nameCreateCertScopeCopy.value": ["nameCreateCertScopeCopy"], "nameCreateCertScopeCopy.isValid": ["nameCreateCertScopeCopy"], "submitCopyCopy3.onClick": ["submitCopyCopy3"], "submitCopyCopy3.buttonColor": ["submitCopyCopy3"], "submitCopyCopy3.borderRadius": ["submitCopyCopy3"], "Text5CopyCopy1CopyCopy3.text": [ "Text5CopyCopy1CopyCopy3.value", "Text5CopyCopy1CopyCopy3", ], "Text5CopyCopy1CopyCopy3.fontFamily": ["Text5CopyCopy1CopyCopy3"], "Text5CopyCopy1CopyCopy3.value": ["Text5CopyCopy1CopyCopy3"], "IconButton3CopyCopyCopyCopyCopy3.buttonColor": [ "IconButton3CopyCopyCopyCopyCopy3", ], "IconButton3CopyCopyCopyCopyCopy3.borderRadius": [ "IconButton3CopyCopyCopyCopyCopy3", ], "CreateSystemApprovalModal.onClose": ["CreateSystemApprovalModal"], "CreateTypeFormCopyCopy1Copy.borderRadius": [ "CreateTypeFormCopyCopy1Copy", ], "descCreateSystemApproval.meta.text": [ "descCreateSystemApproval.text", "descCreateSystemApproval.meta", ], "descCreateSystemApproval.defaultText": [ "descCreateSystemApproval.text", "descCreateSystemApproval.inputText", "descCreateSystemApproval", ], "nameCreateSystemApproval.meta.text": [ "nameCreateSystemApproval.text", "nameCreateSystemApproval.meta", ], "nameCreateSystemApproval.defaultText": [ "nameCreateSystemApproval.text", "nameCreateSystemApproval.inputText", "nameCreateSystemApproval", ], "nameCreateSystemApproval.text": [ "Button11.isDisabled", "nameCreateSystemApproval.value", "nameCreateSystemApproval", "add_system_approval.config.body", ], "descCreateSystemApproval.text": [ "Button11.isDisabled", "descCreateSystemApproval.value", "descCreateSystemApproval", "add_system_approval.config.body", ], "Button11.onClick": ["Button11"], "Button11.buttonColor": ["Button11"], "Button11.borderRadius": ["Button11"], "Button11.isDisabled": ["Button11"], "CreateSystemApprText.text": [ "CreateSystemApprText.value", "CreateSystemApprText", ], "CreateSystemApprText.fontFamily": ["CreateSystemApprText"], "CreateSystemApprText.value": ["CreateSystemApprText"], "closeSystemApprovalModal.buttonColor": ["closeSystemApprovalModal"], "closeSystemApprovalModal.borderRadius": ["closeSystemApprovalModal"], "regionOrCountrySelect.meta.value": [ "regionOrCountrySelect.value", "regionOrCountrySelect.meta", ], "regionOrCountrySelect.defaultOptionValue": [ "regionOrCountrySelect.value", "regionOrCountrySelect.label", "regionOrCountrySelect", ], "get_countries.data": [ "regionOrCountrySelect.options", "get_countries", ], "get_regions.data": ["regionOrCountrySelect.options", "get_regions"], "regionOrCountrySelect.serverSideFiltering": [ "regionOrCountrySelect.selectedOptionValue", "regionOrCountrySelect.selectedOptionLabel", "regionOrCountrySelect", ], "regionOrCountrySelect.options": [ "regionOrCountrySelect.selectedOptionValue", "regionOrCountrySelect.selectedOptionLabel", "regionOrCountrySelect", ], "regionOrCountrySelect.value": [ "regionOrCountrySelect.selectedOptionValue", "regionOrCountrySelect", ], "regionOrCountrySelect.isDirty": [ "regionOrCountrySelect.selectedOptionValue", "regionOrCountrySelect", ], "regionOrCountrySelect.selectedOptionValue": [ "RegulationsContaiter.isVisible", "Default.add_regulation", "get_regulation_by_region.config.body", "regionOrCountrySelect.selectedOptionLabel", "regionOrCountrySelect.isValid", "regionOrCountrySelect", "get_regulation_by_country.config.body", ], "RegulationsContaiter.borderRadius": ["RegulationsContaiter"], "RegulationsContaiter.boxShadow": ["RegulationsContaiter"], "RegulationsContaiter.isVisible": ["RegulationsContaiter"], "Button8.onClick": ["Button8"], "Button8.borderRadius": ["Button8"], "Button8.isDisabled": ["Button8"], "Button6Copy.onClick": ["Button6Copy"], "Button6Copy.buttonColor": ["Button6Copy"], "Button6Copy.borderRadius": ["Button6Copy"], "Button6Copy.isDisabled": ["Button6Copy"], "Button5Copy.onClick": ["Button5Copy"], "Button5Copy.borderRadius": ["Button5Copy"], "Button5Copy.isDisabled": ["Button5Copy"], "Button3Copy.onClick": ["Button3Copy"], "Button3Copy.borderRadius": ["Button3Copy"], "TextCopy1CopyCopy1.text": [ "TextCopy1CopyCopy1.value", "TextCopy1CopyCopy1", ], "TextCopy1CopyCopy1.value": ["TextCopy1CopyCopy1"], "EditRequirementModal.onClose": ["EditRequirementModal"], "CreateTypeFormCopyCopyCopy.borderRadius": [ "CreateTypeFormCopyCopyCopy", ], "kindEditRequirement.meta.value": [ "kindEditRequirement.value", "kindEditRequirement.meta", ], "kindEditRequirement.defaultOptionValue": [ "kindEditRequirement.value", "kindEditRequirement.label", "kindEditRequirement", ], "kindEditRequirement.serverSideFiltering": [ "kindEditRequirement.selectedOptionValue", "kindEditRequirement.selectedOptionLabel", "kindEditRequirement", ], "kindEditRequirement.options": [ "kindEditRequirement.selectedOptionValue", "kindEditRequirement.selectedOptionLabel", "kindEditRequirement", ], "kindEditRequirement.value": [ "kindEditRequirement.selectedOptionValue", "kindEditRequirement", ], "kindEditRequirement.isDirty": [ "kindEditRequirement.selectedOptionValue", "kindEditRequirement", ], "descEditRequirement.meta.text": [ "descEditRequirement.text", "descEditRequirement.meta", ], "descEditRequirement.defaultText": [ "descEditRequirement.text", "descEditRequirement.inputText", "descEditRequirement", ], "nameEditRequirement.meta.text": [ "nameEditRequirement.text", "nameEditRequirement.meta", ], "nameEditRequirement.defaultText": [ "nameEditRequirement.text", "nameEditRequirement.inputText", "nameEditRequirement", ], "nameEditRequirement.text": [ "Button10Copy.isDisabled", "nameEditRequirement.value", "nameEditRequirement", "edit_requirement.config.body", ], "descEditRequirement.text": [ "Button10Copy.isDisabled", "descEditRequirement.value", "descEditRequirement", "edit_requirement.config.body", ], "kindEditRequirement.selectedOptionValue": [ "Button10Copy.isDisabled", "kindEditRequirement.selectedOptionLabel", "kindEditRequirement.isValid", "kindEditRequirement", "edit_requirement.config.body", ], "Button10Copy.onClick": ["Button10Copy"], "Button10Copy.buttonColor": ["Button10Copy"], "Button10Copy.borderRadius": ["Button10Copy"], "Button10Copy.isDisabled": ["Button10Copy"], "Text5CopyCopy1CopyCopyCopy.text": [ "Text5CopyCopy1CopyCopyCopy.value", "Text5CopyCopy1CopyCopyCopy", ], "Text5CopyCopy1CopyCopyCopy.fontFamily": ["Text5CopyCopy1CopyCopyCopy"], "Text5CopyCopy1CopyCopyCopy.value": ["Text5CopyCopy1CopyCopyCopy"], "IconButton3CopyCopyCopyCopyCopyCopy.buttonColor": [ "IconButton3CopyCopyCopyCopyCopyCopy", ], "IconButton3CopyCopyCopyCopyCopyCopy.borderRadius": [ "IconButton3CopyCopyCopyCopyCopyCopy", ], "CreateRequirementModalCopy.onClose": ["CreateRequirementModalCopy"], "CreateTypeFormCopyCopyCopy1.borderRadius": [ "CreateTypeFormCopyCopyCopy1", ], "Button10Copy1.onClick": ["Button10Copy1"], "Button10Copy1.buttonColor": ["Button10Copy1"], "Button10Copy1.borderRadius": ["Button10Copy1"], "Button10Copy1.isDisabled": ["Button10Copy1"], "kindCreateRequirementCopy.meta.value": [ "kindCreateRequirementCopy.meta", "kindCreateRequirementCopy.value", ], "kindCreateRequirementCopy.meta.label": [ "kindCreateRequirementCopy.meta", "kindCreateRequirementCopy.label", ], "kindCreateRequirementCopy.meta.filterText": [ "kindCreateRequirementCopy.meta", "kindCreateRequirementCopy.filterText", ], "kindCreateRequirementCopy.defaultOptionValue": [ "kindCreateRequirementCopy.value", "kindCreateRequirementCopy.label", "kindCreateRequirementCopy", ], "kindCreateRequirementCopy.serverSideFiltering": [ "kindCreateRequirementCopy.selectedOptionValue", "kindCreateRequirementCopy.selectedOptionLabel", "kindCreateRequirementCopy", ], "kindCreateRequirementCopy.options": [ "kindCreateRequirementCopy.selectedOptionValue", "kindCreateRequirementCopy.selectedOptionLabel", "kindCreateRequirementCopy", ], "kindCreateRequirementCopy.value": [ "kindCreateRequirementCopy.selectedOptionValue", "kindCreateRequirementCopy", ], "kindCreateRequirementCopy.isDirty": [ "kindCreateRequirementCopy.selectedOptionValue", "kindCreateRequirementCopy", ], "kindCreateRequirementCopy.label": [ "kindCreateRequirementCopy.selectedOptionLabel", "kindCreateRequirementCopy", ], "kindCreateRequirementCopy.selectedOptionValue": [ "kindCreateRequirementCopy.selectedOptionLabel", "kindCreateRequirementCopy.isValid", "kindCreateRequirementCopy", ], "kindCreateRequirementCopy.isRequired": [ "kindCreateRequirementCopy.isValid", "kindCreateRequirementCopy", ], "kindCreateRequirementCopy.meta": ["kindCreateRequirementCopy"], "kindCreateRequirementCopy.filterText": ["kindCreateRequirementCopy"], "kindCreateRequirementCopy.accentColor": ["kindCreateRequirementCopy"], "kindCreateRequirementCopy.borderRadius": ["kindCreateRequirementCopy"], "kindCreateRequirementCopy.isValid": ["kindCreateRequirementCopy"], "kindCreateRequirementCopy.selectedOptionLabel": [ "kindCreateRequirementCopy", ], "descCreateRequirementCopy.meta.inputText": [ "descCreateRequirementCopy.meta", "descCreateRequirementCopy.inputText", ], "descCreateRequirementCopy.meta.text": [ "descCreateRequirementCopy.meta", "descCreateRequirementCopy.text", ], "descCreateRequirementCopy.defaultText": [ "descCreateRequirementCopy.inputText", "descCreateRequirementCopy.text", "descCreateRequirementCopy", ], "descCreateRequirementCopy.inputType": [ "descCreateRequirementCopy.isValid", "descCreateRequirementCopy", ], "descCreateRequirementCopy.inputText": [ "descCreateRequirementCopy.isValid", "descCreateRequirementCopy", ], "descCreateRequirementCopy.isRequired": [ "descCreateRequirementCopy.isValid", "descCreateRequirementCopy", ], "descCreateRequirementCopy.text": [ "descCreateRequirementCopy.value", "descCreateRequirementCopy", ], "descCreateRequirementCopy.meta": ["descCreateRequirementCopy"], "descCreateRequirementCopy.accentColor": ["descCreateRequirementCopy"], "descCreateRequirementCopy.borderRadius": ["descCreateRequirementCopy"], "descCreateRequirementCopy.value": ["descCreateRequirementCopy"], "descCreateRequirementCopy.isValid": ["descCreateRequirementCopy"], "nameCreateRequirementCopy.meta.inputText": [ "nameCreateRequirementCopy.meta", "nameCreateRequirementCopy.inputText", ], "nameCreateRequirementCopy.meta.text": [ "nameCreateRequirementCopy.meta", "nameCreateRequirementCopy.text", ], "nameCreateRequirementCopy.defaultText": [ "nameCreateRequirementCopy.inputText", "nameCreateRequirementCopy.text", "nameCreateRequirementCopy", ], "nameCreateRequirementCopy.inputType": [ "nameCreateRequirementCopy.isValid", "nameCreateRequirementCopy", ], "nameCreateRequirementCopy.inputText": [ "nameCreateRequirementCopy.isValid", "nameCreateRequirementCopy", ], "nameCreateRequirementCopy.isRequired": [ "nameCreateRequirementCopy.isValid", "nameCreateRequirementCopy", ], "nameCreateRequirementCopy.text": [ "nameCreateRequirementCopy.value", "nameCreateRequirementCopy", ], "nameCreateRequirementCopy.meta": ["nameCreateRequirementCopy"], "nameCreateRequirementCopy.accentColor": ["nameCreateRequirementCopy"], "nameCreateRequirementCopy.borderRadius": ["nameCreateRequirementCopy"], "nameCreateRequirementCopy.value": ["nameCreateRequirementCopy"], "nameCreateRequirementCopy.isValid": ["nameCreateRequirementCopy"], "Text5CopyCopy1CopyCopyCopy1.text": [ "Text5CopyCopy1CopyCopyCopy1.value", "Text5CopyCopy1CopyCopyCopy1", ], "Text5CopyCopy1CopyCopyCopy1.fontFamily": [ "Text5CopyCopy1CopyCopyCopy1", ], "Text5CopyCopy1CopyCopyCopy1.value": ["Text5CopyCopy1CopyCopyCopy1"], "IconButton3CopyCopyCopyCopyCopyCopy1.buttonColor": [ "IconButton3CopyCopyCopyCopyCopyCopy1", ], "IconButton3CopyCopyCopyCopyCopyCopy1.borderRadius": [ "IconButton3CopyCopyCopyCopyCopyCopy1", ], "EditSystemApprovalModal.onClose": ["EditSystemApprovalModal"], "CreateTypeFormCopyCopy1CopyCopy.borderRadius": [ "CreateTypeFormCopyCopy1CopyCopy", ], "descEditSystemApproval.meta.text": [ "descEditSystemApproval.text", "descEditSystemApproval.meta", ], "descEditSystemApproval.defaultText": [ "descEditSystemApproval.text", "descEditSystemApproval.inputText", "descEditSystemApproval", ], "nameEditSystemApproval.meta.text": [ "nameEditSystemApproval.text", "nameEditSystemApproval.meta", ], "nameEditSystemApproval.defaultText": [ "nameEditSystemApproval.text", "nameEditSystemApproval.inputText", "nameEditSystemApproval", ], "nameEditSystemApproval.text": [ "Button11Copy.isDisabled", "nameEditSystemApproval.value", "nameEditSystemApproval", "edit_system_approval.config.body", ], "descEditSystemApproval.text": [ "Button11Copy.isDisabled", "descEditSystemApproval.value", "descEditSystemApproval", "edit_system_approval.config.body", ], "Button11Copy.onClick": ["Button11Copy"], "Button11Copy.buttonColor": ["Button11Copy"], "Button11Copy.borderRadius": ["Button11Copy"], "Button11Copy.isDisabled": ["Button11Copy"], "CreateSystemApprTextCopy.text": [ "CreateSystemApprTextCopy.value", "CreateSystemApprTextCopy", ], "CreateSystemApprTextCopy.fontFamily": ["CreateSystemApprTextCopy"], "CreateSystemApprTextCopy.value": ["CreateSystemApprTextCopy"], "closeSystemApprovalModalCopy.buttonColor": [ "closeSystemApprovalModalCopy", ], "closeSystemApprovalModalCopy.borderRadius": [ "closeSystemApprovalModalCopy", ], "headerCopy2.borderRadius": ["headerCopy2"], "headerCopy2.boxShadow": ["headerCopy2"], "Canvas9.borderRadius": ["Canvas9"], "Canvas9.accentColor": ["Canvas9"], "Button2Copy24.onClick": ["Button2Copy24"], "Button2Copy24.buttonColor": ["Button2Copy24"], "Button2Copy24.borderRadius": ["Button2Copy24"], "Button2Copy12.onClick": ["Button2Copy12"], "Button2Copy12.buttonColor": ["Button2Copy12"], "Button2Copy12.borderRadius": ["Button2Copy12"], "Button2Copy23.onClick": ["Button2Copy23"], "Button2Copy23.buttonColor": ["Button2Copy23"], "Button2Copy23.borderRadius": ["Button2Copy23"], "Button2Copy22.onClick": ["Button2Copy22"], "Button2Copy22.buttonColor": ["Button2Copy22"], "Button2Copy22.borderRadius": ["Button2Copy22"], "Button2Copy2Copy2.onClick": ["Button2Copy2Copy2"], "Button2Copy2Copy2.buttonColor": ["Button2Copy2Copy2"], "Button2Copy2Copy2.borderRadius": ["Button2Copy2Copy2"], "Button2CopyCopy.onClick": ["Button2CopyCopy"], "Button2CopyCopy.buttonColor": ["Button2CopyCopy"], "Button2CopyCopy.borderRadius": ["Button2CopyCopy"], "Button2CopyCopyCopy.onClick": ["Button2CopyCopyCopy"], "Button2CopyCopyCopy.buttonColor": ["Button2CopyCopyCopy"], "Button2CopyCopyCopy.borderRadius": ["Button2CopyCopyCopy"], "Button2Copy25.onClick": ["Button2Copy25"], "Button2Copy25.buttonColor": ["Button2Copy25"], "Button2Copy25.borderRadius": ["Button2Copy25"], "CreateParameterModal.onClose": ["CreateParameterModal"], "CreateTypeFormCopyCopyCopy2.borderRadius": [ "CreateTypeFormCopyCopyCopy2", ], "Button10Copy2.onClick": ["Button10Copy2"], "Button10Copy2.buttonColor": ["Button10Copy2"], "Button10Copy2.borderRadius": ["Button10Copy2"], "Text5CopyCopy1CopyCopyCopy2.text": [ "Text5CopyCopy1CopyCopyCopy2.value", "Text5CopyCopy1CopyCopyCopy2", ], "Text5CopyCopy1CopyCopyCopy2.fontFamily": [ "Text5CopyCopy1CopyCopyCopy2", ], "Text5CopyCopy1CopyCopyCopy2.value": ["Text5CopyCopy1CopyCopyCopy2"], "IconButton3CopyCopyCopyCopyCopyCopy2.buttonColor": [ "IconButton3CopyCopyCopyCopyCopyCopy2", ], "IconButton3CopyCopyCopyCopyCopyCopy2.borderRadius": [ "IconButton3CopyCopyCopyCopyCopyCopy2", ], "EditParameterModal.onClose": ["EditParameterModal"], "CreateTypeFormCopyCopyCopy2Copy.borderRadius": [ "CreateTypeFormCopyCopyCopy2Copy", ], "get_physical_units.data": [ "get_physical_units", "unitEditParameter.options", "unitCreateParameter.options", ], "Button10Copy2Copy.onClick": ["Button10Copy2Copy"], "Button10Copy2Copy.buttonColor": ["Button10Copy2Copy"], "Button10Copy2Copy.borderRadius": ["Button10Copy2Copy"], "Text5CopyCopy1CopyCopyCopy2Copy.text": [ "Text5CopyCopy1CopyCopyCopy2Copy.value", "Text5CopyCopy1CopyCopyCopy2Copy", ], "Text5CopyCopy1CopyCopyCopy2Copy.fontFamily": [ "Text5CopyCopy1CopyCopyCopy2Copy", ], "Text5CopyCopy1CopyCopyCopy2Copy.value": [ "Text5CopyCopy1CopyCopyCopy2Copy", ], "IconButton3CopyCopyCopyCopyCopyCopy2Copy.buttonColor": [ "IconButton3CopyCopyCopyCopyCopyCopy2Copy", ], "IconButton3CopyCopyCopyCopyCopyCopy2Copy.borderRadius": [ "IconButton3CopyCopyCopyCopyCopyCopy2Copy", ], "appsmith.theme.colors": ["appsmith.theme"], "appsmith.theme.borderRadius": ["appsmith.theme"], "appsmith.theme.fontFamily": ["appsmith.theme"], "appsmith.theme.boxShadow": ["appsmith.theme"], "appsmith.theme": ["appsmith"], "unitEditParameter.meta.value": [ "unitEditParameter.meta", "unitEditParameter.value", ], "unitEditParameter.meta.label": [ "unitEditParameter.meta", "unitEditParameter.label", ], "unitEditParameter.meta.filterText": [ "unitEditParameter.meta", "unitEditParameter.filterText", ], "unitEditParameter.defaultOptionValue": [ "unitEditParameter.value", "unitEditParameter.label", "unitEditParameter", ], "unitEditParameter.serverSideFiltering": [ "unitEditParameter.selectedOptionValue", "unitEditParameter.selectedOptionLabel", "unitEditParameter", ], "unitEditParameter.options": [ "unitEditParameter.selectedOptionValue", "unitEditParameter.selectedOptionLabel", "unitEditParameter", ], "unitEditParameter.value": [ "unitEditParameter.selectedOptionValue", "unitEditParameter", ], "unitEditParameter.isDirty": [ "unitEditParameter.selectedOptionValue", "unitEditParameter", ], "unitEditParameter.label": [ "unitEditParameter.selectedOptionLabel", "unitEditParameter", ], "unitEditParameter.selectedOptionValue": [ "unitEditParameter.selectedOptionLabel", "unitEditParameter.isValid", "unitEditParameter", "Default.edit_parameter", ], "unitEditParameter.isRequired": [ "unitEditParameter.isValid", "unitEditParameter", ], "unitEditParameter.meta": ["unitEditParameter"], "unitEditParameter.filterText": ["unitEditParameter"], "unitEditParameter.accentColor": ["unitEditParameter"], "unitEditParameter.borderRadius": ["unitEditParameter"], "unitEditParameter.isValid": ["unitEditParameter"], "unitEditParameter.selectedOptionLabel": ["unitEditParameter"], "descEditParameter.meta.inputText": [ "descEditParameter.meta", "descEditParameter.inputText", ], "descEditParameter.meta.text": [ "descEditParameter.meta", "descEditParameter.text", ], "descEditParameter.defaultText": [ "descEditParameter.inputText", "descEditParameter.text", "descEditParameter", ], "descEditParameter.inputType": [ "descEditParameter.isValid", "descEditParameter", ], "descEditParameter.inputText": [ "descEditParameter.isValid", "descEditParameter", ], "descEditParameter.isRequired": [ "descEditParameter.isValid", "descEditParameter", ], "descEditParameter.text": [ "descEditParameter.value", "descEditParameter", "Default.edit_parameter", ], "descEditParameter.meta": ["descEditParameter"], "descEditParameter.accentColor": ["descEditParameter"], "descEditParameter.borderRadius": ["descEditParameter"], "descEditParameter.value": ["descEditParameter"], "descEditParameter.isValid": ["descEditParameter"], "nameEditParameter.meta.inputText": [ "nameEditParameter.meta", "nameEditParameter.inputText", ], "nameEditParameter.meta.text": [ "nameEditParameter.meta", "nameEditParameter.text", ], "nameEditParameter.defaultText": [ "nameEditParameter.inputText", "nameEditParameter.text", "nameEditParameter", ], "nameEditParameter.inputType": [ "nameEditParameter.isValid", "nameEditParameter", ], "nameEditParameter.inputText": [ "nameEditParameter.isValid", "nameEditParameter", ], "nameEditParameter.isRequired": [ "nameEditParameter.isValid", "nameEditParameter", ], "nameEditParameter.text": [ "nameEditParameter.value", "nameEditParameter", "Default.edit_parameter", ], "nameEditParameter.meta": ["nameEditParameter"], "nameEditParameter.accentColor": ["nameEditParameter"], "nameEditParameter.borderRadius": ["nameEditParameter"], "nameEditParameter.value": ["nameEditParameter"], "nameEditParameter.isValid": ["nameEditParameter"], "ParamsTable.onRowSelected": [ "ParamsTable.triggerRowSelection", "ParamsTable", ], "ParamsTable.bottomRow": ["ParamsTable.pageSize", "ParamsTable"], "ParamsTable.topRow": ["ParamsTable.pageSize", "ParamsTable"], "ParamsTable.parentRowSpace": ["ParamsTable.pageSize", "ParamsTable"], "ParamsTable.triggeredRowIndex": [ "ParamsTable.triggeredRow", "ParamsTable", ], "ParamsTable.onPageChange": ["ParamsTable"], "ParamsTable.meta": ["ParamsTable"], "ParamsTable.accentColor": ["ParamsTable"], "ParamsTable.borderRadius": ["ParamsTable"], "ParamsTable.boxShadow": ["ParamsTable"], "ParamsTable.triggeredRow": ["ParamsTable"], "ParamsTable.selectedRows": ["ParamsTable"], "ParamsTable.pageSize": ["ParamsTable"], "ParamsTable.triggerRowSelection": ["ParamsTable"], "ParamsTable.sortOrder": ["ParamsTable"], "regionOrCountry.isRequired": [ "regionOrCountry.isValid", "regionOrCountry", ], "regionOrCountry.options": [ "regionOrCountry.selectedOption", "regionOrCountry", ], "regionOrCountry.onSelectionChange": ["regionOrCountry"], "regionOrCountry.meta": ["regionOrCountry"], "regionOrCountry.accentColor": ["regionOrCountry"], "regionOrCountry.selectedOption": ["regionOrCountry"], "regionOrCountry.isValid": ["regionOrCountry"], "regionOrCountry.value": ["regionOrCountry"], "unitCreateParameter.meta.value": [ "unitCreateParameter.meta", "unitCreateParameter.value", ], "unitCreateParameter.meta.label": [ "unitCreateParameter.meta", "unitCreateParameter.label", ], "unitCreateParameter.meta.filterText": [ "unitCreateParameter.meta", "unitCreateParameter.filterText", ], "unitCreateParameter.defaultOptionValue": [ "unitCreateParameter.value", "unitCreateParameter.label", "unitCreateParameter", ], "unitCreateParameter.serverSideFiltering": [ "unitCreateParameter.selectedOptionValue", "unitCreateParameter.selectedOptionLabel", "unitCreateParameter", ], "unitCreateParameter.options": [ "unitCreateParameter.selectedOptionValue", "unitCreateParameter.selectedOptionLabel", "unitCreateParameter", ], "unitCreateParameter.value": [ "unitCreateParameter.selectedOptionValue", "unitCreateParameter", ], "unitCreateParameter.isDirty": [ "unitCreateParameter.selectedOptionValue", "unitCreateParameter", ], "unitCreateParameter.label": [ "unitCreateParameter.selectedOptionLabel", "unitCreateParameter", ], "unitCreateParameter.selectedOptionValue": [ "unitCreateParameter.selectedOptionLabel", "unitCreateParameter.isValid", "unitCreateParameter", "Default.add_parameter", ], "unitCreateParameter.isRequired": [ "unitCreateParameter.isValid", "unitCreateParameter", ], "unitCreateParameter.meta": ["unitCreateParameter"], "unitCreateParameter.filterText": ["unitCreateParameter"], "unitCreateParameter.accentColor": ["unitCreateParameter"], "unitCreateParameter.borderRadius": ["unitCreateParameter"], "unitCreateParameter.isValid": ["unitCreateParameter"], "unitCreateParameter.selectedOptionLabel": ["unitCreateParameter"], "descCreateParameter.meta.inputText": [ "descCreateParameter.meta", "descCreateParameter.inputText", ], "descCreateParameter.meta.text": [ "descCreateParameter.meta", "descCreateParameter.text", ], "descCreateParameter.defaultText": [ "descCreateParameter.inputText", "descCreateParameter.text", "descCreateParameter", ], "descCreateParameter.inputType": [ "descCreateParameter.isValid", "descCreateParameter", ], "descCreateParameter.inputText": [ "descCreateParameter.isValid", "descCreateParameter", ], "descCreateParameter.isRequired": [ "descCreateParameter.isValid", "descCreateParameter", ], "descCreateParameter.text": [ "descCreateParameter.value", "descCreateParameter", "Default.add_parameter", ], "descCreateParameter.meta": ["descCreateParameter"], "descCreateParameter.accentColor": ["descCreateParameter"], "descCreateParameter.borderRadius": ["descCreateParameter"], "descCreateParameter.value": ["descCreateParameter"], "descCreateParameter.isValid": ["descCreateParameter"], "nameCreateParameter.meta.inputText": [ "nameCreateParameter.meta", "nameCreateParameter.inputText", ], "nameCreateParameter.meta.text": [ "nameCreateParameter.meta", "nameCreateParameter.text", ], "nameCreateParameter.defaultText": [ "nameCreateParameter.inputText", "nameCreateParameter.text", "nameCreateParameter", ], "nameCreateParameter.inputType": [ "nameCreateParameter.isValid", "nameCreateParameter", ], "nameCreateParameter.inputText": [ "nameCreateParameter.isValid", "nameCreateParameter", ], "nameCreateParameter.isRequired": [ "nameCreateParameter.isValid", "nameCreateParameter", ], "nameCreateParameter.text": [ "nameCreateParameter.value", "nameCreateParameter", "Default.add_parameter", ], "nameCreateParameter.meta": ["nameCreateParameter"], "nameCreateParameter.accentColor": ["nameCreateParameter"], "nameCreateParameter.borderRadius": ["nameCreateParameter"], "nameCreateParameter.value": ["nameCreateParameter"], "nameCreateParameter.isValid": ["nameCreateParameter"], "edit_requirement.run": [ "Default.edit_requirement", "edit_requirement", ], "get_requirements.run": [ "Default.edit_requirement", "Default.add_requirement", "Default.update_regulations", "get_requirements", ], "Default.uuidv4": [ "Default.add_requirement", "Default.add_regulation", "Default.add_parameter", "Default.body", "Default", ], "add_requirement.run": ["Default.add_requirement", "add_requirement"], "add_edges.run": [ "Default.add_requirement", "Default.add_regulation", "add_edges", ], "get_regulation_by_country.run": [ "Default.update_regulations", "get_regulation_by_country", ], "get_regulation_by_region.run": [ "Default.update_regulations", "get_regulation_by_region", ], "edit_regulation.run": ["Default.edit_regulation", "edit_regulation"], "Default.update_regulations": [ "Default.edit_regulation", "Default.add_regulation", "Default.delete_regulation_parameter", "Default.edit_parameter", "Default.add_parameter", "Default.body", "Default", ], "certScopeSelect.meta.value": [ "certScopeSelect.value", "certScopeSelect.meta", ], "certScopeSelect.defaultOptionValue": [ "certScopeSelect.value", "certScopeSelect.label", "certScopeSelect", ], "certScopeSelect.serverSideFiltering": [ "certScopeSelect.selectedOptionValue", "certScopeSelect.selectedOptionLabel", "certScopeSelect", ], "certScopeSelect.options": [ "certScopeSelect.selectedOptionValue", "certScopeSelect.selectedOptionLabel", "certScopeSelect", ], "certScopeSelect.value": [ "certScopeSelect.selectedOptionValue", "certScopeSelect", ], "certScopeSelect.isDirty": [ "certScopeSelect.selectedOptionValue", "certScopeSelect", ], "add_regulation.run": ["Default.add_regulation", "add_regulation"], "certScopeSelect.selectedOptionValue": [ "Default.add_regulation", "get_regulations.config.body", "get_regulation_by_region.config.body", "certScopeSelect.selectedOptionLabel", "certScopeSelect.isValid", "certScopeSelect", "get_regulation_by_country.config.body", ], "edit_regulation_params.run": [ "Default.delete_regulation_parameter", "Default.edit_parameter", "Default.add_parameter", "edit_regulation_params", ], "Default.add_parameter": ["Default.body", "Default"], "Default.edit_parameter": ["Default.body", "Default"], "Default.delete_regulation_parameter": ["Default.body", "Default"], "Default.add_regulation": ["Default.body", "Default"], "Default.edit_regulation": ["Default.body", "Default"], "Default.add_requirement": ["Default.body", "Default"], "Default.edit_requirement": ["Default.body", "Default"], "Default.body": ["Default"], "get_regulations.config.body": ["get_regulations.config"], "get_regulations.config": ["get_regulations"], "edit_physical_unit.config.body": ["edit_physical_unit.config"], "edit_physical_unit.config": ["edit_physical_unit"], "get_regulation_by_region.config.body": [ "get_regulation_by_region.config", ], "get_regulation_by_region.config": ["get_regulation_by_region"], "edit_regulation_params.config.body": ["edit_regulation_params.config"], "edit_regulation_params.config": ["edit_regulation_params"], "extVersionEditRegulation.meta.inputText": [ "extVersionEditRegulation.meta", "extVersionEditRegulation.inputText", ], "extVersionEditRegulation.meta.text": [ "extVersionEditRegulation.meta", "extVersionEditRegulation.text", ], "extVersionEditRegulation.defaultText": [ "extVersionEditRegulation.inputText", "extVersionEditRegulation.text", "extVersionEditRegulation", ], "extVersionEditRegulation.inputType": [ "extVersionEditRegulation.isValid", "extVersionEditRegulation", ], "extVersionEditRegulation.inputText": [ "extVersionEditRegulation.isValid", "extVersionEditRegulation", ], "extVersionEditRegulation.isRequired": [ "extVersionEditRegulation.isValid", "extVersionEditRegulation", ], "extVersionEditRegulation.text": [ "extVersionEditRegulation.value", "extVersionEditRegulation", "edit_regulation.config.body", ], "extVersionEditRegulation.meta": ["extVersionEditRegulation"], "extVersionEditRegulation.accentColor": ["extVersionEditRegulation"], "extVersionEditRegulation.borderRadius": ["extVersionEditRegulation"], "extVersionEditRegulation.value": ["extVersionEditRegulation"], "extVersionEditRegulation.isValid": ["extVersionEditRegulation"], "descEditRegulation.meta.inputText": [ "descEditRegulation.meta", "descEditRegulation.inputText", ], "descEditRegulation.meta.text": [ "descEditRegulation.meta", "descEditRegulation.text", ], "descEditRegulation.defaultText": [ "descEditRegulation.inputText", "descEditRegulation.text", "descEditRegulation", ], "descEditRegulation.inputType": [ "descEditRegulation.isValid", "descEditRegulation", ], "descEditRegulation.inputText": [ "descEditRegulation.isValid", "descEditRegulation", ], "descEditRegulation.isRequired": [ "descEditRegulation.isValid", "descEditRegulation", ], "descEditRegulation.text": [ "descEditRegulation.value", "descEditRegulation", "edit_regulation.config.body", ], "descEditRegulation.meta": ["descEditRegulation"], "descEditRegulation.accentColor": ["descEditRegulation"], "descEditRegulation.borderRadius": ["descEditRegulation"], "descEditRegulation.value": ["descEditRegulation"], "descEditRegulation.isValid": ["descEditRegulation"], "nameEditRegulation.meta.inputText": [ "nameEditRegulation.meta", "nameEditRegulation.inputText", ], "nameEditRegulation.meta.text": [ "nameEditRegulation.meta", "nameEditRegulation.text", ], "nameEditRegulation.defaultText": [ "nameEditRegulation.inputText", "nameEditRegulation.text", "nameEditRegulation", ], "nameEditRegulation.inputType": [ "nameEditRegulation.isValid", "nameEditRegulation", ], "nameEditRegulation.inputText": [ "nameEditRegulation.isValid", "nameEditRegulation", ], "nameEditRegulation.isRequired": [ "nameEditRegulation.isValid", "nameEditRegulation", ], "nameEditRegulation.text": [ "nameEditRegulation.value", "nameEditRegulation", "edit_regulation.config.body", ], "nameEditRegulation.meta": ["nameEditRegulation"], "nameEditRegulation.accentColor": ["nameEditRegulation"], "nameEditRegulation.borderRadius": ["nameEditRegulation"], "nameEditRegulation.value": ["nameEditRegulation"], "nameEditRegulation.isValid": ["nameEditRegulation"], "edit_regulation.config.body": ["edit_regulation.config"], "edit_regulation.config": ["edit_regulation"], "descEditSystemApproval.meta.inputText": [ "descEditSystemApproval.meta", "descEditSystemApproval.inputText", ], "descEditSystemApproval.inputType": [ "descEditSystemApproval.isValid", "descEditSystemApproval", ], "descEditSystemApproval.inputText": [ "descEditSystemApproval.isValid", "descEditSystemApproval", ], "descEditSystemApproval.isRequired": [ "descEditSystemApproval.isValid", "descEditSystemApproval", ], "descEditSystemApproval.meta": ["descEditSystemApproval"], "descEditSystemApproval.accentColor": ["descEditSystemApproval"], "descEditSystemApproval.borderRadius": ["descEditSystemApproval"], "descEditSystemApproval.value": ["descEditSystemApproval"], "descEditSystemApproval.isValid": ["descEditSystemApproval"], "nameEditSystemApproval.meta.inputText": [ "nameEditSystemApproval.meta", "nameEditSystemApproval.inputText", ], "nameEditSystemApproval.inputType": [ "nameEditSystemApproval.isValid", "nameEditSystemApproval", ], "nameEditSystemApproval.inputText": [ "nameEditSystemApproval.isValid", "nameEditSystemApproval", ], "nameEditSystemApproval.isRequired": [ "nameEditSystemApproval.isValid", "nameEditSystemApproval", ], "nameEditSystemApproval.meta": ["nameEditSystemApproval"], "nameEditSystemApproval.accentColor": ["nameEditSystemApproval"], "nameEditSystemApproval.borderRadius": ["nameEditSystemApproval"], "nameEditSystemApproval.value": ["nameEditSystemApproval"], "nameEditSystemApproval.isValid": ["nameEditSystemApproval"], "edit_system_approval.config.body": ["edit_system_approval.config"], "edit_system_approval.config": ["edit_system_approval"], "kindEditRequirement.meta.label": [ "kindEditRequirement.meta", "kindEditRequirement.label", ], "kindEditRequirement.meta.filterText": [ "kindEditRequirement.meta", "kindEditRequirement.filterText", ], "kindEditRequirement.label": [ "kindEditRequirement.selectedOptionLabel", "kindEditRequirement", ], "kindEditRequirement.isRequired": [ "kindEditRequirement.isValid", "kindEditRequirement", ], "kindEditRequirement.meta": ["kindEditRequirement"], "kindEditRequirement.filterText": ["kindEditRequirement"], "kindEditRequirement.accentColor": ["kindEditRequirement"], "kindEditRequirement.borderRadius": ["kindEditRequirement"], "kindEditRequirement.isValid": ["kindEditRequirement"], "kindEditRequirement.selectedOptionLabel": ["kindEditRequirement"], "descEditRequirement.meta.inputText": [ "descEditRequirement.meta", "descEditRequirement.inputText", ], "descEditRequirement.inputType": [ "descEditRequirement.isValid", "descEditRequirement", ], "descEditRequirement.inputText": [ "descEditRequirement.isValid", "descEditRequirement", ], "descEditRequirement.isRequired": [ "descEditRequirement.isValid", "descEditRequirement", ], "descEditRequirement.meta": ["descEditRequirement"], "descEditRequirement.accentColor": ["descEditRequirement"], "descEditRequirement.borderRadius": ["descEditRequirement"], "descEditRequirement.value": ["descEditRequirement"], "descEditRequirement.isValid": ["descEditRequirement"], "nameEditRequirement.meta.inputText": [ "nameEditRequirement.meta", "nameEditRequirement.inputText", ], "nameEditRequirement.inputType": [ "nameEditRequirement.isValid", "nameEditRequirement", ], "nameEditRequirement.inputText": [ "nameEditRequirement.isValid", "nameEditRequirement", ], "nameEditRequirement.isRequired": [ "nameEditRequirement.isValid", "nameEditRequirement", ], "nameEditRequirement.meta": ["nameEditRequirement"], "nameEditRequirement.accentColor": ["nameEditRequirement"], "nameEditRequirement.borderRadius": ["nameEditRequirement"], "nameEditRequirement.value": ["nameEditRequirement"], "nameEditRequirement.isValid": ["nameEditRequirement"], "edit_requirement.config.body": ["edit_requirement.config"], "edit_requirement.config": ["edit_requirement"], "edit_status.config.body": ["edit_status.config"], "edit_status.config": ["edit_status"], "regionOrCountrySelect.meta.label": [ "regionOrCountrySelect.meta", "regionOrCountrySelect.label", ], "regionOrCountrySelect.meta.filterText": [ "regionOrCountrySelect.meta", "regionOrCountrySelect.filterText", ], "regionOrCountrySelect.label": [ "regionOrCountrySelect.selectedOptionLabel", "regionOrCountrySelect", ], "regionOrCountrySelect.isRequired": [ "regionOrCountrySelect.isValid", "regionOrCountrySelect", ], "regionOrCountrySelect.onOptionChange": ["regionOrCountrySelect"], "regionOrCountrySelect.meta": ["regionOrCountrySelect"], "regionOrCountrySelect.filterText": ["regionOrCountrySelect"], "regionOrCountrySelect.accentColor": ["regionOrCountrySelect"], "regionOrCountrySelect.borderRadius": ["regionOrCountrySelect"], "regionOrCountrySelect.placeholderText": ["regionOrCountrySelect"], "regionOrCountrySelect.isVisible": ["regionOrCountrySelect"], "regionOrCountrySelect.isValid": ["regionOrCountrySelect"], "regionOrCountrySelect.selectedOptionLabel": ["regionOrCountrySelect"], "certScopeSelect.meta.label": [ "certScopeSelect.meta", "certScopeSelect.label", ], "certScopeSelect.meta.filterText": [ "certScopeSelect.meta", "certScopeSelect.filterText", ], "certScopeSelect.label": [ "certScopeSelect.selectedOptionLabel", "certScopeSelect", ], "certScopeSelect.isRequired": [ "certScopeSelect.isValid", "certScopeSelect", ], "certScopeSelect.onOptionChange": ["certScopeSelect"], "certScopeSelect.meta": ["certScopeSelect"], "certScopeSelect.filterText": ["certScopeSelect"], "certScopeSelect.accentColor": ["certScopeSelect"], "certScopeSelect.borderRadius": ["certScopeSelect"], "certScopeSelect.isValid": ["certScopeSelect"], "certScopeSelect.selectedOptionLabel": ["certScopeSelect"], "get_regulation_by_country.config.body": [ "get_regulation_by_country.config", ], "get_regulation_by_country.config": ["get_regulation_by_country"], "descCreateSystemApproval.meta.inputText": [ "descCreateSystemApproval.meta", "descCreateSystemApproval.inputText", ], "descCreateSystemApproval.inputType": [ "descCreateSystemApproval.isValid", "descCreateSystemApproval", ], "descCreateSystemApproval.inputText": [ "descCreateSystemApproval.isValid", "descCreateSystemApproval", ], "descCreateSystemApproval.isRequired": [ "descCreateSystemApproval.isValid", "descCreateSystemApproval", ], "descCreateSystemApproval.meta": ["descCreateSystemApproval"], "descCreateSystemApproval.accentColor": ["descCreateSystemApproval"], "descCreateSystemApproval.borderRadius": ["descCreateSystemApproval"], "descCreateSystemApproval.value": ["descCreateSystemApproval"], "descCreateSystemApproval.isValid": ["descCreateSystemApproval"], "nameCreateSystemApproval.meta.inputText": [ "nameCreateSystemApproval.meta", "nameCreateSystemApproval.inputText", ], "nameCreateSystemApproval.inputType": [ "nameCreateSystemApproval.isValid", "nameCreateSystemApproval", ], "nameCreateSystemApproval.inputText": [ "nameCreateSystemApproval.isValid", "nameCreateSystemApproval", ], "nameCreateSystemApproval.isRequired": [ "nameCreateSystemApproval.isValid", "nameCreateSystemApproval", ], "nameCreateSystemApproval.meta": ["nameCreateSystemApproval"], "nameCreateSystemApproval.accentColor": ["nameCreateSystemApproval"], "nameCreateSystemApproval.borderRadius": ["nameCreateSystemApproval"], "nameCreateSystemApproval.value": ["nameCreateSystemApproval"], "nameCreateSystemApproval.isValid": ["nameCreateSystemApproval"], "add_system_approval.config.body": ["add_system_approval.config"], "add_system_approval.config": ["add_system_approval"], "extVersionCreateRegulation.meta.inputText": [ "extVersionCreateRegulation.meta", "extVersionCreateRegulation.inputText", ], "extVersionCreateRegulation.meta.text": [ "extVersionCreateRegulation.meta", "extVersionCreateRegulation.text", ], "extVersionCreateRegulation.defaultText": [ "extVersionCreateRegulation.inputText", "extVersionCreateRegulation.text", "extVersionCreateRegulation", ], "extVersionCreateRegulation.inputType": [ "extVersionCreateRegulation.isValid", "extVersionCreateRegulation", ], "extVersionCreateRegulation.inputText": [ "extVersionCreateRegulation.isValid", "extVersionCreateRegulation", ], "extVersionCreateRegulation.isRequired": [ "extVersionCreateRegulation.isValid", "extVersionCreateRegulation", ], "extVersionCreateRegulation.text": [ "extVersionCreateRegulation.value", "extVersionCreateRegulation", "add_regulation.config.body", ], "extVersionCreateRegulation.meta": ["extVersionCreateRegulation"], "extVersionCreateRegulation.accentColor": [ "extVersionCreateRegulation", ], "extVersionCreateRegulation.borderRadius": [ "extVersionCreateRegulation", ], "extVersionCreateRegulation.value": ["extVersionCreateRegulation"], "extVersionCreateRegulation.isValid": ["extVersionCreateRegulation"], "descCreateRegulation.meta.inputText": [ "descCreateRegulation.meta", "descCreateRegulation.inputText", ], "descCreateRegulation.meta.text": [ "descCreateRegulation.meta", "descCreateRegulation.text", ], "descCreateRegulation.defaultText": [ "descCreateRegulation.inputText", "descCreateRegulation.text", "descCreateRegulation", ], "descCreateRegulation.inputType": [ "descCreateRegulation.isValid", "descCreateRegulation", ], "descCreateRegulation.inputText": [ "descCreateRegulation.isValid", "descCreateRegulation", ], "descCreateRegulation.isRequired": [ "descCreateRegulation.isValid", "descCreateRegulation", ], "descCreateRegulation.text": [ "descCreateRegulation.value", "descCreateRegulation", "add_regulation.config.body", ], "descCreateRegulation.meta": ["descCreateRegulation"], "descCreateRegulation.accentColor": ["descCreateRegulation"], "descCreateRegulation.borderRadius": ["descCreateRegulation"], "descCreateRegulation.value": ["descCreateRegulation"], "descCreateRegulation.isValid": ["descCreateRegulation"], "nameCreateRegulation.meta.inputText": [ "nameCreateRegulation.meta", "nameCreateRegulation.inputText", ], "nameCreateRegulation.meta.text": [ "nameCreateRegulation.meta", "nameCreateRegulation.text", ], "nameCreateRegulation.defaultText": [ "nameCreateRegulation.inputText", "nameCreateRegulation.text", "nameCreateRegulation", ], "nameCreateRegulation.inputType": [ "nameCreateRegulation.isValid", "nameCreateRegulation", ], "nameCreateRegulation.inputText": [ "nameCreateRegulation.isValid", "nameCreateRegulation", ], "nameCreateRegulation.isRequired": [ "nameCreateRegulation.isValid", "nameCreateRegulation", ], "nameCreateRegulation.text": [ "nameCreateRegulation.value", "nameCreateRegulation", "add_regulation.config.body", ], "nameCreateRegulation.meta": ["nameCreateRegulation"], "nameCreateRegulation.accentColor": ["nameCreateRegulation"], "nameCreateRegulation.borderRadius": ["nameCreateRegulation"], "nameCreateRegulation.value": ["nameCreateRegulation"], "nameCreateRegulation.isValid": ["nameCreateRegulation"], "add_regulation.config.body": ["add_regulation.config"], "add_regulation.config": ["add_regulation"], "add_edges.config.body": ["add_edges.config"], "add_edges.config": ["add_edges"], "get_requirements.config.body": ["get_requirements.config"], "get_requirements.config": ["get_requirements"], "delete_regulation.config.body": ["delete_regulation.config"], "delete_regulation.config": ["delete_regulation"], "delete_cert_scope.config.body": ["delete_cert_scope.config"], "delete_cert_scope.config": ["delete_cert_scope"], "kindCreateRequirement.meta.label": [ "kindCreateRequirement.meta", "kindCreateRequirement.label", ], "kindCreateRequirement.meta.filterText": [ "kindCreateRequirement.meta", "kindCreateRequirement.filterText", ], "kindCreateRequirement.label": [ "kindCreateRequirement.selectedOptionLabel", "kindCreateRequirement", ], "kindCreateRequirement.isRequired": [ "kindCreateRequirement.isValid", "kindCreateRequirement", ], "kindCreateRequirement.meta": ["kindCreateRequirement"], "kindCreateRequirement.filterText": ["kindCreateRequirement"], "kindCreateRequirement.accentColor": ["kindCreateRequirement"], "kindCreateRequirement.borderRadius": ["kindCreateRequirement"], "kindCreateRequirement.isValid": ["kindCreateRequirement"], "kindCreateRequirement.selectedOptionLabel": ["kindCreateRequirement"], "descCreateRequirement.meta.inputText": [ "descCreateRequirement.meta", "descCreateRequirement.inputText", ], "descCreateRequirement.inputType": [ "descCreateRequirement.isValid", "descCreateRequirement", ], "descCreateRequirement.inputText": [ "descCreateRequirement.isValid", "descCreateRequirement", ], "descCreateRequirement.isRequired": [ "descCreateRequirement.isValid", "descCreateRequirement", ], "descCreateRequirement.meta": ["descCreateRequirement"], "descCreateRequirement.accentColor": ["descCreateRequirement"], "descCreateRequirement.borderRadius": ["descCreateRequirement"], "descCreateRequirement.value": ["descCreateRequirement"], "descCreateRequirement.isValid": ["descCreateRequirement"], "nameCreateRequirement.meta.inputText": [ "nameCreateRequirement.meta", "nameCreateRequirement.inputText", ], "nameCreateRequirement.inputType": [ "nameCreateRequirement.isValid", "nameCreateRequirement", ], "nameCreateRequirement.inputText": [ "nameCreateRequirement.isValid", "nameCreateRequirement", ], "nameCreateRequirement.isRequired": [ "nameCreateRequirement.isValid", "nameCreateRequirement", ], "nameCreateRequirement.meta": ["nameCreateRequirement"], "nameCreateRequirement.accentColor": ["nameCreateRequirement"], "nameCreateRequirement.borderRadius": ["nameCreateRequirement"], "nameCreateRequirement.value": ["nameCreateRequirement"], "nameCreateRequirement.isValid": ["nameCreateRequirement"], "add_requirement.config.body": ["add_requirement.config"], "add_requirement.config": ["add_requirement"], "regulationsTable.onRowSelected": [ "regulationsTable.triggerRowSelection", "regulationsTable", ], "regulationsTable.bottomRow": [ "regulationsTable.pageSize", "regulationsTable", ], "regulationsTable.topRow": [ "regulationsTable.pageSize", "regulationsTable", ], "regulationsTable.parentRowSpace": [ "regulationsTable.pageSize", "regulationsTable", ], "regulationsTable.triggeredRowIndex": [ "regulationsTable.triggeredRow", "regulationsTable", ], "regulationsTable.onPageChange": ["regulationsTable"], "regulationsTable.meta": ["regulationsTable"], "regulationsTable.accentColor": ["regulationsTable"], "regulationsTable.borderRadius": ["regulationsTable"], "regulationsTable.boxShadow": ["regulationsTable"], "regulationsTable.triggeredRow": ["regulationsTable"], "regulationsTable.selectedRows": ["regulationsTable"], "regulationsTable.pageSize": ["regulationsTable"], "regulationsTable.triggerRowSelection": ["regulationsTable"], "regulationsTable.sortOrder": ["regulationsTable"], "get_system_approvals.config.body": ["get_system_approvals.config"], "get_system_approvals.config": ["get_system_approvals"], "RequirementsTable.onRowSelected": [ "RequirementsTable.triggerRowSelection", "RequirementsTable", ], "RequirementsTable.bottomRow": [ "RequirementsTable.pageSize", "RequirementsTable", ], "RequirementsTable.topRow": [ "RequirementsTable.pageSize", "RequirementsTable", ], "RequirementsTable.parentRowSpace": [ "RequirementsTable.pageSize", "RequirementsTable", ], "RequirementsTable.triggeredRowIndex": [ "RequirementsTable.triggeredRow", "RequirementsTable", ], "RequirementsTable.triggeredRow": [ "RequirementsTable", "delete_requirement.config.body", ], "RequirementsTable.onPageChange": ["RequirementsTable"], "RequirementsTable.meta": ["RequirementsTable"], "RequirementsTable.accentColor": ["RequirementsTable"], "RequirementsTable.borderRadius": ["RequirementsTable"], "RequirementsTable.boxShadow": ["RequirementsTable"], "RequirementsTable.selectedRows": ["RequirementsTable"], "RequirementsTable.pageSize": ["RequirementsTable"], "RequirementsTable.triggerRowSelection": ["RequirementsTable"], "RequirementsTable.sortOrder": ["RequirementsTable"], "delete_requirement.config.body": ["delete_requirement.config"], "delete_requirement.config": ["delete_requirement"], }, ]; const output = [ ["Input1.defaultText", "Checkbox1.label"], ["Text1.text"], [ "Tabs1.isVisible", "Button3CopyCopyCopy1.isDisabled", "ParamsTable.tableData", "Button3CopyCopyCopy1Copy.isDisabled", "Button5CopyCopy1.isDisabled", "Text5CopyCopy1CopyCopyCopy2Copy.text", "unitEditParameter.defaultOptionValue", "Default.edit_parameter", "descEditParameter.defaultText", "nameEditParameter.defaultText", "Default.delete_regulation_parameter", "Button3CopyCopy.isDisabled", "Button8.isDisabled", "Button6Copy.isDisabled", "Button5Copy.isDisabled", "Default.add_requirement", "Default.add_parameter", "edit_regulation_params.config.body", "extVersionEditRegulation.defaultText", "edit_regulation.config.body", "descEditRegulation.defaultText", "nameEditRegulation.defaultText", "get_requirements.config.body", "get_system_approvals.config.body", ], ]; inputs.map((input: any, index) => { expect(getDependencyChain(input, inverseDependencies[index])).toEqual( output[index], ); }); }); });
9,688
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/GlobalSearch/GlobalSearchHooks.test.ts
import { useFilteredAndSortedFileOperations } from "./GlobalSearchHooks"; import type { Datasource } from "entities/Datasource"; import { SEARCH_ITEM_TYPES } from "./utils"; describe("getFilteredAndSortedFileOperations", () => { it("works without any datasources", () => { const fileOptions = useFilteredAndSortedFileOperations({ query: "" }); expect(fileOptions[0]).toEqual( expect.objectContaining({ title: "New JS Object", }), ); expect(fileOptions[1]).toEqual( expect.objectContaining({ title: "New blank API", }), ); expect(fileOptions[2]).toEqual( expect.objectContaining({ title: "New blank GraphQL API", }), ); expect(fileOptions[3]).toEqual( expect.objectContaining({ title: "New cURL import", }), ); expect(fileOptions[4]).toEqual( expect.objectContaining({ title: "New datasource", }), ); }); it("works without permissions", () => { const actionOperationsWithoutCreate = useFilteredAndSortedFileOperations({ query: "", allDatasources: [], recentlyUsedDSMap: {}, canCreateActions: false, }); expect(actionOperationsWithoutCreate.length).toEqual(0); const actionOperationsWithoutDatasourcePermission = useFilteredAndSortedFileOperations({ query: "", allDatasources: [], recentlyUsedDSMap: {}, canCreateActions: true, canCreateDatasource: false, }); expect(actionOperationsWithoutDatasourcePermission.length).toEqual(4); }); it("shows app datasources before other datasources", () => { const appDatasource: Datasource = { datasourceStorages: { unused_env: { datasourceId: "", environmentId: "", datasourceConfiguration: { url: "", }, isValid: true, }, }, id: "", pluginId: "", workspaceId: "", name: "App datasource", }; const otherDatasource: Datasource = { datasourceStorages: { unused_env: { datasourceId: "", environmentId: "", datasourceConfiguration: { url: "", }, isValid: false, }, }, id: "", pluginId: "", workspaceId: "", name: "Other datasource", }; const fileOptions = useFilteredAndSortedFileOperations({ query: "", allDatasources: [appDatasource, otherDatasource], recentlyUsedDSMap: {}, canCreateActions: true, canCreateDatasource: true, }); expect(fileOptions[0]).toEqual( expect.objectContaining({ title: "New JS Object", }), ); expect(fileOptions[1]).toEqual( expect.objectContaining({ title: "Create a query", kind: SEARCH_ITEM_TYPES.sectionTitle, }), ); expect(fileOptions[2]).toEqual( expect.objectContaining({ title: "New App datasource query", }), ); expect(fileOptions[3]).toEqual( expect.objectContaining({ title: "New Other datasource query", }), ); }); it("sorts datasources based on recency", () => { const appDatasource: Datasource = { datasourceStorages: { unused_env: { datasourceId: "", environmentId: "", datasourceConfiguration: { url: "", }, isValid: true, }, }, id: "123", pluginId: "", workspaceId: "", name: "App datasource", }; const otherDatasource: Datasource = { datasourceStorages: { unused_env: { datasourceId: "", environmentId: "", datasourceConfiguration: { url: "", }, isValid: false, }, }, id: "abc", pluginId: "", workspaceId: "", name: "Other datasource", }; const fileOptions = useFilteredAndSortedFileOperations({ query: "", allDatasources: [appDatasource, otherDatasource], recentlyUsedDSMap: { abc: 1, "123": 3 }, canCreateActions: true, canCreateDatasource: true, }); expect(fileOptions[0]).toEqual( expect.objectContaining({ title: "New JS Object", }), ); expect(fileOptions[1]).toEqual( expect.objectContaining({ title: "Create a query", kind: SEARCH_ITEM_TYPES.sectionTitle, }), ); expect(fileOptions[2]).toEqual( expect.objectContaining({ title: "New Other datasource query", }), ); expect(fileOptions[3]).toEqual( expect.objectContaining({ title: "New App datasource query", }), ); }); it("filters with a query", () => { const appDatasource: Datasource = { datasourceStorages: { unused_env: { datasourceId: "", environmentId: "", datasourceConfiguration: { url: "", }, isValid: true, }, }, id: "", pluginId: "", workspaceId: "", name: "App datasource", }; const otherDatasource: Datasource = { datasourceStorages: { unused_env: { datasourceId: "", environmentId: "", datasourceConfiguration: { url: "", }, isValid: false, }, }, id: "", pluginId: "", workspaceId: "", name: "Other datasource", }; const fileOptions = useFilteredAndSortedFileOperations({ query: "App", allDatasources: [appDatasource, otherDatasource], recentlyUsedDSMap: {}, canCreateActions: true, canCreateDatasource: true, }); expect(fileOptions[0]).toEqual( expect.objectContaining({ title: "New App datasource query", }), ); }); it("Non matching query shows on datasource creation", () => { const appDatasource: Datasource = { datasourceStorages: { unused_env: { datasourceId: "", environmentId: "", datasourceConfiguration: { url: "", }, isValid: true, }, }, id: "", pluginId: "", workspaceId: "", name: "App datasource", }; const otherDatasource: Datasource = { datasourceStorages: { unused_env: { datasourceId: "", environmentId: "", datasourceConfiguration: { url: "", }, isValid: false, }, }, id: "", pluginId: "", workspaceId: "", name: "Other datasource", }; const fileOptions = useFilteredAndSortedFileOperations({ query: "zzzz", allDatasources: [appDatasource, otherDatasource], recentlyUsedDSMap: {}, canCreateActions: true, canCreateDatasource: true, }); expect(fileOptions[0]).toEqual( expect.objectContaining({ title: "New datasource", }), ); }); });
9,720
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/utils.test.ts
import WidgetQueryGeneratorRegistry from "utils/WidgetQueryGeneratorRegistry"; import { getDatasourceConnectionMode } from "./utils"; import type { DatasourceStorage } from "entities/Datasource"; import { PluginPackageName } from "entities/Action"; import PostgreSQL from "WidgetQueryGenerators/PostgreSQL"; import GSheets from "WidgetQueryGenerators/GSheets"; describe("getDatasourceConnectionMode", () => { beforeAll(() => { WidgetQueryGeneratorRegistry.register( PluginPackageName.POSTGRES, PostgreSQL, ); WidgetQueryGeneratorRegistry.register( PluginPackageName.GOOGLE_SHEETS, GSheets, ); }); it("should return the connection mode from the query generator", () => { expect( getDatasourceConnectionMode(PluginPackageName.POSTGRES, { connection: { mode: "READ_ONLY", }, } as DatasourceStorage["datasourceConfiguration"]), ).toEqual("READ_ONLY"); expect( getDatasourceConnectionMode(PluginPackageName.GOOGLE_SHEETS, { authentication: { scopeString: "spreadsheets.readonly", }, } as DatasourceStorage["datasourceConfiguration"]), ).toEqual("READ_ONLY"); expect( getDatasourceConnectionMode(PluginPackageName.GOOGLE_SHEETS, { authentication: { scopeString: "spreadsheets", }, } as DatasourceStorage["datasourceConfiguration"]), ).toEqual("READ_WRITE"); }); it("should return null if the query generator is not found", () => { const result = getDatasourceConnectionMode( "non-existent-plugin-package-name", { connection: { mode: "READ_ONLY", }, } as DatasourceStorage["datasourceConfiguration"], ); expect(result).toBe(undefined); }); });
9,777
0
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/form/fields
petrpan-code/appsmithorg/appsmith/app/client/src/components/editorComponents/form/fields/__tests__/KeyValueFieldArray.test.tsx
import React from "react"; import "@testing-library/jest-dom"; import KeyValueFieldArray from "../KeyValueFieldArray"; import { reduxForm } from "redux-form"; import { render } from "test/testUtils"; const initialProps = { name: "Headers", actionConfig: [] as Array<{ key: string; value: string }>, dataTreePath: ".config.headers", hideHeader: false, label: "Headers", placeholder: "Value", pushFields: true, theme: "LIGHT", hasType: false, }; let rendererTimer: any; function getComponent(props: any) { function keyValueComponent() { return <KeyValueFieldArray {...props} />; } const Parent = reduxForm<any, any>({ validate: () => { return {}; }, form: "HeaderForm", touchOnBlur: true, })(keyValueComponent); return <Parent />; } describe("Bug 11832: KeyValueFieldArray", () => { it("If no headers data is there, it must maintain 2 pairs of empty fields by default", () => { render(getComponent(initialProps)); rendererTimer = setTimeout(() => { const headerDivs = document.querySelectorAll('div[class*="t--Headers"]'); expect(headerDivs.length).toBe(2); }, 0); }); it("If headers data is there, it need not maintain pairs of empty fields", () => { initialProps.actionConfig.push({ key: "p1", value: "p2" }); initialProps.actionConfig.push({ key: "p1", value: "p2" }); initialProps.actionConfig.push({ key: "p1", value: "p2" }); initialProps.actionConfig.push({ key: "p1", value: "p2" }); render(getComponent(initialProps)); rendererTimer = setTimeout(() => { const headerDivs = document.querySelectorAll('div[class*="t--Headers"]'); expect(headerDivs.length).toBe(4); }, 0); }); afterEach(() => { clearTimeout(rendererTimer); rendererTimer = undefined; }); });
9,785
0
petrpan-code/appsmithorg/appsmith/app/client/src/components
petrpan-code/appsmithorg/appsmith/app/client/src/components/formControls/DynamicInputTextControl.test.tsx
import React from "react"; import { render, screen } from "test/testUtils"; import DynamicInputTextControl from "./DynamicInputTextControl"; import { reduxForm } from "redux-form"; import { mockCodemirrorRender } from "test/__mocks__/CodeMirrorEditorMock"; import userEvent from "@testing-library/user-event"; import { waitFor } from "@testing-library/dom"; function TestForm(props: any) { return <div>{props.children}</div>; } const ReduxFormDecorator = reduxForm({ form: "TestForm", initialValues: { actionConfiguration: { testPath: "My test value" } }, })(TestForm); describe("DynamicInputTextControl", () => { beforeEach(() => { mockCodemirrorRender(); }); it("renders correctly", () => { render( <ReduxFormDecorator> <DynamicInputTextControl actionName="Test action" configProperty="actionConfiguration.testPath" controlType="DYNAMIC_INPUT_TEXT_CONTROL" dataType={"TABLE"} formName="TestForm" id={"test"} isValid label="Action" onPropertyChange={jest.fn()} placeholderText="Test placeholder" /> </ReduxFormDecorator>, {}, ); waitFor(async () => { const input = screen.getAllByText("My test value")[0]; userEvent.type(input, "New text"); await expect(screen.getAllByText("New text")).toHaveLength(2); await expect(screen.findByText("My test value")).toBeNull(); }); }); });
9,801
0
petrpan-code/appsmithorg/appsmith/app/client/src/components
petrpan-code/appsmithorg/appsmith/app/client/src/components/formControls/utils.test.ts
import { actionPathFromName, caculateIsHidden, checkIfSectionCanRender, checkIfSectionIsEnabled, evaluateCondtionWithType, extractConditionalOutput, getConfigInitialValues, getViewType, isHidden, switchViewType, updateEvaluatedSectionConfig, ViewTypes, } from "./utils"; import type { HiddenType } from "./BaseControl"; import { set } from "lodash"; import { isValidFormConfig } from "reducers/evaluationReducers/formEvaluationReducer"; import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag"; describe("isHidden test", () => { it("Test for isHidden true", () => { const hiddenTrueInputs: any = [ { values: { name: "Name" }, hidden: true }, { values: { datasourceStorages: { unused_env: { name: "Name", number: 2, email: "[email protected]" }, }, }, hidden: { conditionType: "AND", conditions: [ { path: "datasourceStorages.unused_env.name", value: "Name", comparison: "EQUALS", }, { conditionType: "AND", conditions: [ { path: "datasourceStorages.unused_env.number", value: 2, comparison: "EQUALS", }, { path: "datasourceStorages.unused_env.email", value: "[email protected]", comparison: "EQUALS", }, ], }, ], }, }, { values: { datasourceStorages: { unused_env: { name: "Name" }, }, }, hidden: { path: "datasourceStorages.unused_env.name", value: "Name", comparison: "EQUALS", }, }, { values: { datasourceStorages: { unused_env: { name: "Name", config: { type: "EMAIL" } }, }, }, hidden: { path: "datasourceStorages.unused_env.name.config.type", value: "USER_ID", comparison: "NOT_EQUALS", }, }, { values: undefined, hidden: true, }, { values: null, hidden: true, }, ]; hiddenTrueInputs.forEach((input: any) => { expect(isHidden(input.values, input.hidden)).toBeTruthy(); }); }); it("Test for isHidden false", () => { const hiddenFalseInputs: any = [ { values: { name: "Name" }, hidden: false }, { values: { datasourceStorages: { unused_env: { name: "Name" }, }, }, hidden: { path: "datasourceStorages.unused_env.name", value: "Different Name", comparison: "EQUALS", }, }, { values: { datasourceStorages: { unused_env: { name: "Name", config: { type: "EMAIL" } }, }, }, hidden: { path: "datasourceStorages.unused_env.config.type", value: "EMAIL", comparison: "NOT_EQUALS", }, }, { values: { datasourceStorages: { unused_env: { name: "Name", config: { type: "Different BODY" } }, }, }, hidden: { path: "datasourceStorages.unused_env.config.type", value: ["EMAIL", "BODY"], comparison: "IN", }, }, { values: { datasourceStorages: { unused_env: { name: "Name", config: { type: "BODY" } }, }, }, hidden: { path: "datasourceStorages.unused_env.config.type", value: ["EMAIL", "BODY"], comparison: "NOT_IN", }, }, { values: undefined, hidden: false, }, { values: null, hidden: false, }, { values: undefined, }, { values: { datasourceStorages: { unused_env: { name: "Name" }, }, }, }, { values: { datasourceStorages: { unused_env: { name: "Name", config: { type: "EMAIL", name: "TEMP" }, contact: { number: 1234, address: "abcd" }, }, }, }, hidden: { conditionType: "AND", conditions: [ { path: "datasourceStorages.unused_env.contact.number", value: 1234, comparison: "NOT_EQUALS", }, { conditionType: "OR", conditions: [ { conditionType: "AND", conditions: [ { path: "datasourceStorages.unused_env.config.name", value: "TEMP", comparison: "EQUALS", }, { path: "datasourceStorages.unused_env.config.name", value: "HELLO", comparison: "EQUALS", }, ], }, { path: "datasourceStorages.unused_env.config.type", value: "EMAIL", comparison: "NOT_EQUALS", }, ], }, ], }, }, ]; hiddenFalseInputs.forEach((input: any) => { expect(isHidden(input.values, input.hidden)).toBeFalsy(); }); }); }); describe("getConfigInitialValues test", () => { it("getConfigInitialValues test", () => { const testCases = [ { input: [ { sectionName: "Connection", children: [ { label: "Region", configProperty: "datasourceStorages.unused_env.datasourceConfiguration.authentication.databaseName", controlType: "DROP_DOWN", initialValue: "ap-south-1", options: [ { label: "ap-south-1", value: "ap-south-1", }, { label: "eu-south-1", value: "eu-south-1", }, ], }, ], }, ], output: { datasourceStorages: { unused_env: { datasourceConfiguration: { authentication: { databaseName: "ap-south-1" }, }, }, }, }, }, { input: [ { sectionName: "Connection", children: [ { label: "Region", configProperty: "datasourceStorages.unused_env.datasourceConfiguration.authentication.databaseName", controlType: "INPUT_TEXT", }, ], }, ], output: {}, }, { input: [ { sectionName: "Connection", children: [ { label: "Host address (for overriding endpoint only)", configProperty: "datasourceStorages.unused_env.datasourceConfiguration.endpoints[*].host", controlType: "KEYVALUE_ARRAY", initialValue: ["jsonplaceholder.typicode.com"], }, { label: "Port", configProperty: "datasourceStorages.unused_env.datasourceConfiguration.endpoints[*].port", dataType: "NUMBER", controlType: "KEYVALUE_ARRAY", }, ], }, ], output: { datasourceStorages: { unused_env: { datasourceConfiguration: { endpoints: [{ host: "jsonplaceholder.typicode.com" }], }, }, }, }, }, { input: [ { sectionName: "Settings", children: [ { label: "Smart substitution", configProperty: "datasourceStorages.unused_env.datasourceConfiguration.isSmart", controlType: "SWITCH", initialValue: false, }, ], }, ], output: { datasourceStorages: { unused_env: { datasourceConfiguration: { isSmart: false, }, }, }, }, }, ]; testCases.forEach((testCase) => { expect(getConfigInitialValues(testCase.input)).toEqual(testCase.output); }); }); }); describe("caculateIsHidden test", () => { it("calcualte hidden field value", () => { const values = { datasourceStorages: { unused_env: { name: "Name" }, }, }; const hiddenTruthy: HiddenType = { path: "datasourceStorages.unused_env.name", comparison: "EQUALS", value: "Name", flagValue: FEATURE_FLAG.TEST_FLAG, }; const hiddenFalsy: HiddenType = { path: "datasourceStorages.unused_env.name", comparison: "EQUALS", value: "Different Name", flagValue: FEATURE_FLAG.TEST_FLAG, }; expect(caculateIsHidden(values, hiddenTruthy)).toBeTruthy(); expect(caculateIsHidden(values, hiddenFalsy)).toBeFalsy(); }); }); describe("evaluateCondtionWithType test", () => { it("accumulate boolean of array into one based on conditionType", () => { const andConditionType = "AND"; const orConditionType = "OR"; const booleanArray = [true, false, true]; expect( evaluateCondtionWithType(booleanArray, andConditionType), ).toBeFalsy(); expect( evaluateCondtionWithType(booleanArray, orConditionType), ).toBeTruthy(); }); }); describe("actionPathFromName test", () => { it("creates path from name", () => { const actionName = "Api5"; const name = "actionConfiguration.pluginSpecifiedTemplates[7].value"; const pathName = "Api5.config.pluginSpecifiedTemplates[7].value"; expect(actionPathFromName(actionName, name)).toEqual(pathName); }); }); describe("json/form viewTypes test", () => { it("should return correct viewType", () => { const testValues = { actionConfiguration: { formData: { node1: { data: "value1" }, node3: { data: "value1" }, node2: { data: "value1", viewType: ViewTypes.JSON }, node4: { data: "value1", viewType: ViewTypes.COMPONENT }, node5: { bata: "value1", viewType: ViewTypes.COMPONENT }, }, }, actionConfiguration2: { formData: { node6: { data: "value1", viewType: ViewTypes.COMPONENT }, }, }, }; const testCases = [ { input: "actionConfiguration.formData.node1.data", output: ViewTypes.COMPONENT, }, { input: "actionConfiguration.formData.node2.data", output: ViewTypes.JSON, }, { input: "actionConfiguration.formData.node3.data", output: ViewTypes.COMPONENT, }, { input: "actionConfiguration.formData.node4.data", output: ViewTypes.COMPONENT, }, { input: "actionConfiguration.formData.node5.bata", output: ViewTypes.COMPONENT, }, { input: "actionConfiguration2.formData.node6.bata", output: ViewTypes.COMPONENT, }, ]; testCases.forEach((testCase) => { expect(getViewType(testValues, testCase.input)).toEqual(testCase.output); }); }); it("should change the viewType", () => { const outputValues: any[] = [ { actionConfiguration: { formData: { node1: { data: "value1" }, node3: { data: "value1" }, node2: { data: "value1", viewType: ViewTypes.JSON }, node4: { data: "value1", viewType: ViewTypes.COMPONENT }, node5: { data: "value1", viewType: ViewTypes.JSON, componentData: "value2", }, node6: { viewType: ViewTypes.COMPONENT, }, }, }, }, { actionConfiguration: { formData: { node1: { data: "value1" }, node3: { data: "value1" }, node2: { data: "value1", viewType: ViewTypes.JSON }, node4: { data: "value1", viewType: ViewTypes.COMPONENT }, node5: { data: "value1", viewType: ViewTypes.JSON, componentData: "value2", }, node6: { viewType: ViewTypes.COMPONENT, }, }, }, }, { actionConfiguration: { formData: { node1: { data: "value1" }, node3: { data: "value1" }, node2: { data: "value1", viewType: ViewTypes.JSON }, node4: { data: "value1", viewType: ViewTypes.COMPONENT, jsonData: "value2", }, node5: { data: "value1", viewType: ViewTypes.JSON, componentData: "value2", }, node6: { viewType: ViewTypes.COMPONENT, }, }, }, }, { actionConfiguration: { formData: { node1: { data: "value1" }, node3: { data: "value1" }, node2: { data: "value1", viewType: ViewTypes.JSON }, node4: { data: "value1", viewType: ViewTypes.COMPONENT }, node5: { data: "value1", viewType: ViewTypes.JSON, componentData: "value2", }, node6: { viewType: ViewTypes.COMPONENT, }, }, }, }, { actionConfiguration: { formData: { node1: { data: "value1" }, node3: { data: "value1" }, node2: { data: "value1", viewType: ViewTypes.JSON }, node4: { data: "value1", viewType: ViewTypes.COMPONENT }, node5: { data: "value1", viewType: ViewTypes.JSON, componentData: "value2", }, node6: { viewType: ViewTypes.COMPONENT, }, }, }, }, { actionConfiguration: { formData: { node1: { data: "value1" }, node3: { data: "value1" }, node2: { data: "value1", viewType: ViewTypes.JSON }, node4: { data: "value1", viewType: ViewTypes.COMPONENT }, node5: { data: "value1", viewType: ViewTypes.JSON, componentData: "value2", }, node6: { viewType: ViewTypes.COMPONENT, }, }, }, }, ]; const customSetterFunction = ( formName: string, path: string, value: any, ) => { set(outputValues[Number(formName.split("-")[1])], path, value); }; const inputValue = { actionConfiguration: { formData: { node1: { data: "value1" }, node2: { data: "value1", viewType: ViewTypes.JSON }, node3: { data: "value1" }, node4: { data: "value1", viewType: ViewTypes.COMPONENT, jsonData: "value2", }, node5: { data: "value1", viewType: ViewTypes.JSON, componentData: "value2", }, node6: { viewType: ViewTypes.COMPONENT, }, }, }, }; const expectedOutputValues: any[] = [ { actionConfiguration: { formData: { node1: { data: "value1", viewType: ViewTypes.JSON, componentData: "value1", }, node2: { data: "value1", viewType: ViewTypes.JSON }, node3: { data: "value1" }, node4: { data: "value1", viewType: ViewTypes.COMPONENT }, node5: { data: "value1", viewType: ViewTypes.JSON, componentData: "value2", }, node6: { viewType: ViewTypes.COMPONENT, }, }, }, }, { actionConfiguration: { formData: { node1: { data: "value1" }, node3: { data: "value1" }, node2: { data: "value1", viewType: ViewTypes.COMPONENT, jsonData: "value1", }, node4: { data: "value1", viewType: ViewTypes.COMPONENT }, node5: { data: "value1", viewType: ViewTypes.JSON, componentData: "value2", }, node6: { viewType: ViewTypes.COMPONENT, }, }, }, }, { actionConfiguration: { formData: { node1: { data: "value1" }, node3: { data: "value1" }, node2: { data: "value1", viewType: ViewTypes.JSON }, node4: { data: "value1", viewType: ViewTypes.JSON, jsonData: "value2", componentData: "value1", }, node5: { data: "value1", viewType: ViewTypes.JSON, componentData: "value2", }, node6: { viewType: ViewTypes.COMPONENT, }, }, }, }, { actionConfiguration: { formData: { node1: { data: "value1" }, node3: { data: "value1" }, node2: { data: "value1", viewType: ViewTypes.JSON }, node4: { data: "value1", viewType: ViewTypes.COMPONENT }, node5: { data: "value2", viewType: ViewTypes.COMPONENT, componentData: "value2", jsonData: "value1", }, node6: { viewType: ViewTypes.COMPONENT, }, }, }, }, { actionConfiguration: { formData: { node1: { data: "value1" }, node3: { data: "value1", jsonData: "value1", viewType: ViewTypes.COMPONENT, }, node2: { data: "value1", viewType: ViewTypes.JSON }, node4: { data: "value1", viewType: ViewTypes.COMPONENT }, node5: { data: "value1", viewType: ViewTypes.JSON, componentData: "value2", }, node6: { viewType: ViewTypes.COMPONENT, }, }, }, }, { actionConfiguration: { formData: { node1: { data: "value1" }, node2: { data: "value1", viewType: ViewTypes.JSON }, node3: { data: "value1" }, node4: { data: "value1", viewType: ViewTypes.COMPONENT, }, node5: { data: "value1", viewType: ViewTypes.JSON, componentData: "value2", }, node6: { viewType: ViewTypes.JSON, data: "", componentData: "", }, }, }, }, ]; const testCases = [ { path: "actionConfiguration.formData.node1.data", viewType: ViewTypes.COMPONENT, }, { path: "actionConfiguration.formData.node2.data", viewType: ViewTypes.JSON, }, { path: "actionConfiguration.formData.node4.data", viewType: ViewTypes.COMPONENT, }, { path: "actionConfiguration.formData.node5.data", viewType: ViewTypes.JSON, }, { path: "actionConfiguration.formData.node3.data", viewType: ViewTypes.JSON, }, { path: "actionConfiguration.formData.node6.data", viewType: ViewTypes.COMPONENT, }, ]; testCases.forEach((testCase, index) => { const formName = `testForm-${index}`; switchViewType( inputValue, testCase.path, testCase.viewType, formName, customSetterFunction, ); expect(outputValues[index]).toEqual(expectedOutputValues[index]); }); }); }); describe("UQI form render methods", () => { it("extract conditional output", () => { const expectedOutputs = [ {}, { conditionals: {}, visible: true, enabled: true, }, { conditionals: {}, visible: true, enabled: false, }, { conditionals: {}, visible: false, enabled: true, }, ]; const testCases = [ { name: "section1", }, { name: "section2", identifier: "identifier", }, { name: "section3", configProperty: "configProperty", identifier: "identifier", }, { name: "section4", configProperty: "configProperty", propertyName: "propertyName", identifier: "identifier", }, ]; testCases.forEach((testCase, index) => { const output = extractConditionalOutput(testCase, formEvaluation); expect(output).toEqual(expectedOutputs[index]); }); }); it("section render test", () => { const testCases = [ { input: "identifier", output: true, }, { input: "configProperty", output: true, }, { input: "propertyName", output: false, }, { input: "identifier2", output: true, }, { input: "identifier3", output: false, }, { input: "identifier4", output: false, }, { input: "identifier5", output: true, }, ]; testCases.forEach((testCase) => { const output = checkIfSectionCanRender(formEvaluation[testCase.input]); expect(output).toEqual(testCase.output); }); }); it("section enabled/disabled test", () => { const testCases = [ { input: "identifier", output: true, }, { input: "configProperty", output: false, }, { input: "propertyName", output: true, }, { input: "identifier2", output: false, }, { input: "identifier3", output: true, }, ]; testCases.forEach((testCase) => { const output = checkIfSectionIsEnabled(formEvaluation[testCase.input]); expect(output).toEqual(testCase.output); }); }); it("check if valid form config", () => { const testCases: any[] = [ { input: {}, output: false, }, { input: { controlType: "SECTION", label: "Select bucket to query", children: [ { label: "Bucket name", configProperty: "actionConfiguration.formData.bucket.data", controlType: "QUERY_DYNAMIC_INPUT_TEXT", evaluationSubstitutionType: "TEMPLATE", isRequired: true, initialValue: "", }, ], }, output: true, }, { input: { label: "Select bucket to query", children: [ { label: "Bucket name", configProperty: "actionConfiguration.formData.bucket.data", controlType: "QUERY_DYNAMIC_INPUT_TEXT", evaluationSubstitutionType: "TEMPLATE", isRequired: true, initialValue: "", }, ], }, output: false, }, ]; testCases.forEach((testCase) => { const output = isValidFormConfig(testCase.input); expect(output).toEqual(testCase.output); }); }); it("update section config tests", () => { const testCases = [ { input: { sectionObject: { key1: "valueX", key2: "valueY", disabled: false, visible: false, controlType: "SECTION", }, path: "updateSectionConfigTest1", }, output: { key1: "value1", key2: "value2", disabled: false, visible: false, controlType: "SECTION", }, }, { input: { sectionObject: { key1: "valueX", key2: "valueY", disabled: false, visible: false, controlType: "SECTION", }, path: "updateSectionConfigTest2", }, output: { key1: "valueX", key2: "valueY", disabled: false, visible: false, controlType: "SECTION", }, }, ]; testCases.forEach((testCase) => { const output = updateEvaluatedSectionConfig( testCase.input.sectionObject, formEvaluation[testCase.input.path], ); expect(output).toEqual(testCase.output); }); }); }); // Constant evaluation object used for testing const formEvaluation: Record<string, any> = { propertyName: { conditionals: {}, visible: false, enabled: true, }, configProperty: { conditionals: {}, visible: true, enabled: false, }, identifier: { conditionals: {}, visible: true, enabled: true, }, identifier2: { conditionals: {}, enabled: false, }, identifier3: { conditionals: {}, visible: false, }, identifier4: { conditionals: {}, visible: true, evaluateFormConfig: { updateEvaluatedConfig: false, }, }, identifier5: { conditionals: {}, visible: true, evaluateFormConfig: { updateEvaluatedConfig: "false", }, }, updateSectionConfigTest1: { conditionals: {}, visible: true, enabled: true, evaluateFormConfig: { updateEvaluatedConfig: true, evaluateFormConfigObject: { key1: { output: "value1" }, key2: { output: "value2" }, }, }, }, updateSectionConfigTest2: { conditionals: {}, visible: true, enabled: true, evaluateFormConfig: { updateEvaluatedConfig: false, evaluateFormConfigObject: { key1: { output: "value1" }, key2: { output: "value2" }, }, }, }, };