viewmodel.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /*
  2. * Only tests the following:
  3. * - .$get()
  4. * - .$set()
  5. * - .$watch()
  6. * - .$unwatch()
  7. */
  8. var seed = require('seed')
  9. describe('UNIT: ViewModel', function () {
  10. mock('vm-test', '{{a.b.c}}')
  11. var data = {
  12. b: {
  13. c: 12345
  14. }
  15. },
  16. arr = [1, 2, 3],
  17. vm = seed.compile('#vm-test', {
  18. data: {
  19. a: data,
  20. b: arr
  21. }
  22. })
  23. describe('.$get()', function () {
  24. it('should retrieve correct value', function () {
  25. assert.strictEqual(vm.$get('a.b.c'), data.b.c)
  26. })
  27. })
  28. describe('.$set()', function () {
  29. vm.$set('a.b.c', 54321)
  30. it('should set correct value', function () {
  31. assert.strictEqual(data.b.c, 54321)
  32. })
  33. })
  34. describe('.$watch()', function () {
  35. it('should trigger callback when a plain value changes', function () {
  36. var val
  37. vm.$watch('a.b.c', function (newVal) {
  38. val = newVal
  39. })
  40. data.b.c = 'new value!'
  41. assert.strictEqual(val, data.b.c)
  42. })
  43. it('should trigger callback when an object value changes', function () {
  44. var val, subVal, rootVal,
  45. target = { c: 'hohoho' }
  46. vm.$watch('a.b', function (newVal) {
  47. val = newVal
  48. })
  49. vm.$watch('a.b.c', function (newVal) {
  50. subVal = newVal
  51. })
  52. vm.$watch('a', function (newVal) {
  53. rootVal = newVal
  54. })
  55. data.b = target
  56. assert.strictEqual(val, target)
  57. assert.strictEqual(subVal, target.c)
  58. vm.a = 'hehehe'
  59. assert.strictEqual(rootVal, 'hehehe')
  60. })
  61. it('should trigger callback when an array mutates', function () {
  62. var val, mut
  63. vm.$watch('b', function (array, mutation) {
  64. val = array
  65. mut = mutation
  66. })
  67. arr.push(4)
  68. assert.strictEqual(val, arr)
  69. assert.strictEqual(mut.method, 'push')
  70. assert.strictEqual(mut.args.length, 1)
  71. assert.strictEqual(mut.args[0], 4)
  72. })
  73. })
  74. describe('.$unwatch()', function () {
  75. it('should unwatch the stuff', function () {
  76. var triggered = false
  77. vm.$watch('a.b.c', function (newVal) {
  78. triggered = true
  79. })
  80. vm.$watch('a', function (newVal) {
  81. triggered = true
  82. })
  83. vm.$watch('b', function (newVal) {
  84. triggered = true
  85. })
  86. vm.$unwatch('a')
  87. vm.$unwatch('b')
  88. vm.$unwatch('a.b.c')
  89. vm.a = { b: { c:123123 }}
  90. vm.b.push(5)
  91. assert.notOk(triggered)
  92. })
  93. })
  94. })