exp-parser.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. 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 = testCase.paths || 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.paths.length, vars.length)
  66. for (var i = 0; i < vars.length; i++) {
  67. assert.strictEqual(vars[i], result.paths[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. })