Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Pr 5420: fix($timeout.$flush): make $flush follow the timeline #14686

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions src/ngMock/angular-mocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,19 +106,29 @@ angular.mock.$Browser = function() {
* @param {number=} number of milliseconds to flush. See {@link #defer.now}
*/
self.defer.flush = function(delay) {
var nextTime;

if (angular.isDefined(delay)) {
self.defer.now += delay;
// A delay was passed so compute the next time
nextTime = self.defer.now + delay;
} else {
if (self.deferredFns.length) {
self.defer.now = self.deferredFns[self.deferredFns.length - 1].time;
// No delay was passed so set the next time so that it clears the deferred queue
nextTime = self.deferredFns[self.deferredFns.length - 1].time;
} else {
// No delay passed, but there are no deferred tasks so flush - indicates an error!
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 <= nextTime) {
// Increment the time and call the next deferred function
self.defer.now = self.deferredFns[0].time;
self.deferredFns.shift().fn();
}

// Ensure that the current time is correct
self.defer.now = nextTime;
};

self.$$baseHref = '/';
Expand Down
28 changes: 27 additions & 1 deletion test/ngMock/angular-mocksSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -296,8 +296,10 @@ describe('ngMock', function() {
expect(counter).toBe(1);

$interval.flush(1000);

expect(counter).toBe(2);

$interval.flush(2000);
expect(counter).toBe(4);
}));


Expand Down Expand Up @@ -692,6 +694,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);
}));
});


Expand Down