exp-parser.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. var ExpParser = require('../../src/exp-parser'),
  2. assert = require('assert')
  3. describe('UNIT: Expression Parser', function () {
  4. var testCases = [
  5. {
  6. // string concat
  7. exp: 'a + b',
  8. vm: {
  9. a: 'hello',
  10. b: 'world'
  11. },
  12. expectedValue: 'helloworld'
  13. },
  14. {
  15. // math
  16. exp: 'a - b * 2 + 45',
  17. vm: {
  18. a: 100,
  19. b: 23
  20. },
  21. expectedValue: 100 - 23 * 2 + 45
  22. },
  23. {
  24. // boolean logic
  25. exp: '(a && b) ? c : d || e',
  26. vm: {
  27. a: true,
  28. b: false,
  29. c: null,
  30. d: false,
  31. e: 'worked'
  32. },
  33. expectedValue: 'worked'
  34. },
  35. {
  36. // inline string
  37. exp: "a + 'hello'",
  38. vm: {
  39. a: 'inline '
  40. },
  41. expectedValue: 'inline hello'
  42. },
  43. {
  44. // complex with nested values
  45. exp: "todo.title + ' : ' + (todo.done ? 'yep' : 'nope')",
  46. vm: {
  47. todo: {
  48. title: 'write tests',
  49. done: false
  50. }
  51. },
  52. expectedValue: 'write tests : nope'
  53. }
  54. ]
  55. testCases.forEach(describeCase)
  56. function describeCase (testCase) {
  57. describe(testCase.exp, function () {
  58. var result = ExpParser.parse(testCase.exp),
  59. vm = testCase.vm,
  60. vars = Object.keys(vm)
  61. // mock the $get().
  62. // the real $get() will be tested in integration tests.
  63. vm.$get = function (key) { return this[key] }
  64. it('should get correct args', function () {
  65. assert.strictEqual(result.vars.length, vars.length)
  66. for (var i = 0; i < vars.length; i++) {
  67. assert.strictEqual(vars[i], result.vars[i])
  68. }
  69. })
  70. it('should generate correct getter function', function () {
  71. var value = result.getter.call(vm)
  72. assert.strictEqual(value, testCase.expectedValue)
  73. })
  74. })
  75. }
  76. })