angular/packages/core/testing/src/fake_async.ts
2018-04-04 08:24:02 -07:00

116 lines
3.0 KiB
TypeScript

/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {discardPeriodicTasksFallback, fakeAsyncFallback, flushFallback, flushMicrotasksFallback, resetFakeAsyncZoneFallback, tickFallback} from './fake_async_fallback';
const _Zone: any = typeof Zone !== 'undefined' ? Zone : null;
const fakeAsyncTestModule = _Zone && _Zone[_Zone.__symbol__('fakeAsyncTest')];
/**
* Clears out the shared fake async zone for a test.
* To be called in a global `beforeEach`.
*
* @experimental
*/
export function resetFakeAsyncZone(): void {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.resetFakeAsyncZone();
} else {
return resetFakeAsyncZoneFallback();
}
}
/**
* Wraps a function to be executed in the fakeAsync zone:
* - microtasks are manually executed by calling `flushMicrotasks()`,
* - timers are synchronous, `tick()` simulates the asynchronous passage of time.
*
* If there are any pending timers at the end of the function, an exception will be thrown.
*
* Can be used to wrap inject() calls.
*
* ## Example
*
* {@example core/testing/ts/fake_async.ts region='basic'}
*
* @param fn
* @returns The function wrapped to be executed in the fakeAsync zone
*
* @experimental
*/
export function fakeAsync(fn: Function): (...args: any[]) => any {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.fakeAsync(fn);
} else {
return fakeAsyncFallback(fn);
}
}
/**
* Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
*
* The microtasks queue is drained at the very start of this function and after any timer callback
* has been executed.
*
* ## Example
*
* {@example core/testing/ts/fake_async.ts region='basic'}
*
* @experimental
*/
export function tick(millis: number = 0): void {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.tick(millis);
} else {
return tickFallback(millis);
}
}
/**
* Simulates the asynchronous passage of time for the timers in the fakeAsync zone by
* draining the macrotask queue until it is empty. The returned value is the milliseconds
* of time that would have been elapsed.
*
* @param maxTurns
* @returns The simulated time elapsed, in millis.
*
* @experimental
*/
export function flush(maxTurns?: number): number {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.flush(maxTurns);
} else {
return flushFallback(maxTurns);
}
}
/**
* Discard all remaining periodic tasks.
*
* @experimental
*/
export function discardPeriodicTasks(): void {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.discardPeriodicTasks();
} else {
discardPeriodicTasksFallback();
}
}
/**
* Flush any pending microtasks.
*
* @experimental
*/
export function flushMicrotasks(): void {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.flushMicrotasks();
} else {
return flushMicrotasksFallback();
}
}