exp-parser.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. var ExpParser = require('seed/src/exp-parser')
  2. describe('UNIT: Expression Parser', function () {
  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. vm: {
  46. todo: {
  47. title: 'write tests',
  48. done: false
  49. }
  50. },
  51. expectedValue: 'write tests : nope'
  52. }
  53. ]
  54. testCases.forEach(describeCase)
  55. function describeCase (testCase) {
  56. describe(testCase.exp, function () {
  57. var result = ExpParser.parse(testCase.exp),
  58. vm = testCase.vm,
  59. vars = Object.keys(vm)
  60. // mock the $get().
  61. // the real $get() will be tested in integration tests.
  62. vm.$get = function (key) { return this[key] }
  63. it('should get correct args', function () {
  64. assert.strictEqual(result.vars.length, vars.length)
  65. for (var i = 0; i < vars.length; i++) {
  66. assert.strictEqual(vars[i], result.vars[i])
  67. }
  68. })
  69. it('should generate correct getter function', function () {
  70. var value = result.getter.call(vm)
  71. assert.strictEqual(value, testCase.expectedValue)
  72. })
  73. })
  74. }
  75. })