-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.test.ts
93 lines (81 loc) · 2.55 KB
/
index.test.ts
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
import { get } from 'jsonpointer';
import expr from 'property-expr';
import interpolatable from './index';
describe('interpolatble memo', () => {
it('should work with a string', () => {
const subject = 'fred';
const interpolate = interpolatable(subject);
expect(interpolate({ firstName: 'fred' })).toBe(subject);
});
it('should not interpolate if pattern is null', () => {
const subject = {
a: [1, 2, '{{3}}'],
b: [1, 2, 3],
c: ['{{3}} foo'],
};
const interpolate = interpolatable(subject, { pattern: null });
const result = interpolate({ '3': 'foo' });
expect(result.a[2]).toBe('{{3}}');
});
it('should work with an object', () => {
const subject = {
a: [1, 2, '{{3}}'],
b: [1, 2, 3],
c: ['{{3}} foo'],
};
const interpolate = interpolatable(subject);
const result = interpolate({ '3': 'foo' });
expect(result.a[2]).toBe('foo');
// 3 is still foo, dependencies did not change
expect(interpolate({ '3': 'foo', 4: 'bar' })).toBe(result);
// top level object changed
expect(interpolate({ '3': 'joe', 4: 'bar' })).not.toBe(result);
// sub object with no interpolations changed
expect(interpolate({ '3': 'joe', 4: 'bar' }).b).toBe(result.b);
});
it('should accept a custom pattern', () => {
const interpolate = interpolatable(
{
a: [1, 2, '<%= bar %> foo'],
},
{
pattern: /<%=\s*(.+?)\s*%>/g,
},
);
expect(interpolate({ bar: 'baz' })).toEqual({ a: [1, 2, 'baz foo'] });
});
it('should accept custom resolvers', () => {
const context = { bar: { baz: 'qux' } };
expect(
interpolatable({ a: [1, 2, '{{/bar/baz}}'] }, { resolver: get })(context),
).toEqual({ a: [1, 2, 'qux'] });
expect(
interpolatable(
{ a: [1, 2, '{{bar.baz}}'] },
{ resolver: (c, s) => expr.getter(s)(c) },
)(context),
).toEqual({ a: [1, 2, 'qux'] });
});
it('should skip', () => {
const subject = {
foo: '{{someString}}',
bar: {
some: {
deeply: {
nested: {
expensive_to_traverse: {
obj: '{{thing}}',
},
},
},
},
},
};
const interpolate = interpolatable(subject, { skip: /bar/ });
const interpolated = interpolate({ someString: 'joe', thing: 'blah' });
expect(interpolated.foo).toEqual('joe');
expect(interpolated.bar.some.deeply.nested.expensive_to_traverse.obj).toBe(
subject.bar.some.deeply.nested.expensive_to_traverse.obj,
);
});
});