From 27f2040c556b68180262bda5bd0ca93db95db265 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lucas=20Galfas=C3=B3?= Date: Sun, 15 Dec 2013 21:00:57 -0300 Subject: [PATCH] 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 --- src/ngMock/angular-mocks.js | 12 +++++++----- test/ngMock/angular-mocksSpec.js | 28 +++++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/src/ngMock/angular-mocks.js b/src/ngMock/angular-mocks.js index 24b8d84b9506..7544bb8c4c53 100644 --- a/src/ngMock/angular-mocks.js +++ b/src/ngMock/angular-mocks.js @@ -105,19 +105,21 @@ angular.mock.$Browser = function() { * @param {number=} number of milliseconds to flush. See {@link #defer.now} */ self.defer.flush = function(delay) { - if (angular.isDefined(delay)) { - self.defer.now += delay; - } else { + if (!angular.isDefined(delay)) { if (self.deferredFns.length) { - self.defer.now = self.deferredFns[self.deferredFns.length-1].time; + delay = self.deferredFns[self.deferredFns.length-1].time - self.defer.now; } else { throw new Error('No deferred tasks to be flushed'); } } - while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) { + while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now + delay) { + delay -= (self.deferredFns[0].time - self.defer.now); + self.defer.now = self.deferredFns[0].time; self.deferredFns.shift().fn(); } + + self.defer.now += delay; }; self.$$baseHref = ''; diff --git a/test/ngMock/angular-mocksSpec.js b/test/ngMock/angular-mocksSpec.js index f96112feec7c..d64bb92d105d 100644 --- a/test/ngMock/angular-mocksSpec.js +++ b/test/ngMock/angular-mocksSpec.js @@ -291,8 +291,10 @@ describe('ngMock', function() { expect(counter).toBe(1); $interval.flush(1000); - expect(counter).toBe(2); + + $interval.flush(2000); + expect(counter).toBe(4); })); @@ -656,6 +658,30 @@ describe('ngMock', function() { $timeout.flush(123); expect(count).toBe(2); })); + + it('should resolve timeout functions following the timeline', inject(function($timeout) { + var count1 = 0, count2 = 0; + var iterate1 = function() { + count1++; + $timeout(iterate1, 100); + }; + var iterate2 = function() { + count2++; + $timeout(iterate2, 150); + }; + + $timeout(iterate1, 100); + $timeout(iterate2, 150); + $timeout.flush(150); + expect(count1).toBe(1); + expect(count2).toBe(1); + $timeout.flush(50); + expect(count1).toBe(2); + expect(count2).toBe(1); + $timeout.flush(400); + expect(count1).toBe(6); + expect(count2).toBe(4); + })); });