1
0
Fork 0
mirror of synced 2024-07-28 17:46:09 +12:00
budibase/packages/string-templates/test/manifest.spec.js

79 lines
2 KiB
JavaScript
Raw Normal View History

2024-01-22 22:40:26 +13:00
jest.mock("@budibase/handlebars-helpers/lib/math", () => {
const actual = jest.requireActual("@budibase/handlebars-helpers/lib/math")
return {
...actual,
random: () => 10,
}
})
2024-01-20 01:45:23 +13:00
const fs = require("fs")
const { processString } = require("../src/index.cjs")
2024-01-20 02:05:35 +13:00
const tk = require("timekeeper")
tk.freeze("2021-01-21T12:00:00")
2024-01-20 01:45:23 +13:00
const manifest = JSON.parse(
fs.readFileSync(require.resolve("../manifest.json"), "utf8")
)
2024-01-23 10:06:40 +13:00
const functionsToExclude = { string: ["raw"] }
const collections = Object.keys(manifest)
const examples = collections.reduce(
(acc, collection) => ({
...acc,
[collection]: manifest[collection],
}),
{}
2024-01-20 01:45:23 +13:00
)
2024-01-23 02:57:35 +13:00
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") // $& means the whole matched string
}
2024-01-20 01:45:23 +13:00
describe("manifest", () => {
describe("examples are valid", () => {
2024-01-23 10:06:40 +13:00
describe.each(collections)("%s", collection => {
it.each(
Object.keys(examples[collection]).filter(
fnc => !functionsToExclude[collection]?.includes(fnc)
)
)("%s", async func => {
const example = manifest[collection][func].example
2024-01-20 01:45:23 +13:00
2024-01-23 10:06:40 +13:00
let [hbs, js] = example.split("->").map(x => x.trim())
2024-01-23 02:57:35 +13:00
2024-01-23 10:06:40 +13:00
const context = {
double: i => i * 2,
}
2024-01-23 02:57:35 +13:00
2024-01-23 10:06:40 +13:00
const arrays = hbs.match(/\[[^/\]]+\]/)
arrays?.forEach((arrayString, i) => {
hbs = hbs.replace(new RegExp(escapeRegExp(arrayString)), `array${i}`)
context[`array${i}`] = JSON.parse(arrayString.replace(/\'/g, '"'))
})
2024-01-23 00:24:03 +13:00
2024-01-23 10:06:40 +13:00
if (js === undefined) {
// The function has no return value
return
2024-01-23 03:30:15 +13:00
}
2024-01-23 10:06:40 +13:00
let result = await processString(hbs, context)
// Trim 's
js = js.replace(/^\'|\'$/g, "")
try {
let parsedExpected
if (
Array.isArray((parsedExpected = JSON.parse(js.replace(/\'/g, '"'))))
) {
js = parsedExpected.join(",")
}
} catch {}
result = result.replace(/ /g, " ")
expect(result).toEqual(js)
})
2024-01-20 01:45:23 +13:00
})
})
})