expression_spec.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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
  39. exp: "a + 'hello'",
  40. scope: {
  41. a: 'inline '
  42. },
  43. expected: 'inline hello'
  44. },
  45. {
  46. // complex with nested values
  47. exp: "todo.title + ' : ' + (todo.done ? 'yep' : 'nope')",
  48. scope: {
  49. todo: {
  50. title: 'write tests',
  51. done: false
  52. }
  53. },
  54. expected: 'write tests : nope'
  55. },
  56. {
  57. // expression with no data variables
  58. exp: "'a' + 'b'",
  59. scope: {},
  60. expected: 'ab'
  61. },
  62. {
  63. // values with same variable name inside strings
  64. exp: "'\"test\"' + test + \"'hi'\" + hi",
  65. scope: {
  66. test: 1,
  67. hi: 2
  68. },
  69. expected: '"test"1\'hi\'2'
  70. },
  71. {
  72. // expressions with inline object literals
  73. exp: "sortRows({ column: 'name', test: haha, durrr: 123 })",
  74. scope: {
  75. sortRows: function (params) {
  76. return params.column + params.test + params.durrr
  77. },
  78. haha: 'hoho'
  79. },
  80. expected: 'namehoho123'
  81. }
  82. ]
  83. describe('Expression Parser', function () {
  84. it('parse', function () {
  85. testCases.forEach(assertExp)
  86. })
  87. it('cache', function () {
  88. var fn1 = expParser.parse('a + b')
  89. var fn2 = expParser.parse('a + b')
  90. expect(fn1).toBe(fn2)
  91. })
  92. })