Skip to content

Commit 7a96add

Browse files
lgalfasopetebacondarwin
authored andcommitted
fix($timeout.$flush): make $flush aware of $timeout calls during $flush
Fix an issue when flushing a $timeout function and, this function, calls $timeout once again. When this is the case, the new timeout function should be called at the thoerical `now` of when the function was called plus the new period
1 parent 55b7f7d commit 7a96add

File tree

2 files changed

+41
-11
lines changed

2 files changed

+41
-11
lines changed

src/ngMock/angular-mocks.js

+14-10
Original file line numberDiff line numberDiff line change
@@ -106,18 +106,22 @@ angular.mock.$Browser = function() {
106106
* @param {number=} number of milliseconds to flush. See {@link #defer.now}
107107
*/
108108
self.defer.flush = function(delay) {
109-
if (angular.isDefined(delay)) {
110-
self.defer.now += delay;
111-
} else {
112-
if (self.deferredFns.length) {
113-
self.defer.now = self.deferredFns[self.deferredFns.length - 1].time;
114-
} else {
115-
throw new Error('No deferred tasks to be flushed');
109+
try {
110+
if (!angular.isDefined(delay)) {
111+
if (self.deferredFns.length) {
112+
delay = self.deferredFns[self.deferredFns.length-1].time - self.defer.now;
113+
} else {
114+
throw new Error('No deferred tasks to be flushed');
115+
}
116116
}
117-
}
118117

119-
while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
120-
self.deferredFns.shift().fn();
118+
while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now + delay) {
119+
delay -= (self.deferredFns[0].time - self.defer.now);
120+
self.defer.now = self.deferredFns[0].time;
121+
self.deferredFns.shift().fn();
122+
}
123+
} finally {
124+
self.defer.now += delay;
121125
}
122126
};
123127

test/ngMock/angular-mocksSpec.js

+27-1
Original file line numberDiff line numberDiff line change
@@ -296,8 +296,10 @@ describe('ngMock', function() {
296296
expect(counter).toBe(1);
297297

298298
$interval.flush(1000);
299-
300299
expect(counter).toBe(2);
300+
301+
$interval.flush(2000);
302+
expect(counter).toBe(4);
301303
}));
302304

303305

@@ -692,6 +694,30 @@ describe('ngMock', function() {
692694
$timeout.flush(123);
693695
expect(count).toBe(2);
694696
}));
697+
698+
it('should resolve timeout functions following the timeline', inject(function($timeout) {
699+
var count1 = 0, count2 = 0;
700+
var iterate1 = function() {
701+
count1++;
702+
$timeout(iterate1, 100);
703+
};
704+
var iterate2 = function() {
705+
count2++;
706+
$timeout(iterate2, 150);
707+
};
708+
709+
$timeout(iterate1, 100);
710+
$timeout(iterate2, 150);
711+
$timeout.flush(150);
712+
expect(count1).toBe(1);
713+
expect(count2).toBe(1);
714+
$timeout.flush(50);
715+
expect(count1).toBe(2);
716+
expect(count2).toBe(1);
717+
$timeout.flush(400);
718+
expect(count1).toBe(6);
719+
expect(count2).toBe(4);
720+
}));
695721
});
696722

697723

0 commit comments

Comments
 (0)