exp-parser.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. describe('UNIT: Expression Parser', function () {
  2. var ExpParser = require('seed/src/exp-parser')
  3. var testCases = [
  4. {
  5. // string concat
  6. exp: 'a + b',
  7. vm: {
  8. a: 'hello',
  9. b: 'world'
  10. },
  11. expectedValue: 'helloworld'
  12. },
  13. {
  14. // math
  15. exp: 'a - b * 2 + 45',
  16. vm: {
  17. a: 100,
  18. b: 23
  19. },
  20. expectedValue: 100 - 23 * 2 + 45
  21. },
  22. {
  23. // boolean logic
  24. exp: '(a && b) ? c : d || e',
  25. vm: {
  26. a: true,
  27. b: false,
  28. c: null,
  29. d: false,
  30. e: 'worked'
  31. },
  32. expectedValue: 'worked'
  33. },
  34. {
  35. // inline string
  36. exp: "a + 'hello'",
  37. vm: {
  38. a: 'inline '
  39. },
  40. expectedValue: 'inline hello'
  41. },
  42. {
  43. // complex with nested values
  44. exp: "todo.title + ' : ' + (todo.done ? 'yep' : 'nope')",
  45. paths: ['todo.title', 'todo.done'],
  46. vm: {
  47. todo: {
  48. title: 'write tests',
  49. done: false
  50. }
  51. },
  52. expectedValue: 'write tests : nope'
  53. },
  54. {
  55. // expression with no scope variables
  56. exp: "'a' + 'b'",
  57. vm: {},
  58. expectedValue: 'ab'
  59. }
  60. ]
  61. testCases.forEach(describeCase)
  62. function describeCase (testCase) {
  63. describe(testCase.exp, function () {
  64. var result = ExpParser.parse(testCase.exp),
  65. vm = testCase.vm,
  66. vars = testCase.paths || Object.keys(vm)
  67. // mock the $get().
  68. // the real $get() will be tested in integration tests.
  69. vm.$get = function (key) { return this[key] }
  70. it('should get correct args', function () {
  71. if (!vars.length) return
  72. assert.strictEqual(result.paths.length, vars.length)
  73. for (var i = 0; i < vars.length; i++) {
  74. assert.strictEqual(vars[i], result.paths[i])
  75. }
  76. })
  77. it('should generate correct getter function', function () {
  78. var value = result.getter.call(vm)
  79. assert.strictEqual(value, testCase.expectedValue)
  80. })
  81. })
  82. }
  83. // extra case for invalid expressions
  84. describe('invalid expression', function () {
  85. it('should capture the error and warn', function () {
  86. var utils = require('seed/src/utils'),
  87. oldWarn = utils.warn,
  88. warned = false
  89. utils.warn = function () {
  90. warned = true
  91. }
  92. ExpParser.parse('a + "fsef')
  93. assert.ok(warned)
  94. utils.warn = oldWarn
  95. })
  96. })
  97. })