viewmodel.js 2.8 KB

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