Skip to content

Commit

Permalink
chore: add more tests to handlebar templates (#27)
Browse files Browse the repository at this point in the history
Fun fact, I hate every template engine ever made. Another fun fact,
trying to remove items from an array in a pure way is _pure_ pain.
  • Loading branch information
btkostner authored Sep 29, 2023
1 parent 588e54c commit cb1aa1b
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 18 deletions.
31 changes: 31 additions & 0 deletions src/handlebars.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { readFile, mkdtemp, rm } from "fs/promises";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import Handlebars from "./handlebars";

describe.concurrent("handlebars", () => {
it("can use an or helper function", async (ctx) => {
const template = Handlebars.compile(
"{{#or KEY_ONE KEY_TWO KEY_THREE}}helpers: true{{else}}helpers: false{{/or}}",
);
const result = template({
KEY_ONE: "false",
KEY_TWO: "false",
KEY_THREE: "true",
});

expect(result).toEqual("helpers: true");
});

it("can use an or helper inverse function", async (ctx) => {
const template = Handlebars.compile(
"{{#or KEY_ONE KEY_TWO KEY_THREE}}helpers: true{{else}}helpers: false{{/or}}",
);
const result = template({
KEY_ONE: undefined,
KEY_TWO: undefined,
KEY_THREE: undefined,
});

expect(result).toEqual("helpers: false");
});
});
4 changes: 2 additions & 2 deletions src/handlebars.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import Handlebars from "handlebars";
import isObject from "lodash/isObject";
import { urlToHttpOptions } from "url";

Handlebars.registerHelper("or", function (context, ...params) {
const options = params[params.length - 1];
params.pop();

for (const value in params.splice(-1)) {
for (const value of params) {
if (value) {
return options.fn(context);
}
Expand Down
15 changes: 0 additions & 15 deletions src/templates.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,19 +62,4 @@ describe.concurrent("templates", () => {
`{\n "keyOne": true,\n "keyTwo": "valueTwo",\n "keyThree": "valueThree"\n}\n`,
);
});

it<LocalTestContext>("can use handlebars-helpers functions", async (ctx) => {
await templateFiles({
...ctx.config,
templateVariables: {
KEY_ONE: "false",
KEY_TWO: "false",
KEY_THREE: "true",
},
});
const path = join(ctx.config.fullPath, "helpers.txt");
const data = await readFile(path, "utf8");

expect(data).toEqual("helpers: true\n");
});
});
1 change: 0 additions & 1 deletion test/fixtures/templates/helpers.txt

This file was deleted.

0 comments on commit cb1aa1b

Please sign in to comment.