/
exp-parser.js
86 lines (76 loc) · 2.28 KB
/
exp-parser.js
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
var ExpParser = require('seed/src/exp-parser')
describe('UNIT: Expression Parser', function () {
var testCases = [
{
// string concat
exp: 'a + b',
vm: {
a: 'hello',
b: 'world'
},
expectedValue: 'helloworld'
},
{
// math
exp: 'a - b * 2 + 45',
vm: {
a: 100,
b: 23
},
expectedValue: 100 - 23 * 2 + 45
},
{
// boolean logic
exp: '(a && b) ? c : d || e',
vm: {
a: true,
b: false,
c: null,
d: false,
e: 'worked'
},
expectedValue: 'worked'
},
{
// inline string
exp: "a + 'hello'",
vm: {
a: 'inline '
},
expectedValue: 'inline hello'
},
{
// complex with nested values
exp: "todo.title + ' : ' + (todo.done ? 'yep' : 'nope')",
paths: ['todo.title', 'todo.done'],
vm: {
todo: {
title: 'write tests',
done: false
}
},
expectedValue: 'write tests : nope'
}
]
testCases.forEach(describeCase)
function describeCase (testCase) {
describe(testCase.exp, function () {
var result = ExpParser.parse(testCase.exp),
vm = testCase.vm,
vars = testCase.paths || Object.keys(vm)
// mock the $get().
// the real $get() will be tested in integration tests.
vm.$get = function (key) { return this[key] }
it('should get correct args', function () {
assert.strictEqual(result.paths.length, vars.length)
for (var i = 0; i < vars.length; i++) {
assert.strictEqual(vars[i], result.paths[i])
}
})
it('should generate correct getter function', function () {
var value = result.getter.call(vm)
assert.strictEqual(value, testCase.expectedValue)
})
})
}
})