Skip to content

Commit

Permalink
fix(util-endpoints): call multi-level functions from callFunction (#3929
Browse files Browse the repository at this point in the history
)
  • Loading branch information
trivikr authored Sep 12, 2022
1 parent 1cee1f4 commit 1209cb1
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
19 changes: 16 additions & 3 deletions packages/util-endpoints/src/utils/callFunction.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ describe(callFunction.name, () => {
};
const mockFunctionName = "mockFunctionName";
const mockReturn = "mockReturn";
const mockArgReturn = "mockArgReturn";

beforeEach(() => {
lib[mockFunctionName] = jest.fn().mockReturnValue(mockReturn);
(evaluateExpression as jest.Mock).mockReturnValue(mockArgReturn);
});

afterEach(() => {
Expand All @@ -32,15 +34,26 @@ describe(callFunction.name, () => {
it.each(["string", { ref: "ref" }, { fn: "fn", argv: [] }])(
"calls evaluateExpression for non-boolean arg: %s",
(arg) => {
const mockArgReturn = "mockArgReturn";
const mockFn = { fn: mockFunctionName, argv: [arg] };

(evaluateExpression as jest.Mock).mockReturnValue(mockArgReturn);

const result = callFunction(mockFn, mockOptions);
expect(result).toBe(mockReturn);
expect(evaluateExpression).toHaveBeenCalledWith(arg, "arg", mockOptions);
expect(lib[mockFunctionName]).toHaveBeenCalledWith(mockArgReturn);
}
);

it("calls multi-level function", () => {
const mockSecondLevelFunctionName = "mockSecondLevelFunctionName";
lib[mockFunctionName][mockSecondLevelFunctionName] = jest.fn().mockReturnValue(mockReturn);

const mockArg = "mockArg";
const mockFn = { fn: `${mockFunctionName}.${mockSecondLevelFunctionName}`, argv: [mockArg] };

const result = callFunction(mockFn, mockOptions);
expect(result).toBe(mockReturn);
expect(evaluateExpression).toHaveBeenCalledWith(mockArg, "arg", mockOptions);
expect(lib[mockFunctionName]).not.toHaveBeenCalled();
expect(lib[mockFunctionName][mockSecondLevelFunctionName]).toHaveBeenCalledWith(mockArgReturn);
});
});
4 changes: 2 additions & 2 deletions packages/util-endpoints/src/utils/callFunction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { EvaluateOptions, FunctionObject, FunctionReturn } from "../types";
import { evaluateExpression } from "./evaluateExpression";

export const callFunction = ({ fn, argv }: FunctionObject, options: EvaluateOptions): FunctionReturn => {
const argvArray = argv.map((arg) => (typeof arg === "boolean" ? arg : evaluateExpression(arg, "arg", options)));
const evaluatedArgs = argv.map((arg) => (typeof arg === "boolean" ? arg : evaluateExpression(arg, "arg", options)));
// @ts-ignore Element implicitly has an 'any' type
return lib[fn](...argvArray);
return fn.split(".").reduce((acc, key) => acc[key], lib)(...evaluatedArgs);
};

0 comments on commit 1209cb1

Please sign in to comment.