expression_parser_spec.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. var expParser = require('../../src/parse/expression')
  2. function assertExp (testCase) {
  3. var fn = expParser.parse(testCase.exp)
  4. expect(fn(testCase.scope)).toEqual(testCase.expected)
  5. }
  6. var testCases = [
  7. {
  8. // string concat
  9. exp: 'a+b',
  10. scope: {
  11. a: 'hello',
  12. b: 'world'
  13. },
  14. expected: 'helloworld'
  15. },
  16. {
  17. // math
  18. exp: 'a - b * 2 + 45',
  19. scope: {
  20. a: 100,
  21. b: 23
  22. },
  23. expected: 100 - 23 * 2 + 45
  24. },
  25. {
  26. // boolean logic
  27. exp: '(a && b) ? c : d || e',
  28. scope: {
  29. a: true,
  30. b: false,
  31. c: null,
  32. d: false,
  33. e: 'worked'
  34. },
  35. expected: 'worked'
  36. },
  37. {
  38. // inline string with newline
  39. exp: "a + 'hel\nlo'",
  40. scope: {
  41. a: 'inline '
  42. },
  43. expected: 'inline hel\nlo'
  44. },
  45. {
  46. // dollar signs and underscore
  47. exp: "_a + ' ' + $b",
  48. scope: {
  49. _a: 'underscore',
  50. $b: 'dollar'
  51. },
  52. expected: 'underscore dollar'
  53. },
  54. {
  55. // complex with nested values
  56. exp: "todo.title + ' : ' + (todo.done ? 'yep' : 'nope')",
  57. scope: {
  58. todo: {
  59. title: 'write tests',
  60. done: false
  61. }
  62. },
  63. expected: 'write tests : nope'
  64. },
  65. {
  66. // expression with no data variables
  67. exp: "'a' + 'b'",
  68. scope: {},
  69. expected: 'ab'
  70. },
  71. {
  72. // values with same variable name inside strings
  73. exp: "'\"test\"' + test + \"'hi'\" + hi",
  74. scope: {
  75. test: 1,
  76. hi: 2
  77. },
  78. expected: '"test"1\'hi\'2'
  79. },
  80. {
  81. // expressions with inline object literals
  82. exp: "sortRows({ column: 'name', test: haha, durrr: 123 })",
  83. scope: {
  84. sortRows: function (params) {
  85. return params.column + params.test + params.durrr
  86. },
  87. haha: 'hoho'
  88. },
  89. expected: 'namehoho123'
  90. }
  91. ]
  92. describe('Expression Parser', function () {
  93. it('parse getter', function () {
  94. testCases.forEach(assertExp)
  95. })
  96. it('parse setter', function () {
  97. var setter = expParser.parse('a[b]', true).setter
  98. var scope = {
  99. a: { c: 1 },
  100. b: 'c'
  101. }
  102. setter(scope, 2)
  103. expect(scope.a.c).toBe(2)
  104. })
  105. it('cache', function () {
  106. var fn1 = expParser.parse('a + b')
  107. var fn2 = expParser.parse('a + b')
  108. expect(fn1).toBe(fn2)
  109. })
  110. })