From 6619a16caf04f16b52f87c7dacbb829f2fc5b3b0 Mon Sep 17 00:00:00 2001 From: Andrew Kingston Date: Wed, 13 Oct 2021 13:45:14 +0100 Subject: [PATCH] Add tests to HBS JS helper --- .../string-templates/test/javascript.spec.js | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 packages/string-templates/test/javascript.spec.js diff --git a/packages/string-templates/test/javascript.spec.js b/packages/string-templates/test/javascript.spec.js new file mode 100644 index 0000000000..30ce9bbd60 --- /dev/null +++ b/packages/string-templates/test/javascript.spec.js @@ -0,0 +1,73 @@ +const { processStringSync, encodeJSBinding } = require("../src/index.cjs") + +const processJS = (js, context) => { + return processStringSync(encodeJSBinding(js), context) +} + +describe("Test the JavaScript helper", () => { + it("should execute a simple expression", () => { + const output = processJS(`return 1 + 2`) + expect(output).toBe("3") + }) + + it("should be able to use primitive bindings", () => { + const output = processJS(`return $("foo")`, { + foo: "bar", + }) + expect(output).toBe("bar") + }) + + it("should be able to use an object binding", () => { + const output = processJS(`return $("foo").bar`, { + foo: { + bar: "baz", + }, + }) + expect(output).toBe("baz") + }) + + it("should be able to use a complex object binding", () => { + const output = processJS(`return $("foo").bar[0].baz`, { + foo: { + bar: [ + { + baz: "shazbat", + }, + ], + }, + }) + expect(output).toBe("shazbat") + }) + + it("should be able to use a deep binding", () => { + const output = processJS(`return $("foo.bar.baz")`, { + foo: { + bar: { + baz: "shazbat", + }, + }, + }) + expect(output).toBe("shazbat") + }) + + it("should be able to use a deep array binding", () => { + const output = processJS(`return $("foo.0.bar")`, { + foo: [ + { + bar: "baz", + }, + ], + }) + expect(output).toBe("baz") + }) + + it("should handle errors", () => { + const output = processJS(`throw "Error"`) + expect(output).toBe("Error while executing JS") + }) + + it("should timeout after one second", () => { + const output = processJS(`while (true) {}`) + expect(output).toBe("Error while executing JS") + }) +})