feat(test): Implement fakeAsync using the FakeAsyncTestZoneSpec from zone.js.
Update the version of zone.js to @0.6.12 that contains the new FakeAsyncTestZoneSpec.
The new fakeAsync zone handles errors better and clearPendingTimers() is no longer required to be called after handling an error and is deprecated.
The fakeAsync test zone will now throw an error if an XHR is attemtped within the test since that cannot be controlled synchronously in the test(Need to be mocked out with a service implementation that doesn't involve XHRs).
This commit also allows fakeAsync to wrap inject to make it consistent with async test zone.
BREAKING CHANGE:
inject can no longer wrap fakeAsync while fakeAsync can wrap inject. So the order in existing tests with inject and fakeAsync has to be switched as follows:
Before:
```
inject([...], fakeAsync((...) => {...}))
```
After:
```
fakeAsync(inject([...], (...) => {...}))
```
Closes #8142
This commit is contained in:
committed by
vikerman
parent
cc86fee1d1
commit
bab81a9831
@@ -4,6 +4,8 @@ import 'dart:async' show runZoned, ZoneSpecification;
|
||||
import 'package:quiver/testing/async.dart' as quiver;
|
||||
import 'package:angular2/src/facade/exceptions.dart' show BaseException;
|
||||
|
||||
import 'test_injector.dart' show getTestInjector, FunctionWithParamTokens;
|
||||
|
||||
const _u = const Object();
|
||||
|
||||
quiver.FakeAsync _fakeAsync = null;
|
||||
@@ -16,24 +18,38 @@ quiver.FakeAsync _fakeAsync = null;
|
||||
* If there are any pending timers at the end of the function, an exception
|
||||
* will be thrown.
|
||||
*
|
||||
* Can be used to wrap inject() calls.
|
||||
*
|
||||
* Returns a `Function` that wraps [fn].
|
||||
*/
|
||||
Function fakeAsync(Function fn) {
|
||||
Function fakeAsync(dynamic /* Function | FunctionWithParamTokens */ fn) {
|
||||
if (_fakeAsync != null) {
|
||||
throw 'fakeAsync() calls can not be nested';
|
||||
}
|
||||
|
||||
return (
|
||||
[a0 = _u,
|
||||
a1 = _u,
|
||||
a2 = _u,
|
||||
a3 = _u,
|
||||
a4 = _u,
|
||||
a5 = _u,
|
||||
a6 = _u,
|
||||
a7 = _u,
|
||||
a8 = _u,
|
||||
a9 = _u]) {
|
||||
Function innerFn = null;
|
||||
if (fn is FunctionWithParamTokens) {
|
||||
if (fn.isAsync) {
|
||||
throw 'Cannot wrap async test with fakeAsync';
|
||||
}
|
||||
innerFn = () { getTestInjector().execute(fn); };
|
||||
} else if (fn is Function) {
|
||||
innerFn = fn;
|
||||
} else {
|
||||
throw 'fakeAsync can wrap only test functions but got object of type ' +
|
||||
fn.runtimeType.toString();
|
||||
}
|
||||
|
||||
return ([a0 = _u,
|
||||
a1 = _u,
|
||||
a2 = _u,
|
||||
a3 = _u,
|
||||
a4 = _u,
|
||||
a5 = _u,
|
||||
a6 = _u,
|
||||
a7 = _u,
|
||||
a8 = _u,
|
||||
a9 = _u]) {
|
||||
// runZoned() to install a custom exception handler that re-throws
|
||||
return runZoned(() {
|
||||
return new quiver.FakeAsync().run((quiver.FakeAsync async) {
|
||||
@@ -42,7 +58,7 @@ Function fakeAsync(Function fn) {
|
||||
List args = [a0, a1, a2, a3, a4, a5, a6, a7, a8, a9]
|
||||
.takeWhile((a) => a != _u)
|
||||
.toList();
|
||||
var res = Function.apply(fn, args);
|
||||
var res = Function.apply(innerFn, args);
|
||||
_fakeAsync.flushMicrotasks();
|
||||
|
||||
if (async.periodicTimerCount > 0) {
|
||||
|
||||
@@ -1,59 +1,7 @@
|
||||
import {global} from 'angular2/src/facade/lang';
|
||||
import {BaseException} from 'angular2/src/facade/exceptions';
|
||||
import {ListWrapper} from 'angular2/src/facade/collection';
|
||||
import {getTestInjector, FunctionWithParamTokens} from './test_injector';
|
||||
|
||||
var _scheduler;
|
||||
var _microtasks: Function[] = [];
|
||||
var _pendingPeriodicTimers: number[] = [];
|
||||
var _pendingTimers: number[] = [];
|
||||
|
||||
class FakeAsyncZoneSpec implements ZoneSpec {
|
||||
static assertInZone(): void {
|
||||
if (!Zone.current.get('inFakeAsyncZone')) {
|
||||
throw new Error('The code should be running in the fakeAsync zone to call this function');
|
||||
}
|
||||
}
|
||||
|
||||
name: string = 'fakeAsync';
|
||||
|
||||
properties: {[key: string]: any} = {'inFakeAsyncZone': true};
|
||||
|
||||
onScheduleTask(delegate: ZoneDelegate, current: Zone, target: Zone, task: Task): Task {
|
||||
switch (task.type) {
|
||||
case 'microTask':
|
||||
_microtasks.push(task.invoke);
|
||||
break;
|
||||
case 'macroTask':
|
||||
switch (task.source) {
|
||||
case 'setTimeout':
|
||||
task.data['handleId'] = _setTimeout(task.invoke, task.data['delay'], task.data['args']);
|
||||
break;
|
||||
case 'setInterval':
|
||||
task.data['handleId'] =
|
||||
_setInterval(task.invoke, task.data['delay'], task.data['args']);
|
||||
break;
|
||||
default:
|
||||
task = delegate.scheduleTask(target, task);
|
||||
}
|
||||
break;
|
||||
case 'eventTask':
|
||||
task = delegate.scheduleTask(target, task);
|
||||
break;
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
onCancelTask(delegate: ZoneDelegate, current: Zone, target: Zone, task: Task): any {
|
||||
switch (task.source) {
|
||||
case 'setTimeout':
|
||||
return _clearTimeout(task.data['handleId']);
|
||||
case 'setInterval':
|
||||
return _clearInterval(task.data['handleId']);
|
||||
default:
|
||||
return delegate.scheduleTask(target, task);
|
||||
}
|
||||
}
|
||||
}
|
||||
let _FakeAsyncTestZoneSpecType = Zone['FakeAsyncTestZoneSpec'];
|
||||
|
||||
/**
|
||||
* Wraps a function to be executed in the fakeAsync zone:
|
||||
@@ -62,6 +10,8 @@ class FakeAsyncZoneSpec implements ZoneSpec {
|
||||
*
|
||||
* 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 testing/ts/fake_async.ts region='basic'}
|
||||
@@ -69,57 +19,63 @@ class FakeAsyncZoneSpec implements ZoneSpec {
|
||||
* @param fn
|
||||
* @returns {Function} The function wrapped to be executed in the fakeAsync zone
|
||||
*/
|
||||
export function fakeAsync(fn: Function): Function {
|
||||
if (Zone.current.get('inFakeAsyncZone')) {
|
||||
throw new Error('fakeAsync() calls can not be nested');
|
||||
export function fakeAsync(fn: Function | FunctionWithParamTokens): Function {
|
||||
if (Zone.current.get('FakeAsyncTestZoneSpec') != null) {
|
||||
throw new BaseException('fakeAsync() calls can not be nested');
|
||||
}
|
||||
|
||||
var fakeAsyncZone = Zone.current.fork(new FakeAsyncZoneSpec());
|
||||
let fakeAsyncTestZoneSpec = new _FakeAsyncTestZoneSpecType();
|
||||
let fakeAsyncZone = Zone.current.fork(fakeAsyncTestZoneSpec);
|
||||
|
||||
let innerTestFn: Function = null;
|
||||
|
||||
if (fn instanceof FunctionWithParamTokens) {
|
||||
if (fn.isAsync) {
|
||||
throw new BaseException('Cannot wrap async test with fakeAsync');
|
||||
}
|
||||
innerTestFn = () => { getTestInjector().execute(fn as FunctionWithParamTokens); };
|
||||
} else {
|
||||
innerTestFn = fn;
|
||||
}
|
||||
|
||||
return function(...args) {
|
||||
// TODO(tbosch): This class should already be part of the jasmine typings but it is not...
|
||||
_scheduler = new (<any>jasmine).DelayedFunctionScheduler();
|
||||
clearPendingTimers();
|
||||
|
||||
let res = fakeAsyncZone.run(() => {
|
||||
let res = fn(...args);
|
||||
let res = innerTestFn(...args);
|
||||
flushMicrotasks();
|
||||
return res;
|
||||
});
|
||||
|
||||
if (_pendingPeriodicTimers.length > 0) {
|
||||
if (fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) {
|
||||
throw new BaseException(`${fakeAsyncTestZoneSpec.pendingPeriodicTimers.length} ` +
|
||||
`periodic timer(s) still in the queue.`);
|
||||
}
|
||||
|
||||
if (fakeAsyncTestZoneSpec.pendingTimers.length > 0) {
|
||||
throw new BaseException(
|
||||
`${_pendingPeriodicTimers.length} periodic timer(s) still in the queue.`);
|
||||
`${fakeAsyncTestZoneSpec.pendingTimers.length} timer(s) still in the queue.`);
|
||||
}
|
||||
|
||||
if (_pendingTimers.length > 0) {
|
||||
throw new BaseException(`${_pendingTimers.length} timer(s) still in the queue.`);
|
||||
}
|
||||
|
||||
_scheduler = null;
|
||||
ListWrapper.clear(_microtasks);
|
||||
|
||||
return res;
|
||||
};
|
||||
}
|
||||
|
||||
function _getFakeAsyncZoneSpec(): any {
|
||||
let zoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
|
||||
if (zoneSpec == null) {
|
||||
throw new Error('The code should be running in the fakeAsync zone to call this function');
|
||||
}
|
||||
return zoneSpec;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the queue of pending timers and microtasks.
|
||||
* Tests no longer need to call this explicitly.
|
||||
*
|
||||
* Useful for cleaning up after an asynchronous test passes.
|
||||
*
|
||||
* ## Example
|
||||
*
|
||||
* {@example testing/ts/fake_async.ts region='pending'}
|
||||
* @deprecated
|
||||
*/
|
||||
export function clearPendingTimers(): void {
|
||||
// TODO we should fix tick to dequeue the failed timer instead of relying on clearPendingTimers
|
||||
ListWrapper.clear(_microtasks);
|
||||
ListWrapper.clear(_pendingPeriodicTimers);
|
||||
ListWrapper.clear(_pendingTimers);
|
||||
// Do nothing.
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
|
||||
*
|
||||
@@ -133,54 +89,12 @@ export function clearPendingTimers(): void {
|
||||
* @param {number} millis Number of millisecond, defaults to 0
|
||||
*/
|
||||
export function tick(millis: number = 0): void {
|
||||
FakeAsyncZoneSpec.assertInZone();
|
||||
flushMicrotasks();
|
||||
_scheduler.tick(millis);
|
||||
_getFakeAsyncZoneSpec().tick(millis);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush any pending microtasks.
|
||||
*/
|
||||
export function flushMicrotasks(): void {
|
||||
FakeAsyncZoneSpec.assertInZone();
|
||||
while (_microtasks.length > 0) {
|
||||
var microtask = ListWrapper.removeAt(_microtasks, 0);
|
||||
microtask();
|
||||
}
|
||||
}
|
||||
|
||||
function _setTimeout(fn: Function, delay: number, args: any[]): number {
|
||||
var cb = _fnAndFlush(fn);
|
||||
var id = _scheduler.scheduleFunction(cb, delay, args);
|
||||
_pendingTimers.push(id);
|
||||
_scheduler.scheduleFunction(_dequeueTimer(id), delay);
|
||||
return id;
|
||||
}
|
||||
|
||||
function _clearTimeout(id: number) {
|
||||
_dequeueTimer(id);
|
||||
return _scheduler.removeFunctionWithId(id);
|
||||
}
|
||||
|
||||
function _setInterval(fn: Function, interval: number, ...args) {
|
||||
var cb = _fnAndFlush(fn);
|
||||
var id = _scheduler.scheduleFunction(cb, interval, args, true);
|
||||
_pendingPeriodicTimers.push(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
function _clearInterval(id: number) {
|
||||
ListWrapper.remove(_pendingPeriodicTimers, id);
|
||||
return _scheduler.removeFunctionWithId(id);
|
||||
}
|
||||
|
||||
function _fnAndFlush(fn: Function): Function {
|
||||
return (...args) => {
|
||||
fn.apply(global, args);
|
||||
flushMicrotasks();
|
||||
}
|
||||
}
|
||||
|
||||
function _dequeueTimer(id: number): Function {
|
||||
return function() { ListWrapper.remove(_pendingTimers, id); }
|
||||
_getFakeAsyncZoneSpec().flushMicrotasks();
|
||||
}
|
||||
|
||||
@@ -195,7 +195,7 @@ function emptyArray(): Array<any> {
|
||||
}
|
||||
|
||||
export class FunctionWithParamTokens {
|
||||
constructor(private _tokens: any[], private _fn: Function, public isAsync: boolean,
|
||||
constructor(private _tokens: any[], public fn: Function, public isAsync: boolean,
|
||||
public additionalProviders: () => any = emptyArray) {}
|
||||
|
||||
/**
|
||||
@@ -203,7 +203,7 @@ export class FunctionWithParamTokens {
|
||||
*/
|
||||
execute(injector: ReflectiveInjector): any {
|
||||
var params = this._tokens.map(t => injector.get(t));
|
||||
return FunctionWrapper.apply(this._fn, params);
|
||||
return FunctionWrapper.apply(this.fn, params);
|
||||
}
|
||||
|
||||
hasToken(token: any): boolean { return this._tokens.indexOf(token) > -1; }
|
||||
|
||||
@@ -87,7 +87,7 @@ export type AsyncTestFn = (done: () => void) => void;
|
||||
/**
|
||||
* Signature for any simple testing function.
|
||||
*/
|
||||
export type AnyTestFn = SyncTestFn | AsyncTestFn;
|
||||
export type AnyTestFn = SyncTestFn | AsyncTestFn | Function;
|
||||
|
||||
var jsmBeforeEach = _global.beforeEach;
|
||||
var jsmIt = _global.it;
|
||||
|
||||
Reference in New Issue
Block a user