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

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

Closed
wants to merge 1 commit 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
12 changes: 7 additions & 5 deletions src/ngMock/angular-mocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '';
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 @@ -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);
}));


Expand Down Expand Up @@ -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);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess that we don't need to worry about self-referencing timeouts being left around since they are mocked up anyway?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is all mock code, if there is a need to clean this up, please let me know

};
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