|
| 1 | +import { tpl } from "./tpl"; |
| 2 | +import assert from "assert"; |
| 3 | +import { createAccessorModelProxy } from "../data/createAccessorModelProxy"; |
| 4 | + |
| 5 | +interface Model { |
| 6 | + firstName: string; |
| 7 | + lastName: string; |
| 8 | + age: number; |
| 9 | + city: string; |
| 10 | +} |
| 11 | + |
| 12 | +describe("tpl", function () { |
| 13 | + const m = createAccessorModelProxy<Model>(); |
| 14 | + |
| 15 | + describe("string-only form", function () { |
| 16 | + it("returns a tpl object", function () { |
| 17 | + const result = tpl("{firstName} {lastName}"); |
| 18 | + assert.deepStrictEqual(result, { tpl: "{firstName} {lastName}" }); |
| 19 | + }); |
| 20 | + }); |
| 21 | + |
| 22 | + describe("accessor chain form", function () { |
| 23 | + it("formats with a single accessor", function () { |
| 24 | + const selector = tpl(m.firstName, "Hello, {0}!"); |
| 25 | + assert.strictEqual(selector({ firstName: "John" }), "Hello, John!"); |
| 26 | + }); |
| 27 | + |
| 28 | + it("formats with two accessors", function () { |
| 29 | + const selector = tpl(m.firstName, m.lastName, "{0} {1}"); |
| 30 | + assert.strictEqual(selector({ firstName: "John", lastName: "Doe" }), "John Doe"); |
| 31 | + }); |
| 32 | + |
| 33 | + it("formats with three accessors", function () { |
| 34 | + const selector = tpl(m.firstName, m.lastName, m.age, "{0} {1} is {2} years old"); |
| 35 | + assert.strictEqual( |
| 36 | + selector({ firstName: "John", lastName: "Doe", age: 30 }), |
| 37 | + "John Doe is 30 years old", |
| 38 | + ); |
| 39 | + }); |
| 40 | + |
| 41 | + it("formats with four accessors", function () { |
| 42 | + const selector = tpl(m.firstName, m.lastName, m.age, m.city, "{0} {1}, {2}, from {3}"); |
| 43 | + assert.strictEqual( |
| 44 | + selector({ firstName: "John", lastName: "Doe", age: 30, city: "NYC" }), |
| 45 | + "John Doe, 30, from NYC", |
| 46 | + ); |
| 47 | + }); |
| 48 | + |
| 49 | + it("handles null values", function () { |
| 50 | + const selector = tpl(m.firstName, m.lastName, "{0} {1}"); |
| 51 | + assert.strictEqual(selector({ firstName: "John", lastName: null }), "John "); |
| 52 | + }); |
| 53 | + |
| 54 | + it("handles undefined values", function () { |
| 55 | + const selector = tpl(m.firstName, m.lastName, "{0} {1}"); |
| 56 | + assert.strictEqual(selector({ firstName: undefined, lastName: "Doe" }), " Doe"); |
| 57 | + }); |
| 58 | + |
| 59 | + it("supports formatting in template", function () { |
| 60 | + const selector = tpl(m.age, "Age: {0:n;0}"); |
| 61 | + assert.strictEqual(selector({ age: 30 }), "Age: 30"); |
| 62 | + }); |
| 63 | + |
| 64 | + it("supports null text in template", function () { |
| 65 | + const selector = tpl(m.firstName, "Name: {0|N/A}"); |
| 66 | + assert.strictEqual(selector({ firstName: null }), "Name: N/A"); |
| 67 | + }); |
| 68 | + }); |
| 69 | +}); |
0 commit comments