exp-parser.js 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. describe('UNIT: Expression Parser', function () {
  2. var ExpParser = require('vue/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 data 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 caughtMissingPaths = [],
  65. compilerMock = {
  66. vm:{
  67. $data: {},
  68. $compiler:{
  69. bindings:{},
  70. createBinding: function (path) {
  71. caughtMissingPaths.push(path)
  72. }
  73. }
  74. }
  75. },
  76. getter = ExpParser.parse(testCase.exp, compilerMock),
  77. vm = testCase.vm,
  78. vars = testCase.paths || Object.keys(vm)
  79. it('should get correct paths', function () {
  80. if (!vars.length) return
  81. assert.strictEqual(caughtMissingPaths.length, vars.length)
  82. for (var i = 0; i < vars.length; i++) {
  83. assert.strictEqual(vars[i], caughtMissingPaths[i])
  84. }
  85. })
  86. it('should generate correct getter function', function () {
  87. var value = getter.call(vm)
  88. assert.strictEqual(value, testCase.expectedValue)
  89. })
  90. })
  91. }
  92. // extra case for invalid expressions
  93. describe('invalid expression', function () {
  94. it('should capture the error and warn', function () {
  95. var utils = require('vue/src/utils'),
  96. oldWarn = utils.warn,
  97. warned = false
  98. utils.warn = function () {
  99. warned = true
  100. }
  101. ExpParser.parse('a + "fsef', {
  102. vm: {
  103. $compiler: {
  104. bindings: {},
  105. createBinding: function () {}
  106. },
  107. $data: {}
  108. }
  109. })
  110. assert.ok(warned)
  111. utils.warn = oldWarn
  112. })
  113. })
  114. })