fix(testing): add discardPeriodicTasks to be used with fakeAsync (#8629)

Closes #8616
This commit is contained in:
Julie Ralph 2016-05-26 10:19:30 -07:00 committed by Miško Hevery
parent b2e804c961
commit 0cb93a436d
3 changed files with 34 additions and 0 deletions

View File

@ -13,6 +13,7 @@ import {
flushMicrotasks, flushMicrotasks,
Log, Log,
tick, tick,
discardPeriodicTasks,
} from '@angular/core/testing'; } from '@angular/core/testing';
import {TimerWrapper, PromiseWrapper} from '../../router/src/facade/async'; import {TimerWrapper, PromiseWrapper} from '../../router/src/facade/async';
import {BaseException} from '../../router/src/facade/exceptions'; import {BaseException} from '../../router/src/facade/exceptions';
@ -204,6 +205,24 @@ export function main() {
expect(cycles).toEqual(1); expect(cycles).toEqual(1);
})); }));
it('should clear periodic timers', fakeAsync(() => {
var cycles = 0;
var id = TimerWrapper.setInterval(() => { cycles++; }, 10);
tick(10);
expect(cycles).toEqual(1);
discardPeriodicTasks();
// Tick once to clear out the timer which already started.
tick(10);
expect(cycles).toEqual(2);
tick(10);
// Nothing should change
expect(cycles).toEqual(2);
}));
it('should process microtasks before timers', fakeAsync(() => { it('should process microtasks before timers', fakeAsync(() => {
var log = new Log(); var log = new Log();
@ -259,6 +278,11 @@ export function main() {
expect(() => { tick(); }) expect(() => { tick(); })
.toThrowError('The code should be running in the fakeAsync zone to call this function'); .toThrowError('The code should be running in the fakeAsync zone to call this function');
}); });
it('calling discardPeriodicTasks should throw', () => {
expect(() => { discardPeriodicTasks() ; })
.toThrowError('The code should be running in the fakeAsync zone to call this function');
});
}); });
}); });
} }

View File

@ -80,6 +80,15 @@ export function tick(millis: number = 0): void {
_getFakeAsyncZoneSpec().tick(millis); _getFakeAsyncZoneSpec().tick(millis);
} }
/**
* Discard all remaining periodic tasks.
*/
export function discardPeriodicTasks(): void {
let zoneSpec = _getFakeAsyncZoneSpec();
let pendingTimers = zoneSpec.pendingPeriodicTimers;
zoneSpec.pendingPeriodicTimers.length = 0;
}
/** /**
* Flush any pending microtasks. * Flush any pending microtasks.
*/ */

View File

@ -350,6 +350,7 @@ var CORE_TESTING: string[] = [
'resetBaseTestProviders', 'resetBaseTestProviders',
'setBaseTestProviders', 'setBaseTestProviders',
'tick', 'tick',
'discardPeriodicTasks',
'withProviders', 'withProviders',
'xdescribe', 'xdescribe',
'xit' 'xit'