/
asyncBehaviors.js
1399 lines (1145 loc) · 56.4 KB
/
asyncBehaviors.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
describe("Throttled observables", function() {
beforeEach(function() { waits(1); }); // Workaround for spurious timing-related failures on IE8 (issue #736)
it("Should notify subscribers asynchronously after writes stop for the specified timeout duration", function() {
var observable = ko.observable('A').extend({ throttle: 100 });
var notifiedValues = [];
observable.subscribe(function(value) {
notifiedValues.push(value);
});
runs(function() {
// Mutate a few times
observable('B');
observable('C');
observable('D');
expect(notifiedValues.length).toEqual(0); // Should not notify synchronously
});
// Wait
waits(10);
runs(function() {
// Mutate more
observable('E');
observable('F');
expect(notifiedValues.length).toEqual(0); // Should not notify until end of throttle timeout
});
// Wait until after timeout
waitsFor(function() {
return notifiedValues.length > 0;
}, 500);
runs(function() {
expect(notifiedValues.length).toEqual(1);
expect(notifiedValues[0]).toEqual("F");
});
});
});
describe("Throttled dependent observables", function() {
beforeEach(function() { waits(1); }); // Workaround for spurious timing-related failures on IE8 (issue #736)
it("Should notify subscribers asynchronously after dependencies stop updating for the specified timeout duration", function() {
var underlying = ko.observable();
var asyncDepObs = ko.dependentObservable(function() {
return underlying();
}).extend({ throttle: 100 });
var notifiedValues = [];
asyncDepObs.subscribe(function(value) {
notifiedValues.push(value);
});
// Check initial state
expect(asyncDepObs()).toBeUndefined();
runs(function() {
// Mutate
underlying('New value');
expect(asyncDepObs()).toBeUndefined(); // Should not update synchronously
expect(notifiedValues.length).toEqual(0);
});
// Still shouldn't have evaluated
waits(10);
runs(function() {
expect(asyncDepObs()).toBeUndefined(); // Should not update until throttle timeout
expect(notifiedValues.length).toEqual(0);
});
// Now wait for throttle timeout
waitsFor(function() {
return notifiedValues.length > 0;
}, 300);
runs(function() {
expect(asyncDepObs()).toEqual('New value');
expect(notifiedValues.length).toEqual(1);
expect(notifiedValues[0]).toEqual('New value');
});
});
it("Should run evaluator only once when dependencies stop updating for the specified timeout duration", function() {
var evaluationCount = 0;
var someDependency = ko.observable();
var asyncDepObs = ko.dependentObservable(function() {
evaluationCount++;
return someDependency();
}).extend({ throttle: 100 });
runs(function() {
// Mutate a few times synchronously
expect(evaluationCount).toEqual(1); // Evaluates synchronously when first created, like all dependent observables
someDependency("A");
someDependency("B");
someDependency("C");
expect(evaluationCount).toEqual(1); // Should not re-evaluate synchronously when dependencies update
});
// Also mutate async
waits(10);
runs(function() {
someDependency("D");
expect(evaluationCount).toEqual(1);
});
// Now wait for throttle timeout
waitsFor(function() {
return evaluationCount > 1;
}, 300);
runs(function() {
expect(evaluationCount).toEqual(2); // Finally, it's evaluated
expect(asyncDepObs()).toEqual("D");
});
});
});
describe('Rate-limited', function() {
beforeEach(function() {
jasmine.Clock.useMock();
});
describe('Subscribable', function() {
it('Should delay change notifications', function() {
var subscribable = new ko.subscribable().extend({rateLimit:500});
var notifySpy = jasmine.createSpy('notifySpy');
subscribable.subscribe(notifySpy);
subscribable.subscribe(notifySpy, null, 'custom');
// "change" notification is delayed
subscribable.notifySubscribers('a', "change");
expect(notifySpy).not.toHaveBeenCalled();
// Default notification is delayed
subscribable.notifySubscribers('b');
expect(notifySpy).not.toHaveBeenCalled();
// Other notifications happen immediately
subscribable.notifySubscribers('c', "custom");
expect(notifySpy).toHaveBeenCalledWith('c');
// Advance clock; Change notification happens now using the latest value notified
notifySpy.reset();
jasmine.Clock.tick(500);
expect(notifySpy).toHaveBeenCalledWith('b');
});
it('Should notify every timeout interval using notifyAtFixedRate method ', function() {
var subscribable = new ko.subscribable().extend({rateLimit:{method:'notifyAtFixedRate', timeout:50}});
var notifySpy = jasmine.createSpy('notifySpy');
subscribable.subscribe(notifySpy);
// Push 10 changes every 25 ms
for (var i = 0; i < 10; ++i) {
subscribable.notifySubscribers(i+1);
jasmine.Clock.tick(25);
}
// Notification happens every 50 ms, so every other number is notified
expect(notifySpy.calls.length).toBe(5);
expect(notifySpy.argsForCall).toEqual([ [2], [4], [6], [8], [10] ]);
// No more notifications happen
notifySpy.reset();
jasmine.Clock.tick(50);
expect(notifySpy).not.toHaveBeenCalled();
});
it('Should notify after nothing happens for the timeout period using notifyWhenChangesStop method', function() {
var subscribable = new ko.subscribable().extend({rateLimit:{method:'notifyWhenChangesStop', timeout:50}});
var notifySpy = jasmine.createSpy('notifySpy');
subscribable.subscribe(notifySpy);
// Push 10 changes every 25 ms
for (var i = 0; i < 10; ++i) {
subscribable.notifySubscribers(i+1);
jasmine.Clock.tick(25);
}
// No notifications happen yet
expect(notifySpy).not.toHaveBeenCalled();
// Notification happens after the timeout period
jasmine.Clock.tick(50);
expect(notifySpy.calls.length).toBe(1);
expect(notifySpy).toHaveBeenCalledWith(10);
});
it('Should use latest settings when applied multiple times', function() {
var subscribable = new ko.subscribable().extend({rateLimit:250}).extend({rateLimit:500});
var notifySpy = jasmine.createSpy('notifySpy');
subscribable.subscribe(notifySpy);
subscribable.notifySubscribers('a');
jasmine.Clock.tick(250);
expect(notifySpy).not.toHaveBeenCalled();
jasmine.Clock.tick(250);
expect(notifySpy).toHaveBeenCalledWith('a');
});
it('Uses latest settings for future notification and previous settings for pending notification', function() {
// This test describes the current behavior for the given scenario but is not a contract for that
// behavior, which could change in the future if convenient.
var subscribable = new ko.subscribable().extend({rateLimit:250});
var notifySpy = jasmine.createSpy('notifySpy');
subscribable.subscribe(notifySpy);
subscribable.notifySubscribers('a'); // Pending notification
// Apply new setting and schedule new notification
subscribable = subscribable.extend({rateLimit:500});
subscribable.notifySubscribers('b');
// First notification happens using original settings
jasmine.Clock.tick(250);
expect(notifySpy).toHaveBeenCalledWith('a');
// Second notification happends using later settings
notifySpy.reset();
jasmine.Clock.tick(250);
expect(notifySpy).toHaveBeenCalledWith('b');
});
it('Should return "[object Object]" with .toString', function() {
// Issue #2252: make sure .toString method does not throw error
expect(new ko.subscribable().toString()).toBe('[object Object]')
});
});
describe('Observable', function() {
it('Should delay change notifications', function() {
var observable = ko.observable().extend({rateLimit:500});
var notifySpy = jasmine.createSpy('notifySpy');
observable.subscribe(notifySpy);
var beforeChangeSpy = jasmine.createSpy('beforeChangeSpy')
.andCallFake(function(value) {expect(observable()).toBe(value); });
observable.subscribe(beforeChangeSpy, null, 'beforeChange');
// Observable is changed, but notification is delayed
observable('a');
expect(observable()).toEqual('a');
expect(notifySpy).not.toHaveBeenCalled();
expect(beforeChangeSpy).toHaveBeenCalledWith(undefined); // beforeChange notification happens right away
// Second change notification is also delayed
observable('b');
expect(notifySpy).not.toHaveBeenCalled();
// Advance clock; Change notification happens now using the latest value notified
jasmine.Clock.tick(500);
expect(notifySpy).toHaveBeenCalledWith('b');
expect(beforeChangeSpy.calls.length).toBe(1); // Only one beforeChange notification
});
it('Should notify "spectator" subscribers whenever the value changes', function () {
var observable = new ko.observable('A').extend({rateLimit:500}),
spectateSpy = jasmine.createSpy('notifySpy'),
notifySpy = jasmine.createSpy('notifySpy');
observable.subscribe(spectateSpy, null, "spectate");
observable.subscribe(notifySpy);
expect(spectateSpy).not.toHaveBeenCalled();
expect(notifySpy).not.toHaveBeenCalled();
observable('B');
expect(spectateSpy).toHaveBeenCalledWith('B');
observable('C');
expect(spectateSpy).toHaveBeenCalledWith('C');
expect(notifySpy).not.toHaveBeenCalled();
jasmine.Clock.tick(500);
// "spectate" was called for each new value
expect(spectateSpy.argsForCall).toEqual([ ['B'], ['C'] ]);
// whereas "change" was only called for the final value
expect(notifySpy.argsForCall).toEqual([ ['C'] ]);
});
it('Should suppress change notification when value is changed/reverted', function() {
var observable = ko.observable('original').extend({rateLimit:500});
var notifySpy = jasmine.createSpy('notifySpy');
observable.subscribe(notifySpy);
var beforeChangeSpy = jasmine.createSpy('beforeChangeSpy');
observable.subscribe(beforeChangeSpy, null, 'beforeChange');
observable('new'); // change value
expect(observable()).toEqual('new'); // access observable to make sure it really has the changed value
observable('original'); // but then change it back
expect(notifySpy).not.toHaveBeenCalled();
jasmine.Clock.tick(500);
expect(notifySpy).not.toHaveBeenCalled();
// Check that value is correct and notification hasn't happened
expect(observable()).toEqual('original');
expect(notifySpy).not.toHaveBeenCalled();
// Changing observable to a new value still works as expected
observable('new');
jasmine.Clock.tick(500);
expect(notifySpy).toHaveBeenCalledWith('new');
expect(beforeChangeSpy).toHaveBeenCalledWith('original');
expect(beforeChangeSpy).not.toHaveBeenCalledWith('new');
});
it('Should support notifications from nested update', function() {
var observable = ko.observable('a').extend({rateLimit:500});
var notifySpy = jasmine.createSpy('notifySpy');
observable.subscribe(notifySpy);
// Create a one-time subscription that will modify the observable
var updateSub = observable.subscribe(function() {
updateSub.dispose();
observable('z');
});
observable('b');
expect(notifySpy).not.toHaveBeenCalled();
expect(observable()).toEqual('b');
notifySpy.reset();
jasmine.Clock.tick(500);
expect(notifySpy).toHaveBeenCalledWith('b');
expect(observable()).toEqual('z');
notifySpy.reset();
jasmine.Clock.tick(500);
expect(notifySpy).toHaveBeenCalledWith('z');
});
it('Should suppress notifications when value is changed/reverted from nested update', function() {
var observable = ko.observable('a').extend({rateLimit:500});
var notifySpy = jasmine.createSpy('notifySpy');
observable.subscribe(notifySpy);
// Create a one-time subscription that will modify the observable and then revert the change
var updateSub = observable.subscribe(function(newValue) {
updateSub.dispose();
observable('z');
observable(newValue);
});
observable('b');
expect(notifySpy).not.toHaveBeenCalled();
expect(observable()).toEqual('b');
notifySpy.reset();
jasmine.Clock.tick(500);
expect(notifySpy).toHaveBeenCalledWith('b');
expect(observable()).toEqual('b');
notifySpy.reset();
jasmine.Clock.tick(500);
expect(notifySpy).not.toHaveBeenCalled();
});
it('Should not notify future subscribers', function() {
var observable = ko.observable('a').extend({rateLimit:500}),
notifySpy1 = jasmine.createSpy('notifySpy1'),
notifySpy2 = jasmine.createSpy('notifySpy2'),
notifySpy3 = jasmine.createSpy('notifySpy3');
observable.subscribe(notifySpy1);
observable('b');
observable.subscribe(notifySpy2);
observable('c');
observable.subscribe(notifySpy3);
expect(notifySpy1).not.toHaveBeenCalled();
expect(notifySpy2).not.toHaveBeenCalled();
expect(notifySpy3).not.toHaveBeenCalled();
jasmine.Clock.tick(500);
expect(notifySpy1).toHaveBeenCalledWith('c');
expect(notifySpy2).toHaveBeenCalledWith('c');
expect(notifySpy3).not.toHaveBeenCalled();
});
it('Should delay update of dependent computed observable', function() {
var observable = ko.observable().extend({rateLimit:500});
var computed = ko.computed(observable);
// Check initial value
expect(computed()).toBeUndefined();
// Observable is changed, but computed is not
observable('a');
expect(observable()).toEqual('a');
expect(computed()).toBeUndefined();
// Second change also
observable('b');
expect(computed()).toBeUndefined();
// Advance clock; Change notification happens now using the latest value notified
jasmine.Clock.tick(500);
expect(computed()).toEqual('b');
});
it('Should delay update of dependent pure computed observable', function() {
var observable = ko.observable().extend({rateLimit:500});
var computed = ko.pureComputed(observable);
// Check initial value
expect(computed()).toBeUndefined();
// Observable is changed, but computed is not
observable('a');
expect(observable()).toEqual('a');
expect(computed()).toBeUndefined();
// Second change also
observable('b');
expect(computed()).toBeUndefined();
// Advance clock; Change notification happens now using the latest value notified
jasmine.Clock.tick(500);
expect(computed()).toEqual('b');
});
it('Should not update dependent computed created after last update', function() {
var observable = ko.observable('a').extend({rateLimit:500});
observable('b');
var evalSpy = jasmine.createSpy('evalSpy');
var computed = ko.computed(function () {
return evalSpy(observable());
});
expect(evalSpy).toHaveBeenCalledWith('b');
evalSpy.reset();
jasmine.Clock.tick(500);
expect(evalSpy).not.toHaveBeenCalled();
});
it('Should not cause loss of updates when an intermediate value is read by a dependent computed observable', function() {
// From https://github.com/knockout/knockout/issues/1835
var one = ko.observable(false).extend({rateLimit: 100}),
two = ko.observable(false),
three = ko.computed(function() { return one() || two(); }),
threeNotifications = [];
three.subscribe(function(val) {
threeNotifications.push(val);
});
// The loop shows that the same steps work continuously
for (var i = 0; i < 3; i++) {
expect(one() || two() || three()).toEqual(false);
threeNotifications = [];
one(true);
expect(threeNotifications).toEqual([]);
two(true);
expect(threeNotifications).toEqual([true]);
two(false);
expect(threeNotifications).toEqual([true]);
one(false);
expect(threeNotifications).toEqual([true]);
jasmine.Clock.tick(100);
expect(threeNotifications).toEqual([true, false]);
}
});
});
describe('Observable Array change tracking', function() {
it('Should provide correct changelist when multiple updates are merged into one notification', function() {
var myArray = ko.observableArray(['Alpha', 'Beta']).extend({rateLimit:1}),
changelist;
myArray.subscribe(function(changes) {
changelist = changes;
}, null, 'arrayChange');
myArray.push('Gamma');
myArray.push('Delta');
jasmine.Clock.tick(10);
expect(changelist).toEqual([
{ status : 'added', value : 'Gamma', index : 2 },
{ status : 'added', value : 'Delta', index : 3 }
]);
changelist = undefined;
myArray.shift();
myArray.shift();
jasmine.Clock.tick(10);
expect(changelist).toEqual([
{ status : 'deleted', value : 'Alpha', index : 0 },
{ status : 'deleted', value : 'Beta', index : 1 }
]);
changelist = undefined;
myArray.push('Epsilon');
myArray.pop();
jasmine.Clock.tick(10);
expect(changelist).toEqual(undefined);
});
});
describe('Computed Observable', function() {
it('Should delay running evaluator where there are no subscribers', function() {
var observable = ko.observable();
var evalSpy = jasmine.createSpy('evalSpy');
var computed = ko.computed(function () { evalSpy(observable()); return observable(); }).extend({rateLimit:500});
// Observable is changed, but evaluation is delayed
evalSpy.reset();
observable('a');
observable('b');
expect(evalSpy).not.toHaveBeenCalled();
// Advance clock; Change notification happens now using the latest value notified
evalSpy.reset();
jasmine.Clock.tick(500);
expect(evalSpy).toHaveBeenCalledWith('b');
});
it('Should delay change notifications and evaluation', function() {
var observable = ko.observable();
var evalSpy = jasmine.createSpy('evalSpy');
var computed = ko.computed(function () { evalSpy(observable()); return observable(); }).extend({rateLimit:500});
var notifySpy = jasmine.createSpy('notifySpy');
computed.subscribe(notifySpy);
var beforeChangeSpy = jasmine.createSpy('beforeChangeSpy')
.andCallFake(function(value) {expect(computed()).toBe(value); });
computed.subscribe(beforeChangeSpy, null, 'beforeChange');
// Observable is changed, but notification is delayed
evalSpy.reset();
observable('a');
expect(evalSpy).not.toHaveBeenCalled();
expect(computed()).toEqual('a');
expect(evalSpy).toHaveBeenCalledWith('a'); // evaluation happens when computed is accessed
expect(notifySpy).not.toHaveBeenCalled(); // but notification is still delayed
expect(beforeChangeSpy).toHaveBeenCalledWith(undefined); // beforeChange notification happens right away
// Second change notification is also delayed
evalSpy.reset();
observable('b');
expect(computed.peek()).toEqual('a'); // peek returns previously evaluated value
expect(evalSpy).not.toHaveBeenCalled();
expect(notifySpy).not.toHaveBeenCalled();
// Advance clock; Change notification happens now using the latest value notified
evalSpy.reset();
jasmine.Clock.tick(500);
expect(evalSpy).toHaveBeenCalledWith('b');
expect(notifySpy).toHaveBeenCalledWith('b');
expect(beforeChangeSpy.calls.length).toBe(1); // Only one beforeChange notification
});
it('Should run initial evaluation at first subscribe when using deferEvaluation', function() {
// This behavior means that code using rate-limited computeds doesn't need to care if the
// computed also has deferEvaluation. For example, the preceding test ('Should delay change
// notifications and evaluation') will pass just as well if using deferEvaluation.
var observable = ko.observable('a');
var evalSpy = jasmine.createSpy('evalSpy');
var computed = ko.computed({
read: function () {
evalSpy(observable());
return observable();
},
deferEvaluation: true
}).extend({rateLimit:500});
expect(evalSpy).not.toHaveBeenCalled();
var notifySpy = jasmine.createSpy('notifySpy');
computed.subscribe(notifySpy);
expect(evalSpy).toHaveBeenCalledWith('a');
expect(notifySpy).not.toHaveBeenCalled();
});
it('Should run initial evaluation when observable is accessed when using deferEvaluation', function() {
var observable = ko.observable('a');
var evalSpy = jasmine.createSpy('evalSpy');
var computed = ko.computed({
read: function () {
evalSpy(observable());
return observable();
},
deferEvaluation: true
}).extend({rateLimit:500});
expect(evalSpy).not.toHaveBeenCalled();
expect(computed()).toEqual('a');
expect(evalSpy).toHaveBeenCalledWith('a');
});
it('Should suppress change notifications when value is changed/reverted', function() {
var observable = ko.observable('original');
var computed = ko.computed(function () { return observable(); }).extend({rateLimit:500});
var notifySpy = jasmine.createSpy('notifySpy');
computed.subscribe(notifySpy);
var beforeChangeSpy = jasmine.createSpy('beforeChangeSpy');
computed.subscribe(beforeChangeSpy, null, 'beforeChange');
observable('new'); // change value
expect(computed()).toEqual('new'); // access computed to make sure it really has the changed value
observable('original'); // and then change the value back
expect(notifySpy).not.toHaveBeenCalled();
jasmine.Clock.tick(500);
expect(notifySpy).not.toHaveBeenCalled();
// Check that value is correct and notification hasn't happened
expect(computed()).toEqual('original');
expect(notifySpy).not.toHaveBeenCalled();
// Changing observable to a new value still works as expected
observable('new');
jasmine.Clock.tick(500);
expect(notifySpy).toHaveBeenCalledWith('new');
expect(beforeChangeSpy).toHaveBeenCalledWith('original');
expect(beforeChangeSpy).not.toHaveBeenCalledWith('new');
});
it('Should not re-evaluate if computed is disposed before timeout', function() {
var observable = ko.observable('a');
var evalSpy = jasmine.createSpy('evalSpy');
var computed = ko.computed(function () { evalSpy(observable()); return observable(); }).extend({rateLimit:500});
expect(computed()).toEqual('a');
expect(evalSpy.calls.length).toBe(1);
expect(evalSpy).toHaveBeenCalledWith('a');
evalSpy.reset();
observable('b');
computed.dispose();
jasmine.Clock.tick(500);
expect(computed()).toEqual('a');
expect(evalSpy).not.toHaveBeenCalled();
});
it('Should be able to re-evaluate a computed that previously threw an exception', function() {
var observableSwitch = ko.observable(true), observableValue = ko.observable(1),
computed = ko.computed(function() {
if (!observableSwitch()) {
throw Error("Error during computed evaluation");
} else {
return observableValue();
}
}).extend({rateLimit:500});
// Initially the computed evaluated successfully
expect(computed()).toEqual(1);
expect(function () {
// Update observable to cause computed to throw an exception
observableSwitch(false);
computed();
}).toThrow("Error during computed evaluation");
// The value of the computed is now undefined, although currently it keeps the previous value
// This should not try to re-evaluate and thus shouldn't throw an exception
expect(computed()).toEqual(1);
// The computed should not be dependent on the second observable
expect(computed.getDependenciesCount()).toEqual(1);
expect(computed.getDependencies()).toEqual([observableSwitch]);
// Updating the second observable shouldn't re-evaluate computed
observableValue(2);
expect(computed()).toEqual(1);
// Update the first observable to cause computed to re-evaluate
observableSwitch(1);
expect(computed()).toEqual(2);
});
it('Should delay update of dependent computed observable', function() {
var observable = ko.observable();
var rateLimitComputed = ko.computed(observable).extend({rateLimit:500});
var dependentComputed = ko.computed(rateLimitComputed);
// Check initial value
expect(dependentComputed()).toBeUndefined();
// Rate-limited computed is changed, but dependent computed is not
observable('a');
expect(rateLimitComputed()).toEqual('a');
expect(dependentComputed()).toBeUndefined();
// Second change also
observable('b');
expect(dependentComputed()).toBeUndefined();
// Advance clock; Change notification happens now using the latest value notified
jasmine.Clock.tick(500);
expect(dependentComputed()).toEqual('b');
});
it('Should delay update of dependent pure computed observable', function() {
var observable = ko.observable();
var rateLimitComputed = ko.computed(observable).extend({rateLimit:500});
var dependentComputed = ko.pureComputed(rateLimitComputed);
// Check initial value
expect(dependentComputed()).toBeUndefined();
// Rate-limited computed is changed, but dependent computed is not
observable('a');
expect(rateLimitComputed()).toEqual('a');
expect(dependentComputed()).toBeUndefined();
// Second change also
observable('b');
expect(dependentComputed()).toBeUndefined();
// Advance clock; Change notification happens now using the latest value notified
jasmine.Clock.tick(500);
expect(dependentComputed()).toEqual('b');
});
it('Should not cause loss of updates when an intermediate value is read by a dependent computed observable', function() {
// From https://github.com/knockout/knockout/issues/1835
var one = ko.observable(false),
onePointOne = ko.computed(one).extend({rateLimit: 100}),
two = ko.observable(false),
three = ko.computed(function() { return onePointOne() || two(); }),
threeNotifications = [];
three.subscribe(function(val) {
threeNotifications.push(val);
});
// The loop shows that the same steps work continuously
for (var i = 0; i < 3; i++) {
expect(onePointOne() || two() || three()).toEqual(false);
threeNotifications = [];
one(true);
expect(threeNotifications).toEqual([]);
two(true);
expect(threeNotifications).toEqual([true]);
two(false);
expect(threeNotifications).toEqual([true]);
one(false);
expect(threeNotifications).toEqual([true]);
jasmine.Clock.tick(100);
expect(threeNotifications).toEqual([true, false]);
}
});
});
describe('with custom function', function() {
it('that notifies synchronously', function() {
var customFuncSpy = jasmine.createSpy('customFuncSpy');
function notifySync(callback) {
return customFuncSpy.andCallFake(callback);
}
var observable = ko.observable().extend({rateLimit: { method: notifySync }});
var notifySpy = jasmine.createSpy('notifySpy');
observable.subscribe(notifySpy);
expect(customFuncSpy).not.toHaveBeenCalled();
observable('a');
expect(customFuncSpy).toHaveBeenCalled();
expect(notifySpy.argsForCall).toEqual([ ['a'] ]);
customFuncSpy.reset();
notifySpy.reset();
observable('b');
expect(customFuncSpy).toHaveBeenCalled();
expect(notifySpy.argsForCall).toEqual([ ['b'] ]);
});
it('that takes custom options', function() {
// This debounce function will check for an 'immediate' option
function debounce(callback, timeout, options) {
var timeoutInstance;
if (options.immediate) {
return function () {
var callnow = !timeoutInstance;
clearTimeout(timeoutInstance);
timeoutInstance = ko.utils.setTimeout(function() {
timeoutInstance = null;
callback();
}, timeout);
if (callnow) {
callback();
}
};
} else {
throw Error("test expects immediate = true");
}
}
var observable = ko.observable().extend({rateLimit: {method: debounce, timeout: 500, immediate: true} });
var notifySpy = jasmine.createSpy('notifySpy');
observable.subscribe(notifySpy);
var times = 5;
while (--times) { // Verify that it works repeatedly
// Observable is changed, initial notification happens immediately
notifySpy.reset();
observable('a');
expect(observable()).toEqual('a');
expect(notifySpy.argsForCall).toEqual([ ['a'] ]);
// Second change notification is delayed
notifySpy.reset();
observable('b');
expect(notifySpy).not.toHaveBeenCalled();
// Advance clock; Change notification happens now using the latest value notified
jasmine.Clock.tick(500);
expect(notifySpy.argsForCall).toEqual([ ['b'] ]);
}
});
});
});
describe('Deferred', function() {
beforeEach(function() {
jasmine.Clock.useMockForTasks();
});
afterEach(function() {
expect(ko.tasks.resetForTesting()).toEqual(0);
jasmine.Clock.reset();
});
describe('Observable', function() {
it('Should delay notifications', function() {
var observable = ko.observable().extend({deferred:true});
var notifySpy = jasmine.createSpy('notifySpy');
observable.subscribe(notifySpy);
observable('A');
expect(notifySpy).not.toHaveBeenCalled();
jasmine.Clock.tick(1);
expect(notifySpy.argsForCall).toEqual([ ['A'] ]);
});
it('Should throw if you attempt to turn off deferred', function() {
// As of commit 6d5d786, the 'deferred' option cannot be deactivated (once activated for
// a given observable).
var observable = ko.observable();
observable.extend({deferred: true});
expect(function() {
observable.extend({deferred: false});
}).toThrow('The \'deferred\' extender only accepts the value \'true\', because it is not supported to turn deferral off once enabled.');
});
it('Should notify subscribers about only latest value', function() {
var observable = ko.observable().extend({notify:'always', deferred:true}); // include notify:'always' to ensure notifications weren't suppressed by some other means
var notifySpy = jasmine.createSpy('notifySpy');
observable.subscribe(notifySpy);
observable('A');
observable('B');
jasmine.Clock.tick(1);
expect(notifySpy.argsForCall).toEqual([ ['B'] ]);
});
it('Should suppress notification when value is changed/reverted', function() {
var observable = ko.observable('original').extend({deferred:true});
var notifySpy = jasmine.createSpy('notifySpy');
observable.subscribe(notifySpy);
observable('new');
expect(observable()).toEqual('new');
observable('original');
jasmine.Clock.tick(1);
expect(notifySpy).not.toHaveBeenCalled();
expect(observable()).toEqual('original');
});
it('Should not notify future subscribers', function() {
var observable = ko.observable('a').extend({deferred:true}),
notifySpy1 = jasmine.createSpy('notifySpy1'),
notifySpy2 = jasmine.createSpy('notifySpy2'),
notifySpy3 = jasmine.createSpy('notifySpy3');
observable.subscribe(notifySpy1);
observable('b');
observable.subscribe(notifySpy2);
observable('c');
observable.subscribe(notifySpy3);
expect(notifySpy1).not.toHaveBeenCalled();
expect(notifySpy2).not.toHaveBeenCalled();
expect(notifySpy3).not.toHaveBeenCalled();
jasmine.Clock.tick(1);
expect(notifySpy1).toHaveBeenCalledWith('c');
expect(notifySpy2).toHaveBeenCalledWith('c');
expect(notifySpy3).not.toHaveBeenCalled();
});
it('Should not update dependent computed created after last update', function() {
var observable = ko.observable('a').extend({deferred:true});
observable('b');
var evalSpy = jasmine.createSpy('evalSpy');
var computed = ko.computed(function () {
return evalSpy(observable());
});
expect(evalSpy).toHaveBeenCalledWith('b');
evalSpy.reset();
jasmine.Clock.tick(1);
expect(evalSpy).not.toHaveBeenCalled();
});
it('Is default behavior when "ko.options.deferUpdates" is "true"', function() {
this.restoreAfter(ko.options, 'deferUpdates');
ko.options.deferUpdates = true;
var observable = ko.observable();
var notifySpy = jasmine.createSpy('notifySpy');
observable.subscribe(notifySpy);
observable('A');
expect(notifySpy).not.toHaveBeenCalled();
jasmine.Clock.tick(1);
expect(notifySpy.argsForCall).toEqual([ ['A'] ]);
});
});
describe('Observable Array change tracking', function() {
it('Should provide correct changelist when multiple updates are merged into one notification', function() {
var myArray = ko.observableArray(['Alpha', 'Beta']).extend({deferred:true}),
changelist;
myArray.subscribe(function(changes) {
changelist = changes;
}, null, 'arrayChange');
myArray.push('Gamma');
myArray.push('Delta');
jasmine.Clock.tick(1);
expect(changelist).toEqual([
{ status : 'added', value : 'Gamma', index : 2 },
{ status : 'added', value : 'Delta', index : 3 }
]);
changelist = undefined;
myArray.shift();
myArray.shift();
jasmine.Clock.tick(1);
expect(changelist).toEqual([
{ status : 'deleted', value : 'Alpha', index : 0 },
{ status : 'deleted', value : 'Beta', index : 1 }
]);
changelist = undefined;
myArray.push('Epsilon');
myArray.pop();
jasmine.Clock.tick(1);
expect(changelist).toEqual(undefined);
});
});
describe('Computed Observable', function() {
it('Should defer notification of changes and minimize evaluation', function () {
var timesEvaluated = 0,
data = ko.observable('A'),
computed = ko.computed(function () { ++timesEvaluated; return data(); }).extend({deferred:true}),
notifySpy = jasmine.createSpy('notifySpy'),
subscription = computed.subscribe(notifySpy);
expect(computed()).toEqual('A');
expect(timesEvaluated).toEqual(1);
jasmine.Clock.tick(1);
expect(notifySpy).not.toHaveBeenCalled();
data('B');
expect(timesEvaluated).toEqual(1); // not immediately evaluated
expect(computed()).toEqual('B');
expect(timesEvaluated).toEqual(2);
expect(notifySpy).not.toHaveBeenCalled();
jasmine.Clock.tick(1);
expect(notifySpy.calls.length).toEqual(1);
expect(notifySpy.argsForCall).toEqual([ ['B'] ]);
});
it('Should notify first change of computed with deferEvaluation if value is changed to undefined', function () {
var data = ko.observable('A'),
computed = ko.computed(data, null, {deferEvaluation: true}).extend({deferred:true}),
notifySpy = jasmine.createSpy('notifySpy'),
subscription = computed.subscribe(notifySpy);
expect(computed()).toEqual('A');
data(undefined);
expect(computed()).toEqual(undefined);
expect(notifySpy).not.toHaveBeenCalled();
jasmine.Clock.tick(1);
expect(notifySpy.calls.length).toEqual(1);
expect(notifySpy.argsForCall).toEqual([ [undefined] ]);
});