summaryrefslogtreecommitdiff
path: root/dev/lib/handlebars/index.test.ts
blob: ed607db1e0bf6dd976b5d356f52457130bc659a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/*
 * Elasticsearch B.V licenses this file to you under the MIT License.
 * See `packages/kbn-handlebars/LICENSE` for more information.
 */

/**
 * ABOUT THIS FILE:
 *
 * This file is for tests not copied from the upstream handlebars project, but
 * tests that we feel are needed in order to fully cover our use-cases.
 */

import Handlebars from '.';
import type { HelperOptions, TemplateDelegate } from './src/types';
import { expectTemplate, forEachCompileFunctionName } from './src/__jest__/test_bench';

it('Handlebars.create', () => {
  expect(Handlebars.create()).toMatchSnapshot();
});

describe('Handlebars.compileAST', () => {
  describe('compiler options', () => {
    it('noEscape', () => {
      expectTemplate('{{value}}').withInput({ value: '<foo>' }).toCompileTo('&lt;foo&gt;');

      expectTemplate('{{value}}')
        .withCompileOptions({ noEscape: false })
        .withInput({ value: '<foo>' })
        .toCompileTo('&lt;foo&gt;');

      expectTemplate('{{value}}')
        .withCompileOptions({ noEscape: true })
        .withInput({ value: '<foo>' })
        .toCompileTo('<foo>');
    });
  });

  it('invalid template', () => {
    expectTemplate('{{value').withInput({ value: 42 }).toThrow(`Parse error on line 1:
{{value
--^
Expecting 'ID', 'STRING', 'NUMBER', 'BOOLEAN', 'UNDEFINED', 'NULL', 'DATA', got 'INVALID'`);
  });

  if (!process.env.EVAL) {
    it('reassign', () => {
      const fn = Handlebars.compileAST;
      expect(fn('{{value}}')({ value: 42 })).toEqual('42');
    });
  }
});

// Extra "helpers" tests
describe('helpers', () => {
  it('Only provide options.fn/inverse to block helpers', () => {
    function toHaveProperties(...args: any[]) {
      toHaveProperties.calls++;
      const options = args[args.length - 1];
      expect(options).toHaveProperty('fn');
      expect(options).toHaveProperty('inverse');
      return 42;
    }
    toHaveProperties.calls = 0;

    function toNotHaveProperties(...args: any[]) {
      toNotHaveProperties.calls++;
      const options = args[args.length - 1];
      expect(options).not.toHaveProperty('fn');
      expect(options).not.toHaveProperty('inverse');
      return 42;
    }
    toNotHaveProperties.calls = 0;

    const nonBlockTemplates = ['{{foo}}', '{{foo 1 2}}'];
    const blockTemplates = ['{{#foo}}42{{/foo}}', '{{#foo 1 2}}42{{/foo}}'];

    for (const template of nonBlockTemplates) {
      expectTemplate(template)
        .withInput({
          foo: toNotHaveProperties,
        })
        .toCompileTo('42');

      expectTemplate(template).withHelper('foo', toNotHaveProperties).toCompileTo('42');
    }

    for (const template of blockTemplates) {
      expectTemplate(template)
        .withInput({
          foo: toHaveProperties,
        })
        .toCompileTo('42');

      expectTemplate(template).withHelper('foo', toHaveProperties).toCompileTo('42');
    }

    const factor = process.env.AST || process.env.EVAL ? 1 : 2;
    expect(toNotHaveProperties.calls).toEqual(nonBlockTemplates.length * 2 * factor);
    expect(toHaveProperties.calls).toEqual(blockTemplates.length * 2 * factor);
  });

  it('should pass expected "this" to helper functions (without input)', () => {
    expectTemplate('{{hello "world" 12 true false}}')
      .withHelper('hello', function (this: any, ...args: any[]) {
        expect(this).toMatchInlineSnapshot(`Object {}`);
      })
      .toCompileTo('');
  });

  it('should pass expected "this" to helper functions (with input)', () => {
    expectTemplate('{{hello "world" 12 true false}}')
      .withHelper('hello', function (this: any, ...args: any[]) {
        expect(this).toMatchInlineSnapshot(`
          Object {
            "people": Array [
              Object {
                "id": 1,
                "name": "Alan",
              },
              Object {
                "id": 2,
                "name": "Yehuda",
              },
            ],
          }
        `);
      })
      .withInput({
        people: [
          { name: 'Alan', id: 1 },
          { name: 'Yehuda', id: 2 },
        ],
      })
      .toCompileTo('');
  });

  it('should pass expected "this" and arguments to helper functions (non-block helper)', () => {
    expectTemplate('{{hello "world" 12 true false}}')
      .withHelper('hello', function (this: any, ...args: any[]) {
        expect(args).toMatchInlineSnapshot(`
          Array [
            "world",
            12,
            true,
            false,
            Object {
              "data": Object {
                "root": Object {
                  "people": Array [
                    Object {
                      "id": 1,
                      "name": "Alan",
                    },
                    Object {
                      "id": 2,
                      "name": "Yehuda",
                    },
                  ],
                },
              },
              "hash": Object {},
              "loc": Object {
                "end": Object {
                  "column": 31,
                  "line": 1,
                },
                "start": Object {
                  "column": 0,
                  "line": 1,
                },
              },
              "lookupProperty": [Function],
              "name": "hello",
            },
          ]
        `);
      })
      .withInput({
        people: [
          { name: 'Alan', id: 1 },
          { name: 'Yehuda', id: 2 },
        ],
      })
      .toCompileTo('');
  });

  it('should pass expected "this" and arguments to helper functions (block helper)', () => {
    expectTemplate('{{#hello "world" 12 true false}}{{/hello}}')
      .withHelper('hello', function (this: any, ...args: any[]) {
        expect(args).toMatchInlineSnapshot(`
          Array [
            "world",
            12,
            true,
            false,
            Object {
              "data": Object {
                "root": Object {
                  "people": Array [
                    Object {
                      "id": 1,
                      "name": "Alan",
                    },
                    Object {
                      "id": 2,
                      "name": "Yehuda",
                    },
                  ],
                },
              },
              "fn": [Function],
              "hash": Object {},
              "inverse": [Function],
              "loc": Object {
                "end": Object {
                  "column": 42,
                  "line": 1,
                },
                "start": Object {
                  "column": 0,
                  "line": 1,
                },
              },
              "lookupProperty": [Function],
              "name": "hello",
            },
          ]
        `);
      })
      .withInput({
        people: [
          { name: 'Alan', id: 1 },
          { name: 'Yehuda', id: 2 },
        ],
      })
      .toCompileTo('');
  });
});

// Extra "blocks" tests
describe('blocks', () => {
  describe('decorators', () => {
    it('should only call decorator once', () => {
      let calls = 0;
      const callsExpected = process.env.AST || process.env.EVAL ? 1 : 2;
      expectTemplate('{{#helper}}{{*decorator}}{{/helper}}')
        .withHelper('helper', () => {})
        .withDecorator('decorator', () => {
          calls++;
        })
        .toCompileTo('');
      expect(calls).toEqual(callsExpected);
    });

    forEachCompileFunctionName((compileName) => {
      it(`should call decorator again if render function is called again for #${compileName}`, () => {
        global.kbnHandlebarsEnv = Handlebars.create();

        kbnHandlebarsEnv!.registerDecorator('decorator', () => {
          calls++;
        });

        const compile = kbnHandlebarsEnv![compileName].bind(kbnHandlebarsEnv);
        const render = compile('{{*decorator}}');

        let calls = 0;
        expect(render()).toEqual('');
        expect(calls).toEqual(1);

        calls = 0;
        expect(render()).toEqual('');
        expect(calls).toEqual(1);

        global.kbnHandlebarsEnv = null;
      });
    });

    it('should pass expected options to nested decorator', () => {
      expectTemplate('{{#helper}}{{*decorator foo}}{{/helper}}')
        .withHelper('helper', () => {})
        .withDecorator('decorator', function (fn, props, container, options) {
          expect(options).toMatchInlineSnapshot(`
            Object {
              "args": Array [
                "bar",
              ],
              "data": Object {
                "root": Object {
                  "foo": "bar",
                },
              },
              "hash": Object {},
              "loc": Object {
                "end": Object {
                  "column": 29,
                  "line": 1,
                },
                "start": Object {
                  "column": 11,
                  "line": 1,
                },
              },
              "name": "decorator",
            }
          `);
        })
        .withInput({ foo: 'bar' })
        .toCompileTo('');
    });

    it('should pass expected options to root decorator with no args', () => {
      expectTemplate('{{*decorator}}')
        .withDecorator('decorator', function (fn, props, container, options) {
          expect(options).toMatchInlineSnapshot(`
            Object {
              "args": Array [],
              "data": Object {
                "root": Object {
                  "foo": "bar",
                },
              },
              "hash": Object {},
              "loc": Object {
                "end": Object {
                  "column": 14,
                  "line": 1,
                },
                "start": Object {
                  "column": 0,
                  "line": 1,
                },
              },
              "name": "decorator",
            }
          `);
        })
        .withInput({ foo: 'bar' })
        .toCompileTo('');
    });

    it('should pass expected options to root decorator with one arg', () => {
      expectTemplate('{{*decorator foo}}')
        .withDecorator('decorator', function (fn, props, container, options) {
          expect(options).toMatchInlineSnapshot(`
            Object {
              "args": Array [
                undefined,
              ],
              "data": Object {
                "root": Object {
                  "foo": "bar",
                },
              },
              "hash": Object {},
              "loc": Object {
                "end": Object {
                  "column": 18,
                  "line": 1,
                },
                "start": Object {
                  "column": 0,
                  "line": 1,
                },
              },
              "name": "decorator",
            }
          `);
        })
        .withInput({ foo: 'bar' })
        .toCompileTo('');
    });

    describe('return values', () => {
      for (const [desc, template, result] of [
        ['non-block', '{{*decorator}}cont{{*decorator}}ent', 'content'],
        ['block', '{{#*decorator}}con{{/decorator}}tent', 'tent'],
      ]) {
        describe(desc, () => {
          const falsy = [undefined, null, false, 0, ''];
          const truthy = [true, 42, 'foo', {}];

          // Falsy return values from decorators are simply ignored and the
          // execution falls back to default behavior which is to render the
          // other parts of the template.
          for (const value of falsy) {
            it(`falsy value (type ${typeof value}): ${JSON.stringify(value)}`, () => {
              expectTemplate(template)
                .withDecorator('decorator', () => value)
                .toCompileTo(result);
            });
          }

          // Truthy return values from decorators are expected to be functions
          // and the program will attempt to call them. We expect an error to
          // be thrown in this case.
          for (const value of truthy) {
            it(`non-falsy value (type ${typeof value}): ${JSON.stringify(value)}`, () => {
              expectTemplate(template)
                .withDecorator('decorator', () => value)
                .toThrow('is not a function');
            });
          }

          // If the decorator return value is a custom function, its return
          // value will be the final content of the template.
          for (const value of [...falsy, ...truthy]) {
            it(`function returning ${typeof value}: ${JSON.stringify(value)}`, () => {
              expectTemplate(template)
                .withDecorator('decorator', () => () => value)
                .toCompileTo(value as string);
            });
          }
        });
      }
    });

    describe('custom return function should be called with expected arguments and its return value should be rendered in the template', () => {
      it('root decorator', () => {
        expectTemplate('{{*decorator}}world')
          .withInput({ me: 'my' })
          .withDecorator(
            'decorator',
            (fn): TemplateDelegate =>
              (context, options) => {
                expect(context).toMatchInlineSnapshot(`
              Object {
                "me": "my",
              }
            `);
                expect(options).toMatchInlineSnapshot(`
              Object {
                "decorators": Object {
                  "decorator": [Function],
                },
                "helpers": Object {},
                "partials": Object {},
              }
            `);
                return `hello ${context.me} ${fn()}!`;
              }
          )
          .toCompileTo('hello my world!');
      });

      it('decorator nested inside of array-helper', () => {
        expectTemplate('{{#arr}}{{*decorator}}world{{/arr}}')
          .withInput({ arr: ['my'] })
          .withDecorator(
            'decorator',
            (fn): TemplateDelegate =>
              (context, options) => {
                expect(context).toMatchInlineSnapshot(`"my"`);
                expect(options).toMatchInlineSnapshot(`
              Object {
                "blockParams": Array [
                  "my",
                  0,
                ],
                "data": Object {
                  "_parent": Object {
                    "root": Object {
                      "arr": Array [
                        "my",
                      ],
                    },
                  },
                  "first": true,
                  "index": 0,
                  "key": 0,
                  "last": true,
                  "root": Object {
                    "arr": Array [
                      "my",
                    ],
                  },
                },
              }
            `);
                return `hello ${context} ${fn()}!`;
              }
          )
          .toCompileTo('hello my world!');
      });

      it('decorator nested inside of custom helper', () => {
        expectTemplate('{{#helper}}{{*decorator}}world{{/helper}}')
          .withHelper('helper', function (options: HelperOptions) {
            return options.fn('my', { foo: 'bar' } as any);
          })
          .withDecorator(
            'decorator',
            (fn): TemplateDelegate =>
              (context, options) => {
                expect(context).toMatchInlineSnapshot(`"my"`);
                expect(options).toMatchInlineSnapshot(`
              Object {
                "foo": "bar",
              }
            `);
                return `hello ${context} ${fn()}!`;
              }
          )
          .toCompileTo('hello my world!');
      });
    });

    it('should call multiple decorators in the same program body in the expected order and get the expected output', () => {
      let decoratorCall = 0;
      let progCall = 0;
      expectTemplate('{{*decorator}}con{{*decorator}}tent', {
        beforeRender() {
          // ensure the counters are reset between EVAL/AST render calls
          decoratorCall = 0;
          progCall = 0;
        },
      })
        .withInput({
          decoratorCall: 0,
          progCall: 0,
        })
        .withDecorator('decorator', (fn) => {
          const decoratorCallOrder = ++decoratorCall;
          const ret: TemplateDelegate = () => {
            const progCallOrder = ++progCall;
            return `(decorator: ${decoratorCallOrder}, prog: ${progCallOrder}, fn: "${fn()}")`;
          };
          return ret;
        })
        .toCompileTo('(decorator: 2, prog: 1, fn: "(decorator: 1, prog: 2, fn: "content")")');
    });

    describe('registration', () => {
      beforeEach(() => {
        global.kbnHandlebarsEnv = Handlebars.create();
      });

      afterEach(() => {
        global.kbnHandlebarsEnv = null;
      });

      it('should be able to call decorators registered using the `registerDecorator` function', () => {
        let calls = 0;
        const callsExpected = process.env.AST || process.env.EVAL ? 1 : 2;

        kbnHandlebarsEnv!.registerDecorator('decorator', () => {
          calls++;
        });

        expectTemplate('{{*decorator}}').toCompileTo('');
        expect(calls).toEqual(callsExpected);
      });

      it('should not be able to call decorators unregistered using the `unregisterDecorator` function', () => {
        let calls = 0;

        kbnHandlebarsEnv!.registerDecorator('decorator', () => {
          calls++;
        });

        kbnHandlebarsEnv!.unregisterDecorator('decorator');

        expectTemplate('{{*decorator}}').toThrow('lookupProperty(...) is not a function');
        expect(calls).toEqual(0);
      });
    });
  });
});