chore(facade): remove most facade/async functions

This commit is contained in:
Jason Choi 2016-08-02 15:53:34 -07:00 committed by Alex Rickabaugh
parent 6baf3baedd
commit 99989f5d3f
184 changed files with 1609 additions and 1698 deletions

View File

@ -8,7 +8,7 @@
import {Directive, Host, Inject, OnChanges, OnDestroy, Optional, Self, SimpleChanges, SkipSelf, forwardRef} from '@angular/core'; import {Directive, Host, Inject, OnChanges, OnDestroy, Optional, Self, SimpleChanges, SkipSelf, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper} from '../../facade/async'; import {EventEmitter} from '../../facade/async';
import {Control} from '../model'; import {Control} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
@ -122,7 +122,7 @@ export class NgControlName extends NgControl implements OnChanges,
viewToModelUpdate(newValue: any): void { viewToModelUpdate(newValue: any): void {
this.viewModel = newValue; this.viewModel = newValue;
ObservableWrapper.callEmit(this.update, newValue); this.update.emit(newValue);
} }
get path(): string[] { return controlPath(this.name, this._parent); } get path(): string[] { return controlPath(this.name, this._parent); }

View File

@ -8,7 +8,7 @@
import {Directive, Inject, Optional, Self, forwardRef} from '@angular/core'; import {Directive, Inject, Optional, Self, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper, PromiseWrapper} from '../../facade/async'; import {EventEmitter} from '../../facade/async';
import {ListWrapper} from '../../facade/collection'; import {ListWrapper} from '../../facade/collection';
import {isPresent} from '../../facade/lang'; import {isPresent} from '../../facade/lang';
import {AbstractControl, Control, ControlGroup} from '../model'; import {AbstractControl, Control, ControlGroup} from '../model';
@ -27,6 +27,8 @@ export const formDirectiveProvider: any = {
let _formWarningDisplayed: boolean = false; let _formWarningDisplayed: boolean = false;
const resolvedPromise = Promise.resolve(null);
/** /**
* If `NgForm` is bound in a component, `<form>` elements in that component will be * If `NgForm` is bound in a component, `<form>` elements in that component will be
* upgraded to use the Angular form system. * upgraded to use the Angular form system.
@ -136,7 +138,7 @@ export class NgForm extends ControlContainer implements Form {
get controls(): {[key: string]: AbstractControl} { return this.form.controls; } get controls(): {[key: string]: AbstractControl} { return this.form.controls; }
addControl(dir: NgControl): void { addControl(dir: NgControl): void {
PromiseWrapper.scheduleMicrotask(() => { resolvedPromise.then(() => {
var container = this._findContainer(dir.path); var container = this._findContainer(dir.path);
var ctrl = new Control(); var ctrl = new Control();
setUpControl(ctrl, dir); setUpControl(ctrl, dir);
@ -148,7 +150,7 @@ export class NgForm extends ControlContainer implements Form {
getControl(dir: NgControl): Control { return <Control>this.form.find(dir.path); } getControl(dir: NgControl): Control { return <Control>this.form.find(dir.path); }
removeControl(dir: NgControl): void { removeControl(dir: NgControl): void {
PromiseWrapper.scheduleMicrotask(() => { resolvedPromise.then(() => {
var container = this._findContainer(dir.path); var container = this._findContainer(dir.path);
if (isPresent(container)) { if (isPresent(container)) {
container.removeControl(dir.name); container.removeControl(dir.name);
@ -157,7 +159,7 @@ export class NgForm extends ControlContainer implements Form {
} }
addControlGroup(dir: NgControlGroup): void { addControlGroup(dir: NgControlGroup): void {
PromiseWrapper.scheduleMicrotask(() => { resolvedPromise.then(() => {
var container = this._findContainer(dir.path); var container = this._findContainer(dir.path);
var group = new ControlGroup({}); var group = new ControlGroup({});
setUpControlGroup(group, dir); setUpControlGroup(group, dir);
@ -167,7 +169,7 @@ export class NgForm extends ControlContainer implements Form {
} }
removeControlGroup(dir: NgControlGroup): void { removeControlGroup(dir: NgControlGroup): void {
PromiseWrapper.scheduleMicrotask(() => { resolvedPromise.then(() => {
var container = this._findContainer(dir.path); var container = this._findContainer(dir.path);
if (isPresent(container)) { if (isPresent(container)) {
container.removeControl(dir.name); container.removeControl(dir.name);
@ -180,7 +182,7 @@ export class NgForm extends ControlContainer implements Form {
} }
updateModel(dir: NgControl, value: any): void { updateModel(dir: NgControl, value: any): void {
PromiseWrapper.scheduleMicrotask(() => { resolvedPromise.then(() => {
var ctrl = <Control>this.form.find(dir.path); var ctrl = <Control>this.form.find(dir.path);
ctrl.updateValue(value); ctrl.updateValue(value);
}); });
@ -188,7 +190,7 @@ export class NgForm extends ControlContainer implements Form {
onSubmit(): boolean { onSubmit(): boolean {
this._submitted = true; this._submitted = true;
ObservableWrapper.callEmit(this.ngSubmit, null); this.ngSubmit.emit(null);
return false; return false;
} }

View File

@ -8,7 +8,7 @@
import {Directive, Inject, OnChanges, Optional, Self, SimpleChanges, forwardRef} from '@angular/core'; import {Directive, Inject, OnChanges, Optional, Self, SimpleChanges, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper} from '../../facade/async'; import {EventEmitter} from '../../facade/async';
import {StringMapWrapper} from '../../facade/collection'; import {StringMapWrapper} from '../../facade/collection';
import {Control} from '../model'; import {Control} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
@ -118,7 +118,7 @@ export class NgFormControl extends NgControl implements OnChanges {
viewToModelUpdate(newValue: any): void { viewToModelUpdate(newValue: any): void {
this.viewModel = newValue; this.viewModel = newValue;
ObservableWrapper.callEmit(this.update, newValue); this.update.emit(newValue);
} }
private _isControlChanged(changes: {[key: string]: any}): boolean { private _isControlChanged(changes: {[key: string]: any}): boolean {

View File

@ -8,7 +8,7 @@
import {Directive, Inject, OnChanges, Optional, Self, SimpleChanges, forwardRef} from '@angular/core'; import {Directive, Inject, OnChanges, Optional, Self, SimpleChanges, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper} from '../../facade/async'; import {EventEmitter} from '../../facade/async';
import {ListWrapper, StringMapWrapper} from '../../facade/collection'; import {ListWrapper, StringMapWrapper} from '../../facade/collection';
import {BaseException} from '../../facade/exceptions'; import {BaseException} from '../../facade/exceptions';
import {isBlank} from '../../facade/lang'; import {isBlank} from '../../facade/lang';
@ -191,7 +191,7 @@ export class NgFormModel extends ControlContainer implements Form,
onSubmit(): boolean { onSubmit(): boolean {
this._submitted = true; this._submitted = true;
ObservableWrapper.callEmit(this.ngSubmit, null); this.ngSubmit.emit(null);
return false; return false;
} }

View File

@ -8,7 +8,7 @@
import {Directive, Inject, OnChanges, Optional, Self, SimpleChanges, forwardRef} from '@angular/core'; import {Directive, Inject, OnChanges, Optional, Self, SimpleChanges, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper} from '../../facade/async'; import {EventEmitter} from '../../facade/async';
import {Control} from '../model'; import {Control} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
@ -94,6 +94,6 @@ export class NgModel extends NgControl implements OnChanges {
viewToModelUpdate(newValue: any): void { viewToModelUpdate(newValue: any): void {
this.viewModel = newValue; this.viewModel = newValue;
ObservableWrapper.callEmit(this.update, newValue); this.update.emit(newValue);
} }
} }

View File

@ -6,11 +6,15 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {EventEmitter, Observable, ObservableWrapper} from '../facade/async'; import {PromiseObservable} from 'rxjs/observable/PromiseObservable';
import {EventEmitter, Observable} from '../facade/async';
import {ListWrapper, StringMapWrapper} from '../facade/collection'; import {ListWrapper, StringMapWrapper} from '../facade/collection';
import {isBlank, isPresent, isPromise, normalizeBool} from '../facade/lang'; import {isBlank, isPresent, isPromise, normalizeBool} from '../facade/lang';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators'; import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
/** /**
* Indicates that a Control is valid, i.e. that no errors exist in the input value. * Indicates that a Control is valid, i.e. that no errors exist in the input value.
*/ */
@ -52,7 +56,7 @@ function _find(control: AbstractControl, path: Array<string|number>| string) {
} }
function toObservable(r: any): Observable<any> { function toObservable(r: any): Observable<any> {
return isPromise(r) ? ObservableWrapper.fromPromise(r) : r; return isPromise(r) ? PromiseObservable.create(r) : r;
} }
/** /**
@ -135,8 +139,8 @@ export abstract class AbstractControl {
} }
if (emitEvent) { if (emitEvent) {
ObservableWrapper.callEmit(this._valueChanges, this._value); this._valueChanges.emit(this._value);
ObservableWrapper.callEmit(this._statusChanges, this._status); this._statusChanges.emit(this._status);
} }
if (isPresent(this._parent) && !onlySelf) { if (isPresent(this._parent) && !onlySelf) {
@ -153,14 +157,14 @@ export abstract class AbstractControl {
this._status = PENDING; this._status = PENDING;
this._cancelExistingSubscription(); this._cancelExistingSubscription();
var obs = toObservable(this.asyncValidator(this)); var obs = toObservable(this.asyncValidator(this));
this._asyncValidationSubscription = ObservableWrapper.subscribe( this._asyncValidationSubscription = obs.subscribe(
obs, (res: {[key: string]: any}) => this.setErrors(res, {emitEvent: emitEvent})); {next: (res: {[key: string]: any}) => this.setErrors(res, {emitEvent: emitEvent})});
} }
} }
private _cancelExistingSubscription(): void { private _cancelExistingSubscription(): void {
if (isPresent(this._asyncValidationSubscription)) { if (isPresent(this._asyncValidationSubscription)) {
ObservableWrapper.dispose(this._asyncValidationSubscription); this._asyncValidationSubscription.unsubscribe();
} }
} }
@ -194,7 +198,7 @@ export abstract class AbstractControl {
this._status = this._calculateStatus(); this._status = this._calculateStatus();
if (emitEvent) { if (emitEvent) {
ObservableWrapper.callEmit(this._statusChanges, this._status); this._statusChanges.emit(this._status);
} }
if (isPresent(this._parent)) { if (isPresent(this._parent)) {

View File

@ -7,13 +7,15 @@
*/ */
import {OpaqueToken} from '@angular/core'; import {OpaqueToken} from '@angular/core';
import {ObservableWrapper} from '../facade/async'; import {toPromise} from 'rxjs/operator/toPromise';
import {StringMapWrapper} from '../facade/collection'; import {StringMapWrapper} from '../facade/collection';
import {isBlank, isPresent, isPromise, isString} from '../facade/lang'; import {isBlank, isPresent, isPromise, isString} from '../facade/lang';
import {PromiseWrapper} from '../facade/promise';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators'; import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
import {AbstractControl} from './model'; import {AbstractControl} from './model';
/** /**
* Providers for validators to be used for {@link Control}s in a form. * Providers for validators to be used for {@link Control}s in a form.
* *
@ -127,13 +129,13 @@ export class Validators {
return function(control: AbstractControl) { return function(control: AbstractControl) {
let promises = _executeAsyncValidators(control, presentValidators).map(_convertToPromise); let promises = _executeAsyncValidators(control, presentValidators).map(_convertToPromise);
return PromiseWrapper.all(promises).then(_mergeErrors); return Promise.all(promises).then(_mergeErrors);
}; };
} }
} }
function _convertToPromise(obj: any): Promise<any> { function _convertToPromise(obj: any): Promise<any> {
return isPromise(obj) ? obj : ObservableWrapper.toPromise(obj); return isPromise(obj) ? obj : toPromise.call(obj);
} }
function _executeValidators(control: AbstractControl, validators: ValidatorFn[]): any[] { function _executeValidators(control: AbstractControl, validators: ValidatorFn[]): any[] {

View File

@ -8,8 +8,6 @@
import {EventEmitter, Injectable} from '@angular/core'; import {EventEmitter, Injectable} from '@angular/core';
import {ObservableWrapper} from '../facade/async';
import {LocationStrategy} from './location_strategy'; import {LocationStrategy} from './location_strategy';
@ -69,10 +67,8 @@ export class Location {
this._platformStrategy = platformStrategy; this._platformStrategy = platformStrategy;
var browserBaseHref = this._platformStrategy.getBaseHref(); var browserBaseHref = this._platformStrategy.getBaseHref();
this._baseHref = Location.stripTrailingSlash(_stripIndexHtml(browserBaseHref)); this._baseHref = Location.stripTrailingSlash(_stripIndexHtml(browserBaseHref));
this._platformStrategy.onPopState((ev) => { this._platformStrategy.onPopState(
ObservableWrapper.callEmit( (ev) => { this._subject.emit({'url': this.path(true), 'pop': true, 'type': ev.type}); });
this._subject, {'url': this.path(true), 'pop': true, 'type': ev.type});
});
} }
/** /**
@ -145,7 +141,7 @@ export class Location {
subscribe( subscribe(
onNext: (value: any) => void, onThrow: (exception: any) => void = null, onNext: (value: any) => void, onThrow: (exception: any) => void = null,
onReturn: () => void = null): Object { onReturn: () => void = null): Object {
return ObservableWrapper.subscribe(this._subject, onNext, onThrow, onReturn); return this._subject.subscribe({next: onNext, error: onThrow, complete: onReturn});
} }
/** /**

View File

@ -7,7 +7,7 @@
*/ */
import {ChangeDetectorRef, OnDestroy, Pipe, WrappedValue} from '@angular/core'; import {ChangeDetectorRef, OnDestroy, Pipe, WrappedValue} from '@angular/core';
import {EventEmitter, Observable, ObservableWrapper} from '../facade/async'; import {EventEmitter, Observable} from '../facade/async';
import {isBlank, isPresent, isPromise} from '../facade/lang'; import {isBlank, isPresent, isPromise} from '../facade/lang';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';
@ -19,12 +19,12 @@ interface SubscriptionStrategy {
class ObservableStrategy implements SubscriptionStrategy { class ObservableStrategy implements SubscriptionStrategy {
createSubscription(async: any, updateLatestValue: any): any { createSubscription(async: any, updateLatestValue: any): any {
return ObservableWrapper.subscribe(async, updateLatestValue, e => { throw e; }); return async.subscribe({next: updateLatestValue, error: (e: any) => { throw e; }});
} }
dispose(subscription: any): void { ObservableWrapper.dispose(subscription); } dispose(subscription: any): void { subscription.unsubscribe(); }
onDestroy(subscription: any): void { ObservableWrapper.dispose(subscription); } onDestroy(subscription: any): void { subscription.unsubscribe(); }
} }
class PromiseStrategy implements SubscriptionStrategy { class PromiseStrategy implements SubscriptionStrategy {
@ -125,7 +125,7 @@ export class AsyncPipe implements OnDestroy {
_selectStrategy(obj: Observable<any>|Promise<any>|EventEmitter<any>): any { _selectStrategy(obj: Observable<any>|Promise<any>|EventEmitter<any>): any {
if (isPromise(obj)) { if (isPromise(obj)) {
return _promiseStrategy; return _promiseStrategy;
} else if (ObservableWrapper.isObservable(obj)) { } else if ((<any>obj).subscribe) {
return _observableStrategy; return _observableStrategy;
} else { } else {
throw new InvalidPipeArgumentException(AsyncPipe, obj); throw new InvalidPipeArgumentException(AsyncPipe, obj);

View File

@ -6,13 +6,14 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {TestComponentBuilder} from '@angular/core/testing';
import {ListWrapper} from '../../src/facade/collection';
import {Component, TemplateRef, ContentChild} from '@angular/core';
import {NgFor, NgIf} from '@angular/common'; import {NgFor, NgIf} from '@angular/common';
import {expect} from '@angular/platform-browser/testing/matchers'; import {Component, ContentChild, TemplateRef} from '@angular/core';
import {TestComponentBuilder} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {By} from '@angular/platform-browser/src/dom/debug/by'; import {By} from '@angular/platform-browser/src/dom/debug/by';
import {expect} from '@angular/platform-browser/testing/matchers';
import {ListWrapper} from '../../src/facade/collection';
let thisArg: any; let thisArg: any;

View File

@ -6,13 +6,12 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEach, ddescribe, describe, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {TestComponentBuilder} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/matchers';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {Component} from '@angular/core';
import {NgIf} from '@angular/common'; import {NgIf} from '@angular/common';
import {Component} from '@angular/core';
import {TestComponentBuilder} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {expect} from '@angular/platform-browser/testing/matchers';
export function main() { export function main() {
describe('ngIf directive', () => { describe('ngIf directive', () => {

View File

@ -6,12 +6,11 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEachProviders, beforeEach, ddescribe, describe, iit, inject, it, xit,} from '@angular/core/testing/testing_internal'; import {NgLocalization, NgPlural, NgPluralCase} from '@angular/common';
import {expect} from '@angular/platform-browser/testing/matchers';
import {TestComponentBuilder} from '@angular/core/testing';
import {Component, Injectable} from '@angular/core'; import {Component, Injectable} from '@angular/core';
import {NgPlural, NgPluralCase, NgLocalization} from '@angular/common'; import {TestComponentBuilder} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing/matchers';
export function main() { export function main() {
describe('switch', () => { describe('switch', () => {

View File

@ -6,12 +6,11 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEach, ddescribe, describe, iit, inject, it, xit,} from '@angular/core/testing/testing_internal'; import {NgSwitch, NgSwitchCase, NgSwitchDefault} from '@angular/common';
import {expect} from '@angular/platform-browser/testing/matchers';
import {Component} from '@angular/core'; import {Component} from '@angular/core';
import {TestComponentBuilder} from '@angular/core/testing'; import {TestComponentBuilder} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {NgSwitch, NgSwitchCase, NgSwitchDefault} from '@angular/common'; import {expect} from '@angular/platform-browser/testing/matchers';
export function main() { export function main() {
describe('switch', () => { describe('switch', () => {

View File

@ -6,11 +6,11 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEach, ddescribe, describe, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing/matchers';
import {TestComponentBuilder} from '@angular/core/testing';
import {Component, Directive, TemplateRef, ContentChildren, QueryList} from '@angular/core';
import {NgTemplateOutlet} from '@angular/common'; import {NgTemplateOutlet} from '@angular/common';
import {Component, ContentChildren, Directive, QueryList, TemplateRef} from '@angular/core';
import {TestComponentBuilder} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing/matchers';
export function main() { export function main() {
describe('insert', () => { describe('insert', () => {

View File

@ -6,12 +6,12 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEach, ddescribe, describe, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing/matchers';
import {TestComponentBuilder} from '@angular/core/testing';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {Component, Directive} from '@angular/core'; import {Component, Directive} from '@angular/core';
import {ElementRef} from '@angular/core/src/linker/element_ref'; import {ElementRef} from '@angular/core/src/linker/element_ref';
import {TestComponentBuilder} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {expect} from '@angular/platform-browser/testing/matchers';
export function main() { export function main() {
describe('non-bindable', () => { describe('non-bindable', () => {

View File

@ -6,20 +6,14 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {CheckboxControlValueAccessor, Control, ControlGroup, ControlValueAccessor, DefaultValueAccessor, NgControl, NgControlGroup, NgControlName, NgForm, NgFormControl, NgFormModel, NgModel, SelectControlValueAccessor, Validator, Validators} from '@angular/common/src/forms-deprecated';
import {composeValidators, selectValueAccessor} from '@angular/common/src/forms-deprecated/directives/shared';
import {SimpleChange} from '@angular/core/src/change_detection';
import {fakeAsync, flushMicrotasks, tick} from '@angular/core/testing';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {fakeAsync, flushMicrotasks, tick,} from '@angular/core/testing';
import {SpyNgControl, SpyValueAccessor} from '../spies'; import {SpyNgControl, SpyValueAccessor} from '../spies';
import {ControlGroup, Control, NgControlName, NgControlGroup, NgFormModel, ControlValueAccessor, Validators, NgForm, NgModel, NgFormControl, NgControl, DefaultValueAccessor, CheckboxControlValueAccessor, SelectControlValueAccessor, Validator} from '@angular/common/src/forms-deprecated';
import {selectValueAccessor, composeValidators} from '@angular/common/src/forms-deprecated/directives/shared';
import {TimerWrapper} from '../../src/facade/async';
import {PromiseWrapper} from '../../src/facade/promise';
import {SimpleChange} from '@angular/core/src/change_detection';
class DummyControlValueAccessor implements ControlValueAccessor { class DummyControlValueAccessor implements ControlValueAccessor {
writtenValue: any /** TODO #9100 */; writtenValue: any /** TODO #9100 */;
@ -35,14 +29,14 @@ class CustomValidatorDirective implements Validator {
function asyncValidator(expected: any /** TODO #9100 */, timeout = 0) { function asyncValidator(expected: any /** TODO #9100 */, timeout = 0) {
return (c: any /** TODO #9100 */) => { return (c: any /** TODO #9100 */) => {
var completer = PromiseWrapper.completer(); return new Promise((resolve) => {
var res = c.value != expected ? {'async': true} : null; var res = c.value != expected ? {'async': true} : null;
if (timeout == 0) { if (timeout == 0) {
completer.resolve(res); resolve(res);
} else { } else {
TimerWrapper.setTimeout(() => { completer.resolve(res); }, timeout); setTimeout(() => { resolve(res); }, timeout);
} }
return completer.promise; });
}; };
} }

View File

@ -9,11 +9,9 @@
import {Control, FormBuilder} from '@angular/common/src/forms-deprecated'; import {Control, FormBuilder} from '@angular/common/src/forms-deprecated';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal'; import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {PromiseWrapper} from '../../src/facade/promise';
export function main() { export function main() {
function syncValidator(_: any): any { return null; } function syncValidator(_: any): any { return null; }
function asyncValidator(_: any) { return PromiseWrapper.resolve(null); } function asyncValidator(_: any) { return Promise.resolve(null); }
describe('Form Builder', () => { describe('Form Builder', () => {
var b: any /** TODO #9100 */; var b: any /** TODO #9100 */;

View File

@ -15,9 +15,7 @@ import {By} from '@angular/platform-browser/src/dom/debug/by';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {dispatchEvent} from '@angular/platform-browser/testing/browser_util'; import {dispatchEvent} from '@angular/platform-browser/testing/browser_util';
import {ObservableWrapper, TimerWrapper} from '../../src/facade/async';
import {ListWrapper} from '../../src/facade/collection'; import {ListWrapper} from '../../src/facade/collection';
import {PromiseWrapper} from '../../src/facade/promise';
export function main() { export function main() {
describe('integration tests', () => { describe('integration tests', () => {
@ -98,8 +96,8 @@ export function main() {
input.nativeElement.value = 'updatedValue'; input.nativeElement.value = 'updatedValue';
ObservableWrapper.subscribe(
form.valueChanges, (value) => { throw 'Should not happen'; }); form.valueChanges.subscribe({next: (value: any) => { throw 'Should not happen'; }});
dispatchEvent(input.nativeElement, 'change'); dispatchEvent(input.nativeElement, 'change');
async.done(); async.done();
@ -606,7 +604,7 @@ export function main() {
select.nativeElement.value = '2: Object'; select.nativeElement.value = '2: Object';
dispatchEvent(select.nativeElement, 'change'); dispatchEvent(select.nativeElement, 'change');
fixture.detectChanges(); fixture.detectChanges();
TimerWrapper.setTimeout(() => { setTimeout(() => {
expect(testComp.selectedCity['name']).toEqual('Buffalo'); expect(testComp.selectedCity['name']).toEqual('Buffalo');
async.done(); async.done();
}, 0); }, 0);
@ -831,11 +829,13 @@ export function main() {
expect(input.componentInstance.value).toEqual('!aa!'); expect(input.componentInstance.value).toEqual('!aa!');
input.componentInstance.value = '!bb!'; input.componentInstance.value = '!bb!';
ObservableWrapper.subscribe(input.componentInstance.onInput, (value) => { input.componentInstance.onInput.subscribe({
expect(fixture.debugElement.componentInstance.form.value).toEqual({ next: (value: any) => {
'name': 'bb' expect(fixture.debugElement.componentInstance.form.value).toEqual({
}); 'name': 'bb'
async.done(); });
async.done();
}
}); });
input.componentInstance.dispatchChangeEvent(); input.componentInstance.dispatchChangeEvent();
}); });
@ -1491,21 +1491,16 @@ class MyInput implements ControlValueAccessor {
writeValue(value: any /** TODO #9100 */) { this.value = `!${value}!`; } writeValue(value: any /** TODO #9100 */) { this.value = `!${value}!`; }
registerOnChange(fn: any /** TODO #9100 */) { ObservableWrapper.subscribe(this.onInput, fn); } registerOnChange(fn: any /** TODO #9100 */) { this.onInput.subscribe({next: fn}); }
registerOnTouched(fn: any /** TODO #9100 */) {} registerOnTouched(fn: any /** TODO #9100 */) {}
dispatchChangeEvent() { dispatchChangeEvent() { this.onInput.emit(this.value.substring(1, this.value.length - 1)); }
ObservableWrapper.callEmit(this.onInput, this.value.substring(1, this.value.length - 1));
}
} }
function uniqLoginAsyncValidator(expectedValue: string) { function uniqLoginAsyncValidator(expectedValue: string) {
return (c: any /** TODO #9100 */) => { return (c: any /** TODO #9100 */) => {
var completer = PromiseWrapper.completer(); return Promise.resolve((c.value == expectedValue) ? null : {'uniqLogin': true});
var res = (c.value == expectedValue) ? null : {'uniqLogin': true};
completer.resolve(res);
return completer.promise;
}; };
} }

View File

@ -6,35 +6,34 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal'; import {Control, ControlArray, ControlGroup, Validators} from '@angular/common/src/forms-deprecated';
import {fakeAsync, flushMicrotasks, tick} from '@angular/core/testing'; import {fakeAsync, flushMicrotasks, tick} from '@angular/core/testing';
import {ControlGroup, Control, ControlArray, Validators} from '@angular/common/src/forms-deprecated'; import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {EventEmitter} from '../../src/facade/async';
import {isPresent} from '../../src/facade/lang'; import {isPresent} from '../../src/facade/lang';
import {PromiseWrapper} from '../../src/facade/promise';
import {TimerWrapper, ObservableWrapper, EventEmitter} from '../../src/facade/async';
export function main() { export function main() {
function asyncValidator(expected: any /** TODO #9100 */, timeouts = {}) { function asyncValidator(expected: any /** TODO #9100 */, timeouts = {}) {
return (c: any /** TODO #9100 */) => { return (c: any /** TODO #9100 */) => {
var completer = PromiseWrapper.completer(); return new Promise((resolve) => {
var t = isPresent((timeouts as any /** TODO #9100 */)[c.value]) ? var t = isPresent((timeouts as any /** TODO #9100 */)[c.value]) ?
(timeouts as any /** TODO #9100 */)[c.value] : (timeouts as any /** TODO #9100 */)[c.value] :
0; 0;
var res = c.value != expected ? {'async': true} : null; var res = c.value != expected ? {'async': true} : null;
if (t == 0) { if (t == 0) {
completer.resolve(res); resolve(res);
} else { } else {
TimerWrapper.setTimeout(() => { completer.resolve(res); }, t); setTimeout(() => { resolve(res); }, t);
} }
});
return completer.promise;
}; };
} }
function asyncValidatorReturningObservable(c: any /** TODO #9100 */) { function asyncValidatorReturningObservable(c: any /** TODO #9100 */) {
var e = new EventEmitter(); var e = new EventEmitter();
PromiseWrapper.scheduleMicrotask(() => ObservableWrapper.callEmit(e, {'async': true})); Promise.resolve(null).then(() => { e.emit({'async': true}); });
return e; return e;
} }
@ -179,15 +178,16 @@ export function main() {
}); });
it('should fire an event', fakeAsync(() => { it('should fire an event', fakeAsync(() => {
ObservableWrapper.subscribe(
c.valueChanges, (value) => { expect(value).toEqual('newValue'); }); c.valueChanges.subscribe(
{next: (value: any) => { expect(value).toEqual('newValue'); }});
c.updateValue('newValue'); c.updateValue('newValue');
tick(); tick();
})); }));
it('should not fire an event when explicitly specified', fakeAsync(() => { it('should not fire an event when explicitly specified', fakeAsync(() => {
ObservableWrapper.subscribe(c.valueChanges, (value) => { throw 'Should not happen'; }); c.valueChanges.subscribe({next: (value: any) => { throw 'Should not happen'; }});
c.updateValue('newValue', {emitEvent: false}); c.updateValue('newValue', {emitEvent: false});
@ -202,18 +202,22 @@ export function main() {
it('should fire an event after the value has been updated', it('should fire an event after the value has been updated',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ObservableWrapper.subscribe(c.valueChanges, (value) => { c.valueChanges.subscribe({
expect(c.value).toEqual('new'); next: (value: any) => {
expect(value).toEqual('new'); expect(c.value).toEqual('new');
async.done(); expect(value).toEqual('new');
async.done();
}
}); });
c.updateValue('new'); c.updateValue('new');
})); }));
it('should fire an event after the status has been updated to invalid', fakeAsync(() => { it('should fire an event after the status has been updated to invalid', fakeAsync(() => {
ObservableWrapper.subscribe(c.statusChanges, (status) => { c.statusChanges.subscribe({
expect(c.status).toEqual('INVALID'); next: (status: any) => {
expect(status).toEqual('INVALID'); expect(c.status).toEqual('INVALID');
expect(status).toEqual('INVALID');
}
}); });
c.updateValue(''); c.updateValue('');
@ -224,9 +228,9 @@ export function main() {
var c = new Control('old', Validators.required, asyncValidator('expected')); var c = new Control('old', Validators.required, asyncValidator('expected'));
var log: any[] /** TODO #9100 */ = []; var log: any[] /** TODO #9100 */ = [];
ObservableWrapper.subscribe(c.valueChanges, (value) => log.push(`value: '${value}'`)); c.valueChanges.subscribe({next: (value: any) => log.push(`value: '${value}'`)});
ObservableWrapper.subscribe(
c.statusChanges, (status) => log.push(`status: '${status}'`)); c.statusChanges.subscribe({next: (status: any) => log.push(`status: '${status}'`)});
c.updateValue(''); c.updateValue('');
tick(); tick();
@ -264,9 +268,11 @@ export function main() {
it('should return a cold observable', it('should return a cold observable',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
c.updateValue('will be ignored'); c.updateValue('will be ignored');
ObservableWrapper.subscribe(c.valueChanges, (value) => { c.valueChanges.subscribe({
expect(value).toEqual('new'); next: (value: any) => {
async.done(); expect(value).toEqual('new');
async.done();
}
}); });
c.updateValue('new'); c.updateValue('new');
})); }));
@ -480,10 +486,12 @@ export function main() {
it('should fire an event after the value has been updated', it('should fire an event after the value has been updated',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ObservableWrapper.subscribe(g.valueChanges, (value) => { g.valueChanges.subscribe({
expect(g.value).toEqual({'one': 'new1', 'two': 'old2'}); next: (value: any) => {
expect(value).toEqual({'one': 'new1', 'two': 'old2'}); expect(g.value).toEqual({'one': 'new1', 'two': 'old2'});
async.done(); expect(value).toEqual({'one': 'new1', 'two': 'old2'});
async.done();
}
}); });
c1.updateValue('new1'); c1.updateValue('new1');
})); }));
@ -492,12 +500,14 @@ export function main() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var controlCallbackIsCalled = false; var controlCallbackIsCalled = false;
ObservableWrapper.subscribe(
c1.valueChanges, (value) => { controlCallbackIsCalled = true; });
ObservableWrapper.subscribe(g.valueChanges, (value) => { c1.valueChanges.subscribe({next: (value: any) => { controlCallbackIsCalled = true; }});
expect(controlCallbackIsCalled).toBe(true);
async.done(); g.valueChanges.subscribe({
next: (value: any) => {
expect(controlCallbackIsCalled).toBe(true);
async.done();
}
}); });
c1.updateValue('new1'); c1.updateValue('new1');
@ -505,9 +515,11 @@ export function main() {
it('should fire an event when a control is excluded', it('should fire an event when a control is excluded',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ObservableWrapper.subscribe(g.valueChanges, (value) => { g.valueChanges.subscribe({
expect(value).toEqual({'one': 'old1'}); next: (value: any) => {
async.done(); expect(value).toEqual({'one': 'old1'});
async.done();
}
}); });
g.exclude('two'); g.exclude('two');
@ -517,9 +529,11 @@ export function main() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
g.exclude('two'); g.exclude('two');
ObservableWrapper.subscribe(g.valueChanges, (value) => { g.valueChanges.subscribe({
expect(value).toEqual({'one': 'old1', 'two': 'old2'}); next: (value: any) => {
async.done(); expect(value).toEqual({'one': 'old1', 'two': 'old2'});
async.done();
}
}); });
g.include('two'); g.include('two');
@ -529,14 +543,16 @@ export function main() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var loggedValues: any[] /** TODO #9100 */ = []; var loggedValues: any[] /** TODO #9100 */ = [];
ObservableWrapper.subscribe(g.valueChanges, (value) => { g.valueChanges.subscribe({
loggedValues.push(value); next: (value: any) => {
loggedValues.push(value);
if (loggedValues.length == 2) { if (loggedValues.length == 2) {
expect(loggedValues).toEqual([ expect(loggedValues).toEqual([
{'one': 'new1', 'two': 'old2'}, {'one': 'new1', 'two': 'new2'} {'one': 'new1', 'two': 'old2'}, {'one': 'new1', 'two': 'new2'}
]); ]);
async.done(); async.done();
}
} }
}); });
@ -735,10 +751,12 @@ export function main() {
it('should fire an event after the value has been updated', it('should fire an event after the value has been updated',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ObservableWrapper.subscribe(a.valueChanges, (value) => { a.valueChanges.subscribe({
expect(a.value).toEqual(['new1', 'old2']); next: (value: any) => {
expect(value).toEqual(['new1', 'old2']); expect(a.value).toEqual(['new1', 'old2']);
async.done(); expect(value).toEqual(['new1', 'old2']);
async.done();
}
}); });
c1.updateValue('new1'); c1.updateValue('new1');
})); }));
@ -747,12 +765,14 @@ export function main() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var controlCallbackIsCalled = false; var controlCallbackIsCalled = false;
ObservableWrapper.subscribe(
c1.valueChanges, (value) => { controlCallbackIsCalled = true; });
ObservableWrapper.subscribe(a.valueChanges, (value) => { c1.valueChanges.subscribe({next: (value: any) => { controlCallbackIsCalled = true; }});
expect(controlCallbackIsCalled).toBe(true);
async.done(); a.valueChanges.subscribe({
next: (value: any) => {
expect(controlCallbackIsCalled).toBe(true);
async.done();
}
}); });
c1.updateValue('new1'); c1.updateValue('new1');
@ -760,9 +780,11 @@ export function main() {
it('should fire an event when a control is removed', it('should fire an event when a control is removed',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ObservableWrapper.subscribe(a.valueChanges, (value) => { a.valueChanges.subscribe({
expect(value).toEqual(['old1']); next: (value: any) => {
async.done(); expect(value).toEqual(['old1']);
async.done();
}
}); });
a.removeAt(1); a.removeAt(1);
@ -772,9 +794,11 @@ export function main() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
a.removeAt(1); a.removeAt(1);
ObservableWrapper.subscribe(a.valueChanges, (value) => { a.valueChanges.subscribe({
expect(value).toEqual(['old1', 'old2']); next: (value: any) => {
async.done(); expect(value).toEqual(['old1', 'old2']);
async.done();
}
}); });
a.push(c2); a.push(c2);

View File

@ -11,8 +11,7 @@ import {fakeAsync, flushMicrotasks, tick} from '@angular/core/testing';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal'; import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {Observable} from 'rxjs/Observable'; import {Observable} from 'rxjs/Observable';
import {EventEmitter, ObservableWrapper, TimerWrapper} from '../../src/facade/async'; import {EventEmitter} from '../../src/facade/async';
import {PromiseWrapper} from '../../src/facade/promise';
import {normalizeAsyncValidator} from '../../src/forms-deprecated/directives/normalize_validator'; import {normalizeAsyncValidator} from '../../src/forms-deprecated/directives/normalize_validator';
export function main() { export function main() {
@ -143,14 +142,14 @@ export function main() {
return (c: any /** TODO #9100 */) => { return (c: any /** TODO #9100 */) => {
var emitter = new EventEmitter(); var emitter = new EventEmitter();
var res = c.value != expected ? response : null; var res = c.value != expected ? response : null;
Promise.resolve(null).then(() => {
PromiseWrapper.scheduleMicrotask(() => { emitter.emit(res);
ObservableWrapper.callEmit(emitter, res);
// this is required because of a bug in ObservableWrapper // this is required because of a bug in ObservableWrapper
// where callComplete can fire before callEmit // where callComplete can fire before callEmit
// remove this one the bug is fixed // remove this one the bug is fixed
TimerWrapper.setTimeout(() => { ObservableWrapper.callComplete(emitter); }, 0); setTimeout(() => { emitter.complete(); }, 0);
}); });
return emitter; return emitter;
}; };
} }

View File

@ -6,16 +6,16 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal';
import {SpyChangeDetectorRef} from '../spies';
import {isBlank} from '../../src/facade/lang';
import {AsyncPipe} from '@angular/common'; import {AsyncPipe} from '@angular/common';
import {WrappedValue} from '@angular/core'; import {WrappedValue} from '@angular/core';
import {EventEmitter, ObservableWrapper, PromiseWrapper, TimerWrapper} from '../../src/facade/async'; import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {PromiseCompleter} from '../../src/facade/promise';
import {browserDetection} from '@angular/platform-browser/testing/browser_util'; import {browserDetection} from '@angular/platform-browser/testing/browser_util';
import {EventEmitter} from '../../src/facade/async';
import {isBlank} from '../../src/facade/lang';
import {SpyChangeDetectorRef} from '../spies';
export function main() { export function main() {
describe('AsyncPipe', () => { describe('AsyncPipe', () => {
@ -38,10 +38,9 @@ export function main() {
it('should return the latest available value wrapped', it('should return the latest available value wrapped',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(emitter); pipe.transform(emitter);
emitter.emit(message);
ObservableWrapper.callEmit(emitter, message); setTimeout(() => {
TimerWrapper.setTimeout(() => {
expect(pipe.transform(emitter)).toEqual(new WrappedValue(message)); expect(pipe.transform(emitter)).toEqual(new WrappedValue(message));
async.done(); async.done();
}, 0); }, 0);
@ -51,9 +50,9 @@ export function main() {
it('should return same value when nothing has changed since the last call', it('should return same value when nothing has changed since the last call',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(emitter); pipe.transform(emitter);
ObservableWrapper.callEmit(emitter, message); emitter.emit(message);
TimerWrapper.setTimeout(() => { setTimeout(() => {
pipe.transform(emitter); pipe.transform(emitter);
expect(pipe.transform(emitter)).toBe(message); expect(pipe.transform(emitter)).toBe(message);
async.done(); async.done();
@ -66,11 +65,10 @@ export function main() {
var newEmitter = new EventEmitter(); var newEmitter = new EventEmitter();
expect(pipe.transform(newEmitter)).toBe(null); expect(pipe.transform(newEmitter)).toBe(null);
emitter.emit(message);
// this should not affect the pipe // this should not affect the pipe
ObservableWrapper.callEmit(emitter, message); setTimeout(() => {
TimerWrapper.setTimeout(() => {
expect(pipe.transform(newEmitter)).toBe(null); expect(pipe.transform(newEmitter)).toBe(null);
async.done(); async.done();
}, 0); }, 0);
@ -79,9 +77,9 @@ export function main() {
it('should request a change detection check upon receiving a new value', it('should request a change detection check upon receiving a new value',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(emitter); pipe.transform(emitter);
ObservableWrapper.callEmit(emitter, message); emitter.emit(message);
TimerWrapper.setTimeout(() => { setTimeout(() => {
expect(ref.spy('markForCheck')).toHaveBeenCalled(); expect(ref.spy('markForCheck')).toHaveBeenCalled();
async.done(); async.done();
}, 10); }, 10);
@ -96,10 +94,9 @@ export function main() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(emitter); pipe.transform(emitter);
pipe.ngOnDestroy(); pipe.ngOnDestroy();
emitter.emit(message);
ObservableWrapper.callEmit(emitter, message); setTimeout(() => {
TimerWrapper.setTimeout(() => {
expect(pipe.transform(emitter)).toBe(null); expect(pipe.transform(emitter)).toBe(null);
async.done(); async.done();
}, 0); }, 0);
@ -110,57 +107,62 @@ export function main() {
describe('Promise', () => { describe('Promise', () => {
var message = new Object(); var message = new Object();
var pipe: AsyncPipe; var pipe: AsyncPipe;
var completer: PromiseCompleter<any>; var resolve: (result: any) => void;
var reject: (error: any) => void;
var promise: Promise<any>;
var ref: SpyChangeDetectorRef; var ref: SpyChangeDetectorRef;
// adds longer timers for passing tests in IE // adds longer timers for passing tests in IE
var timer = (!isBlank(getDOM()) && browserDetection.isIE) ? 50 : 10; var timer = (!isBlank(getDOM()) && browserDetection.isIE) ? 50 : 10;
beforeEach(() => { beforeEach(() => {
completer = PromiseWrapper.completer(); promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
ref = new SpyChangeDetectorRef(); ref = new SpyChangeDetectorRef();
pipe = new AsyncPipe(<any>ref); pipe = new AsyncPipe(<any>ref);
}); });
describe('transform', () => { describe('transform', () => {
it('should return null when subscribing to a promise', it('should return null when subscribing to a promise',
() => { expect(pipe.transform(completer.promise)).toBe(null); }); () => { expect(pipe.transform(promise)).toBe(null); });
it('should return the latest available value', it('should return the latest available value',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(completer.promise); pipe.transform(promise);
completer.resolve(message); resolve(message);
TimerWrapper.setTimeout(() => { setTimeout(() => {
expect(pipe.transform(completer.promise)).toEqual(new WrappedValue(message)); expect(pipe.transform(promise)).toEqual(new WrappedValue(message));
async.done(); async.done();
}, timer); }, timer);
})); }));
it('should return unwrapped value when nothing has changed since the last call', it('should return unwrapped value when nothing has changed since the last call',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(completer.promise); pipe.transform(promise);
completer.resolve(message); resolve(message);
TimerWrapper.setTimeout(() => { setTimeout(() => {
pipe.transform(completer.promise); pipe.transform(promise);
expect(pipe.transform(completer.promise)).toBe(message); expect(pipe.transform(promise)).toBe(message);
async.done(); async.done();
}, timer); }, timer);
})); }));
it('should dispose of the existing subscription when subscribing to a new promise', it('should dispose of the existing subscription when subscribing to a new promise',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(completer.promise); pipe.transform(promise);
var newCompleter = PromiseWrapper.completer(); var promise = new Promise<any>(() => {});
expect(pipe.transform(newCompleter.promise)).toBe(null); expect(pipe.transform(promise)).toBe(null);
// this should not affect the pipe, so it should return WrappedValue // this should not affect the pipe, so it should return WrappedValue
completer.resolve(message); resolve(message);
TimerWrapper.setTimeout(() => { setTimeout(() => {
expect(pipe.transform(newCompleter.promise)).toBe(null); expect(pipe.transform(promise)).toBe(null);
async.done(); async.done();
}, timer); }, timer);
})); }));
@ -168,10 +170,10 @@ export function main() {
it('should request a change detection check upon receiving a new value', it('should request a change detection check upon receiving a new value',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var markForCheck = ref.spy('markForCheck'); var markForCheck = ref.spy('markForCheck');
pipe.transform(completer.promise); pipe.transform(promise);
completer.resolve(message); resolve(message);
TimerWrapper.setTimeout(() => { setTimeout(() => {
expect(markForCheck).toHaveBeenCalled(); expect(markForCheck).toHaveBeenCalled();
async.done(); async.done();
}, timer); }, timer);
@ -183,15 +185,15 @@ export function main() {
it('should dispose of the existing source', it('should dispose of the existing source',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(completer.promise); pipe.transform(promise);
expect(pipe.transform(completer.promise)).toBe(null); expect(pipe.transform(promise)).toBe(null);
completer.resolve(message); resolve(message);
TimerWrapper.setTimeout(() => { setTimeout(() => {
expect(pipe.transform(completer.promise)).toEqual(new WrappedValue(message)); expect(pipe.transform(promise)).toEqual(new WrappedValue(message));
pipe.ngOnDestroy(); pipe.ngOnDestroy();
expect(pipe.transform(completer.promise)).toBe(null); expect(pipe.transform(promise)).toBe(null);
async.done(); async.done();
}, timer); }, timer);
})); }));

View File

@ -6,13 +6,13 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, ddescribe, describe, it, iit, xit, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing/matchers';
import {TestComponentBuilder} from '@angular/core/testing';
import {Json, StringWrapper} from '../../src/facade/lang';
import {Component} from '@angular/core';
import {JsonPipe} from '@angular/common'; import {JsonPipe} from '@angular/common';
import {Component} from '@angular/core';
import {TestComponentBuilder} from '@angular/core/testing';
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing/matchers';
import {Json, StringWrapper} from '../../src/facade/lang';
export function main() { export function main() {
describe('JsonPipe', () => { describe('JsonPipe', () => {

View File

@ -6,11 +6,10 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach,} from '@angular/core/testing/testing_internal'; import {CurrencyPipe, DecimalPipe, PercentPipe} from '@angular/common';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {browserDetection} from '@angular/platform-browser/testing/browser_util'; import {browserDetection} from '@angular/platform-browser/testing/browser_util';
import {DecimalPipe, PercentPipe, CurrencyPipe} from '@angular/common';
export function main() { export function main() {
describe('Number pipes', () => { describe('Number pipes', () => {
// TODO(mlaval): enable tests when Intl API is no longer used, see // TODO(mlaval): enable tests when Intl API is no longer used, see

View File

@ -6,10 +6,8 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal';
import {ReplacePipe} from '@angular/common'; import {ReplacePipe} from '@angular/common';
import {StringJoiner} from '../../src/facade/lang'; import {afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
export function main() { export function main() {
describe('ReplacePipe', () => { describe('ReplacePipe', () => {

View File

@ -6,13 +6,12 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, ddescribe, describe, it, iit, xit, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing/matchers';
import {TestComponentBuilder} from '@angular/core/testing';
import {browserDetection} from '@angular/platform-browser/testing/browser_util';
import {Component} from '@angular/core';
import {SlicePipe} from '@angular/common'; import {SlicePipe} from '@angular/common';
import {Component} from '@angular/core';
import {TestComponentBuilder} from '@angular/core/testing';
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {browserDetection} from '@angular/platform-browser/testing/browser_util';
import {expect} from '@angular/platform-browser/testing/matchers';
export function main() { export function main() {
describe('SlicePipe', () => { describe('SlicePipe', () => {

View File

@ -9,7 +9,6 @@
import {EventEmitter, Injectable} from '@angular/core'; import {EventEmitter, Injectable} from '@angular/core';
import {Location} from '../index'; import {Location} from '../index';
import {ObservableWrapper} from '../src/facade/async';
import {LocationStrategy} from '../src/location/location_strategy'; import {LocationStrategy} from '../src/location/location_strategy';
@ -46,15 +45,13 @@ export class SpyLocation implements Location {
return currPath == givenPath + (query.length > 0 ? ('?' + query) : ''); return currPath == givenPath + (query.length > 0 ? ('?' + query) : '');
} }
simulateUrlPop(pathname: string) { simulateUrlPop(pathname: string) { this._subject.emit({'url': pathname, 'pop': true}); }
ObservableWrapper.callEmit(this._subject, {'url': pathname, 'pop': true});
}
simulateHashChange(pathname: string) { simulateHashChange(pathname: string) {
// Because we don't prevent the native event, the browser will independently update the path // Because we don't prevent the native event, the browser will independently update the path
this.setInitialPath(pathname); this.setInitialPath(pathname);
this.urlChanges.push('hash: ' + pathname); this.urlChanges.push('hash: ' + pathname);
ObservableWrapper.callEmit(this._subject, {'url': pathname, 'pop': true, 'type': 'hashchange'}); this._subject.emit({'url': pathname, 'pop': true, 'type': 'hashchange'});
} }
prepareExternalUrl(url: string): string { prepareExternalUrl(url: string): string {
@ -100,21 +97,21 @@ export class SpyLocation implements Location {
forward() { forward() {
if (this._historyIndex < (this._history.length - 1)) { if (this._historyIndex < (this._history.length - 1)) {
this._historyIndex++; this._historyIndex++;
ObservableWrapper.callEmit(this._subject, {'url': this.path(), 'pop': true}); this._subject.emit({'url': this.path(), 'pop': true});
} }
} }
back() { back() {
if (this._historyIndex > 0) { if (this._historyIndex > 0) {
this._historyIndex--; this._historyIndex--;
ObservableWrapper.callEmit(this._subject, {'url': this.path(), 'pop': true}); this._subject.emit({'url': this.path(), 'pop': true});
} }
} }
subscribe( subscribe(
onNext: (value: any) => void, onThrow: (error: any) => void = null, onNext: (value: any) => void, onThrow: (error: any) => void = null,
onReturn: () => void = null): Object { onReturn: () => void = null): Object {
return ObservableWrapper.subscribe(this._subject, onNext, onThrow, onReturn); return this._subject.subscribe({next: onNext, error: onThrow, complete: onReturn});
} }
normalize(url: string): string { return null; } normalize(url: string): string { return null; }

View File

@ -9,7 +9,7 @@
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {LocationStrategy} from '../index'; import {LocationStrategy} from '../index';
import {EventEmitter, ObservableWrapper} from '../src/facade/async'; import {EventEmitter} from '../src/facade/async';
@ -31,7 +31,7 @@ export class MockLocationStrategy extends LocationStrategy {
simulatePopState(url: string): void { simulatePopState(url: string): void {
this.internalPath = url; this.internalPath = url;
ObservableWrapper.callEmit(this._subject, new _MockPopStateEvent(this.path())); this._subject.emit(new _MockPopStateEvent(this.path()));
} }
path(includeHash: boolean = false): string { return this.internalPath; } path(includeHash: boolean = false): string { return this.internalPath; }
@ -63,7 +63,7 @@ export class MockLocationStrategy extends LocationStrategy {
this.urlChanges.push('replace: ' + externalUrl); this.urlChanges.push('replace: ' + externalUrl);
} }
onPopState(fn: (value: any) => void): void { ObservableWrapper.subscribe(this._subject, fn); } onPopState(fn: (value: any) => void): void { this._subject.subscribe({next: fn}); }
getBaseHref(): string { return this.internalBaseHref; } getBaseHref(): string { return this.internalBaseHref; }

View File

@ -6,13 +6,14 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {isPresent, isBlank,} from '../facade/lang';
import {ListWrapper} from '../facade/collection'; import {ListWrapper} from '../facade/collection';
import {isBlank, isPresent} from '../facade/lang';
import {ParseError, ParseSourceSpan} from '../parse_util';
import * as html from './ast'; import * as html from './ast';
import * as lex from './lexer';
import {ParseSourceSpan, ParseError} from '../parse_util';
import {TagDefinition, getNsPrefix, mergeNsAndName} from './tags';
import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from './interpolation_config'; import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from './interpolation_config';
import * as lex from './lexer';
import {TagDefinition, getNsPrefix, mergeNsAndName} from './tags';
export class TreeError extends ParseError { export class TreeError extends ParseError {
static create(elementName: string, span: ParseSourceSpan, msg: string): TreeError { static create(elementName: string, span: ParseSourceSpan, msg: string): TreeError {

View File

@ -6,11 +6,12 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {OnInit, OnDestroy, DoCheck, OnChanges, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked,} from '@angular/core'; import {AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, DoCheck, OnChanges, OnDestroy, OnInit} from '@angular/core';
import {reflector, LifecycleHooks} from '../core_private';
import {LifecycleHooks, reflector} from '../core_private';
import {Type} from './facade/lang';
import {MapWrapper} from './facade/collection'; import {MapWrapper} from './facade/collection';
import {Type} from './facade/lang';
const LIFECYCLE_INTERFACES: Map<any, Type> = MapWrapper.createFromPairs([ const LIFECYCLE_INTERFACES: Map<any, Type> = MapWrapper.createFromPairs([
[LifecycleHooks.OnInit, OnInit], [LifecycleHooks.OnInit, OnInit],

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {ObservableWrapper} from '../facade/async';
import {ListWrapper} from '../facade/collection'; import {ListWrapper} from '../facade/collection';
import {BaseException, unimplemented} from '../facade/exceptions'; import {BaseException, unimplemented} from '../facade/exceptions';
import {isPresent} from '../facade/lang'; import {isPresent} from '../facade/lang';
@ -157,7 +156,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
result = ListWrapper.concat(receiver, args[0]); result = ListWrapper.concat(receiver, args[0]);
break; break;
case o.BuiltinMethod.SubscribeObservable: case o.BuiltinMethod.SubscribeObservable:
result = ObservableWrapper.subscribe(receiver, args[0]); result = receiver.subscribe({next: args[0]});
break; break;
case o.BuiltinMethod.bind: case o.BuiltinMethod.bind:
result = receiver.bind(args[0]); result = receiver.bind(args[0]);

View File

@ -6,11 +6,12 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {isPresent, evalExpression,} from '../facade/lang'; import {evalExpression, isPresent} from '../facade/lang';
import * as o from './output_ast'; import {sanitizeIdentifier} from '../util';
import {EmitterVisitorContext} from './abstract_emitter'; import {EmitterVisitorContext} from './abstract_emitter';
import {AbstractJsEmitterVisitor} from './abstract_js_emitter'; import {AbstractJsEmitterVisitor} from './abstract_js_emitter';
import {sanitizeIdentifier} from '../util'; import * as o from './output_ast';
export function jitStatements( export function jitStatements(
sourceUrl: string, statements: o.Statement[], resultVar: string): any { sourceUrl: string, statements: o.Statement[], resultVar: string): any {

View File

@ -13,7 +13,6 @@ import {Console} from '../core_private';
import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompileNgModuleMetadata, CompilePipeMetadata, createHostComponentMeta} from './compile_metadata'; import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompileNgModuleMetadata, CompilePipeMetadata, createHostComponentMeta} from './compile_metadata';
import {CompilerConfig} from './config'; import {CompilerConfig} from './config';
import {DirectiveNormalizer} from './directive_normalizer'; import {DirectiveNormalizer} from './directive_normalizer';
import {PromiseWrapper} from './facade/async';
import {BaseException} from './facade/exceptions'; import {BaseException} from './facade/exceptions';
import {ConcreteType, Type, isBlank, isString, stringify} from './facade/lang'; import {ConcreteType, Type, isBlank, isString, stringify} from './facade/lang';
import {CompileMetadataResolver} from './metadata_resolver'; import {CompileMetadataResolver} from './metadata_resolver';
@ -426,8 +425,8 @@ class ModuleBoundCompiler implements Compiler, ComponentResolver {
if (this._parentComponentResolver) { if (this._parentComponentResolver) {
return this._parentComponentResolver.resolveComponent(component); return this._parentComponentResolver.resolveComponent(component);
} else { } else {
return PromiseWrapper.reject( return <Promise<any>>Promise.reject(
new BaseException(`Cannot resolve component using '${component}'.`), null); new BaseException(`Cannot resolve component using '${component}'.`));
} }
} }
if (this._warnOnComponentResolver) { if (this._warnOnComponentResolver) {

View File

@ -6,13 +6,14 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {SecurityContext} from '@angular/core';
import {LifecycleHooks} from '../../core_private';
import {CompileDirectiveMetadata, CompileProviderMetadata, CompileTokenMetadata} from '../compile_metadata';
import {AST} from '../expression_parser/ast'; import {AST} from '../expression_parser/ast';
import {isPresent} from '../facade/lang'; import {isPresent} from '../facade/lang';
import {CompileDirectiveMetadata, CompileTokenMetadata, CompileProviderMetadata,} from '../compile_metadata';
import {ParseSourceSpan} from '../parse_util'; import {ParseSourceSpan} from '../parse_util';
import {SecurityContext} from '@angular/core';
import {LifecycleHooks} from '../../core_private';
/** /**
* An Abstract Syntax Tree node representing part of a parsed Angular template. * An Abstract Syntax Tree node representing part of a parsed Angular template.

View File

@ -7,28 +7,30 @@
*/ */
import {Inject, Injectable, OpaqueToken, Optional, SchemaMetadata, SecurityContext} from '@angular/core'; import {Inject, Injectable, OpaqueToken, Optional, SchemaMetadata, SecurityContext} from '@angular/core';
import {Console, MAX_INTERPOLATION_VALUES} from '../../core_private';
import {ListWrapper, StringMapWrapper, SetWrapper,} from '../facade/collection'; import {Console, MAX_INTERPOLATION_VALUES} from '../../core_private';
import {isPresent, isBlank} from '../facade/lang'; import {CompileDirectiveMetadata, CompilePipeMetadata, CompileTokenMetadata, removeIdentifierDuplicates} from '../compile_metadata';
import {BaseException} from '../facade/exceptions'; import {AST, ASTWithSource, BindingPipe, EmptyExpr, Interpolation, ParserError, RecursiveAstVisitor, TemplateBinding} from '../expression_parser/ast';
import {EmptyExpr, AST, Interpolation, ASTWithSource, TemplateBinding, RecursiveAstVisitor, BindingPipe, ParserError} from '../expression_parser/ast';
import {Parser} from '../expression_parser/parser'; import {Parser} from '../expression_parser/parser';
import {CompileDirectiveMetadata, CompilePipeMetadata, CompileTokenMetadata, removeIdentifierDuplicates,} from '../compile_metadata'; import {ListWrapper, SetWrapper, StringMapWrapper} from '../facade/collection';
import {HtmlParser, ParseTreeResult} from '../html_parser/html_parser'; import {BaseException} from '../facade/exceptions';
import {splitNsName, mergeNsAndName} from '../html_parser/tags'; import {isBlank, isPresent} from '../facade/lang';
import {ParseSourceSpan, ParseError, ParseErrorLevel} from '../parse_util';
import {InterpolationConfig} from '../html_parser/interpolation_config';
import {ElementAst, BoundElementPropertyAst, BoundEventAst, ReferenceAst, TemplateAst, TemplateAstVisitor, templateVisitAll, TextAst, BoundTextAst, EmbeddedTemplateAst, AttrAst, NgContentAst, PropertyBindingType, DirectiveAst, BoundDirectivePropertyAst, VariableAst} from './template_ast';
import {CssSelector, SelectorMatcher} from '../selector';
import {ElementSchemaRegistry} from '../schema/element_schema_registry';
import {preparseElement, PreparsedElementType} from './template_preparser';
import {isStyleUrlResolvable} from '../style_url_resolver';
import * as html from '../html_parser/ast'; import * as html from '../html_parser/ast';
import {splitAtColon} from '../util'; import {HtmlParser, ParseTreeResult} from '../html_parser/html_parser';
import {identifierToken, Identifiers} from '../identifiers';
import {expandNodes} from '../html_parser/icu_ast_expander'; import {expandNodes} from '../html_parser/icu_ast_expander';
import {InterpolationConfig} from '../html_parser/interpolation_config';
import {mergeNsAndName, splitNsName} from '../html_parser/tags';
import {Identifiers, identifierToken} from '../identifiers';
import {ParseError, ParseErrorLevel, ParseSourceSpan} from '../parse_util';
import {ProviderElementContext, ProviderViewContext} from '../provider_analyzer'; import {ProviderElementContext, ProviderViewContext} from '../provider_analyzer';
import {ElementSchemaRegistry} from '../schema/element_schema_registry';
import {CssSelector, SelectorMatcher} from '../selector';
import {isStyleUrlResolvable} from '../style_url_resolver';
import {splitAtColon} from '../util';
import {AttrAst, BoundDirectivePropertyAst, BoundElementPropertyAst, BoundEventAst, BoundTextAst, DirectiveAst, ElementAst, EmbeddedTemplateAst, NgContentAst, PropertyBindingType, ReferenceAst, TemplateAst, TemplateAstVisitor, TextAst, VariableAst, templateVisitAll} from './template_ast';
import {PreparsedElementType, preparseElement} from './template_preparser';
// Group 1 = "bind-" // Group 1 = "bind-"
// Group 2 = "var-" // Group 2 = "var-"

View File

@ -8,21 +8,20 @@
import {BaseException} from '@angular/core'; import {BaseException} from '@angular/core';
import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileIdentifierMap, CompileIdentifierMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata} from '../compile_metadata';
import {ListWrapper, StringMapWrapper} from '../facade/collection'; import {ListWrapper, StringMapWrapper} from '../facade/collection';
import {isBlank, isPresent} from '../facade/lang'; import {isBlank, isPresent} from '../facade/lang';
import {Identifiers, identifierToken} from '../identifiers'; import {Identifiers, identifierToken} from '../identifiers';
import * as o from '../output/output_ast'; import * as o from '../output/output_ast';
import {convertValueToOutputAst} from '../output/value_util'; import {convertValueToOutputAst} from '../output/value_util';
import {ProviderAst, ProviderAstType, ReferenceAst, TemplateAst} from '../template_parser/template_ast'; import {ProviderAst, ProviderAstType, ReferenceAst, TemplateAst} from '../template_parser/template_ast';
import {createDiTokenExpression} from '../util';
import {CompileMethod} from './compile_method';
import {CompileQuery, addQueryToTokenMap, createQueryList} from './compile_query';
import {CompileView} from './compile_view'; import {CompileView} from './compile_view';
import {InjectMethodVars} from './constants'; import {InjectMethodVars} from './constants';
import {CompileIdentifierMap, CompileDirectiveMetadata, CompileTokenMetadata, CompileQueryMetadata, CompileProviderMetadata, CompileDiDependencyMetadata, CompileIdentifierMetadata,} from '../compile_metadata';
import {getPropertyInView, injectFromViewParentInjector} from './util'; import {getPropertyInView, injectFromViewParentInjector} from './util';
import {CompileQuery, createQueryList, addQueryToTokenMap} from './compile_query';
import {CompileMethod} from './compile_method';
import {createDiTokenExpression} from '../util';
export class CompileNode { export class CompileNode {
constructor( constructor(

View File

@ -6,20 +6,22 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {SecurityContext} from '@angular/core';
import {EMPTY_STATE as EMPTY_ANIMATION_STATE, LifecycleHooks, isDefaultChangeDetectionStrategy} from '../../core_private'; import {EMPTY_STATE as EMPTY_ANIMATION_STATE, LifecycleHooks, isDefaultChangeDetectionStrategy} from '../../core_private';
import * as cdAst from '../expression_parser/ast'; import * as cdAst from '../expression_parser/ast';
import {isBlank, isPresent} from '../facade/lang'; import {isBlank, isPresent} from '../facade/lang';
import {Identifiers} from '../identifiers'; import {Identifiers} from '../identifiers';
import * as o from '../output/output_ast'; import * as o from '../output/output_ast';
import {DetectChangesVars, ViewProperties} from './constants'; import {BoundElementPropertyAst, BoundTextAst, DirectiveAst, PropertyBindingType} from '../template_parser/template_ast';
import {BoundTextAst, BoundElementPropertyAst, DirectiveAst, PropertyBindingType,} from '../template_parser/template_ast'; import {camelCaseToDashCase} from '../util';
import {CompileView} from './compile_view';
import {CompileBinding} from './compile_binding';
import {CompileElement, CompileNode} from './compile_element'; import {CompileElement, CompileNode} from './compile_element';
import {CompileMethod} from './compile_method'; import {CompileMethod} from './compile_method';
import {camelCaseToDashCase} from '../util'; import {CompileView} from './compile_view';
import {DetectChangesVars, ViewProperties} from './constants';
import {convertCdExpressionToIr} from './expression_converter'; import {convertCdExpressionToIr} from './expression_converter';
import {CompileBinding} from './compile_binding';
import {SecurityContext} from '@angular/core';
function createBindFieldExpr(exprIndex: number): o.ReadPropExpr { function createBindFieldExpr(exprIndex: number): o.ReadPropExpr {
return o.THIS_EXPR.prop(`_expr_${exprIndex}`); return o.THIS_EXPR.prop(`_expr_${exprIndex}`);

View File

@ -6,15 +6,15 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {CompileDirectiveMetadata, CompileTokenMetadata} from '../compile_metadata';
import {BaseException} from '../facade/exceptions'; import {BaseException} from '../facade/exceptions';
import {isBlank, isPresent} from '../facade/lang'; import {isBlank, isPresent} from '../facade/lang';
import * as o from '../output/output_ast';
import {CompileTokenMetadata, CompileDirectiveMetadata,} from '../compile_metadata';
import {CompileView} from './compile_view';
import {Identifiers} from '../identifiers'; import {Identifiers} from '../identifiers';
import * as o from '../output/output_ast';
import {createDiTokenExpression} from '../util'; import {createDiTokenExpression} from '../util';
import {CompileView} from './compile_view';
export function getPropertyInView( export function getPropertyInView(
property: o.Expression, callingView: CompileView, definedView: CompileView): o.Expression { property: o.Expression, callingView: CompileView, definedView: CompileView): o.Expression {
if (callingView === definedView) { if (callingView === definedView) {

View File

@ -6,14 +6,15 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {ListWrapper,} from '../facade/collection'; import {ListWrapper} from '../facade/collection';
import {TemplateAst, TemplateAstVisitor, NgContentAst, EmbeddedTemplateAst, ElementAst, ReferenceAst, VariableAst, BoundEventAst, BoundElementPropertyAst, AttrAst, BoundTextAst, TextAst, DirectiveAst, BoundDirectivePropertyAst, templateVisitAll,} from '../template_parser/template_ast';
import {bindRenderText, bindRenderInputs, bindDirectiveInputs, bindDirectiveHostProps} from './property_binder';
import {bindRenderOutputs, collectEventListeners, bindDirectiveOutputs} from './event_binder';
import {bindDirectiveAfterContentLifecycleCallbacks, bindDirectiveAfterViewLifecycleCallbacks, bindInjectableDestroyLifecycleCallbacks, bindPipeDestroyLifecycleCallbacks, bindDirectiveDetectChangesLifecycleCallbacks} from './lifecycle_binder';
import {CompileView} from './compile_view';
import {CompileElement, CompileNode} from './compile_element';
import {identifierToken} from '../identifiers'; import {identifierToken} from '../identifiers';
import {AttrAst, BoundDirectivePropertyAst, BoundElementPropertyAst, BoundEventAst, BoundTextAst, DirectiveAst, ElementAst, EmbeddedTemplateAst, NgContentAst, ReferenceAst, TemplateAst, TemplateAstVisitor, TextAst, VariableAst, templateVisitAll} from '../template_parser/template_ast';
import {CompileElement, CompileNode} from './compile_element';
import {CompileView} from './compile_view';
import {bindDirectiveOutputs, bindRenderOutputs, collectEventListeners} from './event_binder';
import {bindDirectiveAfterContentLifecycleCallbacks, bindDirectiveAfterViewLifecycleCallbacks, bindDirectiveDetectChangesLifecycleCallbacks, bindInjectableDestroyLifecycleCallbacks, bindPipeDestroyLifecycleCallbacks} from './lifecycle_binder';
import {bindDirectiveHostProps, bindDirectiveInputs, bindRenderInputs, bindRenderText} from './property_binder';
export function bindView(view: CompileView, parsedTemplate: TemplateAst[]): void { export function bindView(view: CompileView, parsedTemplate: TemplateAst[]): void {
var visitor = new ViewBinderVisitor(view); var visitor = new ViewBinderVisitor(view);

View File

@ -6,10 +6,9 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {beforeEach, xdescribe, ddescribe, describe, expect, iit, inject, it,} from '@angular/core/testing/testing_internal';
import {hasLifecycleHook} from '@angular/compiler/src/lifecycle_reflector'; import {hasLifecycleHook} from '@angular/compiler/src/lifecycle_reflector';
import {LifecycleHooks} from '@angular/core/src/metadata/lifecycle_hooks'; import {LifecycleHooks} from '@angular/core/src/metadata/lifecycle_hooks';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe} from '@angular/core/testing/testing_internal';
export function main() { export function main() {
describe('Create DirectiveMetadata', () => { describe('Create DirectiveMetadata', () => {

View File

@ -6,11 +6,11 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {beforeEach, ddescribe, describe, expect, iit, it, inject,} from '@angular/core/testing/testing_internal'; import {Component, ComponentMetadata, Injector, ViewMetadata} from '@angular/core';
import {beforeEach, ddescribe, describe, expect, iit, inject, it} from '@angular/core/testing/testing_internal';
import {stringify, isBlank} from '../src/facade/lang'; import {isBlank, stringify} from '../src/facade/lang';
import {MockDirectiveResolver} from '../testing'; import {MockDirectiveResolver} from '../testing';
import {Component, ViewMetadata, Injector, ComponentMetadata} from '@angular/core';
export function main() { export function main() {
describe('MockDirectiveResolver', () => { describe('MockDirectiveResolver', () => {

View File

@ -6,11 +6,11 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {beforeEach, ddescribe, describe, expect, iit, it, inject,} from '@angular/core/testing/testing_internal'; import {Injector, NgModule, NgModuleMetadata} from '@angular/core';
import {beforeEach, ddescribe, describe, expect, iit, inject, it} from '@angular/core/testing/testing_internal';
import {stringify, isBlank} from '../src/facade/lang'; import {isBlank, stringify} from '../src/facade/lang';
import {MockNgModuleResolver} from '../testing'; import {MockNgModuleResolver} from '../testing';
import {NgModule, NgModuleMetadata, Injector} from '@angular/core';
export function main() { export function main() {
describe('MockNgModuleResolver', () => { describe('MockNgModuleResolver', () => {

View File

@ -6,9 +6,8 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {escapeSingleQuoteString} from '@angular/compiler/src/output/abstract_emitter'; import {escapeSingleQuoteString} from '@angular/compiler/src/output/abstract_emitter';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
export function main() { export function main() {
describe('AbstractEmitter', () => { describe('AbstractEmitter', () => {

View File

@ -6,12 +6,13 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal'; import {CompileIdentifierMetadata} from '@angular/compiler/src/compile_metadata';
import {JavaScriptEmitter} from '@angular/compiler/src/output/js_emitter';
import * as o from '@angular/compiler/src/output/output_ast';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {isBlank} from '../../src/facade/lang'; import {isBlank} from '../../src/facade/lang';
import {JavaScriptEmitter} from '@angular/compiler/src/output/js_emitter';
import {CompileIdentifierMetadata} from '@angular/compiler/src/compile_metadata';
import * as o from '@angular/compiler/src/output/output_ast';
import {SimpleJsImportGenerator} from './output_emitter_util'; import {SimpleJsImportGenerator} from './output_emitter_util';
var someModuleUrl = 'asset:somePackage/lib/somePath'; var someModuleUrl = 'asset:somePackage/lib/somePath';

View File

@ -6,18 +6,18 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {beforeEach, ddescribe, describe, iit, inject, it, xit,} from '@angular/core/testing/testing_internal'; import {interpretStatements} from '@angular/compiler/src/output/output_interpreter';
import {jitStatements} from '@angular/compiler/src/output/output_jit';
import {BaseException, EventEmitter} from '@angular/core';
import {ViewType} from '@angular/core/src/linker/view_type';
import {beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {browserDetection} from '@angular/platform-browser/testing/browser_util';
import {expect} from '@angular/platform-browser/testing/matchers'; import {expect} from '@angular/platform-browser/testing/matchers';
import * as typed from './output_emitter_codegen_typed'; import * as typed from './output_emitter_codegen_typed';
import * as untyped from './output_emitter_codegen_untyped'; import * as untyped from './output_emitter_codegen_untyped';
import {jitStatements} from '@angular/compiler/src/output/output_jit'; import {ExternalClass, codegenStmts} from './output_emitter_util';
import {interpretStatements} from '@angular/compiler/src/output/output_interpreter';
import {codegenStmts, ExternalClass} from './output_emitter_util';
import {BaseException, EventEmitter} from '@angular/core';
import {ViewType} from '@angular/core/src/linker/view_type';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {browserDetection} from '@angular/platform-browser/testing/browser_util';
export function main() { export function main() {
var outputDefs: any[] /** TODO #9100 */ = []; var outputDefs: any[] /** TODO #9100 */ = [];

View File

@ -6,12 +6,13 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {isBlank} from '../../src/facade/lang';
import {TypeScriptEmitter} from '@angular/compiler/src/output/ts_emitter';
import {CompileIdentifierMetadata} from '@angular/compiler/src/compile_metadata'; import {CompileIdentifierMetadata} from '@angular/compiler/src/compile_metadata';
import * as o from '@angular/compiler/src/output/output_ast'; import * as o from '@angular/compiler/src/output/output_ast';
import {TypeScriptEmitter} from '@angular/compiler/src/output/ts_emitter';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {isBlank} from '../../src/facade/lang';
import {SimpleJsImportGenerator} from './output_emitter_util'; import {SimpleJsImportGenerator} from './output_emitter_util';
var someModuleUrl = 'asset:somePackage/lib/somePath'; var someModuleUrl = 'asset:somePackage/lib/somePath';

View File

@ -6,11 +6,11 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {beforeEach, ddescribe, describe, expect, iit, it, inject,} from '@angular/core/testing/testing_internal'; import {Injector, Pipe, PipeMetadata} from '@angular/core';
import {beforeEach, ddescribe, describe, expect, iit, inject, it} from '@angular/core/testing/testing_internal';
import {stringify, isBlank} from '../src/facade/lang'; import {isBlank, stringify} from '../src/facade/lang';
import {MockPipeResolver} from '../testing'; import {MockPipeResolver} from '../testing';
import {Pipe, PipeMetadata, Injector} from '@angular/core';
export function main() { export function main() {
describe('MockPipeResolver', () => { describe('MockPipeResolver', () => {

View File

@ -6,13 +6,14 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {beforeEach, ddescribe, xdescribe, describe, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal'; import {DirectiveResolver, XHR} from '@angular/compiler';
import {expect} from '@angular/platform-browser/testing/matchers';
import {Injectable, Component, Input, ViewMetadata, Compiler, ComponentFactory, Injector, NgModule, NgModuleFactory} from '@angular/core';
import {ConcreteType, stringify} from '../src/facade/lang';
import {fakeAsync, tick, TestComponentBuilder, ComponentFixture, TestBed} from '@angular/core/testing';
import {XHR, DirectiveResolver} from '@angular/compiler';
import {MockDirectiveResolver} from '@angular/compiler/testing'; import {MockDirectiveResolver} from '@angular/compiler/testing';
import {Compiler, Component, ComponentFactory, Injectable, Injector, Input, NgModule, NgModuleFactory, ViewMetadata} from '@angular/core';
import {ComponentFixture, TestBed, TestComponentBuilder, fakeAsync, tick} from '@angular/core/testing';
import {beforeEach, beforeEachProviders, ddescribe, describe, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing/matchers';
import {ConcreteType, stringify} from '../src/facade/lang';
import {SpyXHR} from './spies'; import {SpyXHR} from './spies';

View File

@ -6,11 +6,11 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {describe, beforeEach, it, expect, ddescribe, iit,} from '@angular/core/testing/testing_internal'; import {CssRule, ShadowCss, processRules} from '@angular/compiler/src/shadow_css';
import {ShadowCss, processRules, CssRule} from '@angular/compiler/src/shadow_css'; import {beforeEach, ddescribe, describe, expect, iit, it} from '@angular/core/testing/testing_internal';
import {normalizeCSS} from '@angular/platform-browser/testing/browser_util';
import {StringWrapper, isPresent} from '../src/facade/lang'; import {StringWrapper, isPresent} from '../src/facade/lang';
import {normalizeCSS} from '@angular/platform-browser/testing/browser_util';
export function main() { export function main() {
describe('ShadowCss', function() { describe('ShadowCss', function() {

View File

@ -6,14 +6,12 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing/matchers';
import {TestComponentBuilder, ComponentFixtureAutoDetect, ComponentFixtureNoNgZone, withProviders} from '@angular/core/testing';
import {Injectable, Component, Input, ViewMetadata, Pipe, NgModule} from '@angular/core';
import {NgIf} from '@angular/common'; import {NgIf} from '@angular/common';
import {TimerWrapper} from '../src/facade/async'; import {Component, Injectable, Input, NgModule, Pipe, ViewMetadata} from '@angular/core';
import {PromiseWrapper} from '../src/facade/promise'; import {ComponentFixtureAutoDetect, ComponentFixtureNoNgZone, TestComponentBuilder, withProviders} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {dispatchEvent} from '@angular/platform-browser/testing/browser_util'; import {dispatchEvent} from '@angular/platform-browser/testing/browser_util';
import {expect} from '@angular/platform-browser/testing/matchers';
@Component( @Component(
{selector: 'child-comp', template: `<span>Original {{childBinding}}</span>`, directives: []}) {selector: 'child-comp', template: `<span>Original {{childBinding}}</span>`, directives: []})
@ -80,7 +78,7 @@ class AsyncComp {
text: string = '1'; text: string = '1';
click() { click() {
PromiseWrapper.resolve(null).then((_) => { this.text += '1'; }); Promise.resolve(null).then((_) => { this.text += '1'; });
} }
} }
@ -90,7 +88,7 @@ class AsyncChildComp {
@Input() @Input()
set text(value: string) { set text(value: string) {
PromiseWrapper.resolve(null).then((_) => { this.localText = value; }); Promise.resolve(null).then((_) => { this.localText = value; });
} }
} }
@ -110,7 +108,7 @@ class AsyncTimeoutComp {
text: string = '1'; text: string = '1';
click() { click() {
TimerWrapper.setTimeout(() => { this.text += '1'; }, 10); setTimeout(() => { this.text += '1'; }, 10);
} }
} }
@ -120,8 +118,7 @@ class NestedAsyncTimeoutComp {
text: string = '1'; text: string = '1';
click() { click() {
TimerWrapper.setTimeout( setTimeout(() => { setTimeout(() => { this.text += '1'; }, 10); }, 10);
() => { TimerWrapper.setTimeout(() => { this.text += '1'; }, 10); }, 10);
} }
} }

View File

@ -6,9 +6,8 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it,} from '@angular/core/testing/testing_internal';
import {MockXHR} from '@angular/compiler/testing/xhr_mock'; import {MockXHR} from '@angular/compiler/testing/xhr_mock';
import {PromiseWrapper} from '../src/facade/async'; import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it} from '@angular/core/testing/testing_internal';
import {isPresent} from '../src/facade/lang'; import {isPresent} from '../src/facade/lang';
export function main() { export function main() {
@ -39,7 +38,7 @@ export function main() {
return error; return error;
} }
PromiseWrapper.then(request, onResponse, onError); request.then(onResponse, onError);
} }
it('should return a response from the definitions', it('should return a response from the definitions',

View File

@ -9,7 +9,6 @@
import {BaseException} from '@angular/core'; import {BaseException} from '@angular/core';
import {XHR} from '../index'; import {XHR} from '../index';
import {PromiseCompleter, PromiseWrapper} from '../src/facade/async';
import {ListWrapper, Map} from '../src/facade/collection'; import {ListWrapper, Map} from '../src/facade/collection';
import {isBlank, normalizeBlank} from '../src/facade/lang'; import {isBlank, normalizeBlank} from '../src/facade/lang';
@ -103,19 +102,26 @@ export class MockXHR extends XHR {
} }
class _PendingRequest { class _PendingRequest {
completer: PromiseCompleter<string>; resolve: (result: string) => void;
reject: (error: any) => void;
promise: Promise<string>;
constructor(public url: string) { this.completer = PromiseWrapper.completer(); } constructor(public url: string) {
this.promise = new Promise((res, rej) => {
this.resolve = res;
this.reject = rej;
});
}
complete(response: string) { complete(response: string) {
if (isBlank(response)) { if (isBlank(response)) {
this.completer.reject(`Failed to load ${this.url}`, null); this.reject(`Failed to load ${this.url}`);
} else { } else {
this.completer.resolve(response); this.resolve(response);
} }
} }
getPromise(): Promise<string> { return this.completer.promise; } getPromise(): Promise<string> { return this.promise; }
} }
class _Expectation { class _Expectation {

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {ObservableWrapper, PromiseCompleter, PromiseWrapper} from '../src/facade/async';
import {ListWrapper} from '../src/facade/collection'; import {ListWrapper} from '../src/facade/collection';
import {BaseException, ExceptionHandler, unimplemented} from '../src/facade/exceptions'; import {BaseException, ExceptionHandler, unimplemented} from '../src/facade/exceptions';
import {ConcreteType, Type, isBlank, isPresent, isPromise, stringify} from '../src/facade/lang'; import {ConcreteType, Type, isBlank, isPresent, isPromise, stringify} from '../src/facade/lang';
@ -356,8 +355,8 @@ export class PlatformRef_ extends PlatformRef {
throw new Error('No ExceptionHandler. Is platform module (BrowserModule) included?'); throw new Error('No ExceptionHandler. Is platform module (BrowserModule) included?');
} }
moduleRef.onDestroy(() => ListWrapper.remove(this._modules, moduleRef)); moduleRef.onDestroy(() => ListWrapper.remove(this._modules, moduleRef));
ObservableWrapper.subscribe(ngZone.onError, (error: NgZoneError) => { ngZone.onError.subscribe({
exceptionHandler.call(error.error, error.stackTrace); next: (error: NgZoneError) => { exceptionHandler.call(error.error, error.stackTrace); }
}); });
return _callAndReportToExceptionHandler(exceptionHandler, () => { return _callAndReportToExceptionHandler(exceptionHandler, () => {
const initStatus: ApplicationInitStatus = moduleRef.injector.get(ApplicationInitStatus); const initStatus: ApplicationInitStatus = moduleRef.injector.get(ApplicationInitStatus);
@ -519,8 +518,9 @@ export class ApplicationRef_ extends ApplicationRef {
@Optional() private _testability: Testability) { @Optional() private _testability: Testability) {
super(); super();
this._enforceNoNewChanges = isDevMode(); this._enforceNoNewChanges = isDevMode();
ObservableWrapper.subscribe(
this._zone.onMicrotaskEmpty, (_) => { this._zone.run(() => { this.tick(); }); }); this._zone.onMicrotaskEmpty.subscribe(
{next: () => { this._zone.run(() => { this.tick(); }); }});
} }
/** /**

View File

@ -6,15 +6,17 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {Type, isBlank, isPresent, isArray,} from '../facade/lang'; import {ListWrapper, MapWrapper} from '../facade/collection';
import {MapWrapper, ListWrapper} from '../facade/collection'; import {Type, isArray, isBlank, isPresent} from '../facade/lang';
import {reflector} from '../reflection/reflection'; import {reflector} from '../reflection/reflection';
import {ReflectiveKey} from './reflective_key';
import {InjectMetadata, OptionalMetadata, SelfMetadata, HostMetadata, SkipSelfMetadata, DependencyMetadata} from './metadata';
import {NoAnnotationError, MixingMultiProvidersWithRegularProvidersError, InvalidProviderError} from './reflective_exceptions';
import {resolveForwardRef} from './forward_ref'; import {resolveForwardRef} from './forward_ref';
import {DependencyMetadata, HostMetadata, InjectMetadata, OptionalMetadata, SelfMetadata, SkipSelfMetadata} from './metadata';
import {Provider, ProviderBuilder, provide} from './provider'; import {Provider, ProviderBuilder, provide} from './provider';
import {isProviderLiteral, createProvider} from './provider_util'; import {createProvider, isProviderLiteral} from './provider_util';
import {InvalidProviderError, MixingMultiProvidersWithRegularProvidersError, NoAnnotationError} from './reflective_exceptions';
import {ReflectiveKey} from './reflective_key';
/** /**
* `Dependency` is used by the framework to extend DI. * `Dependency` is used by the framework to extend DI.

View File

@ -6,23 +6,23 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {ObservableWrapper} from '../facade/async'; import {AnimationGroupPlayer} from '../animation/animation_group_player';
import {AnimationPlayer} from '../animation/animation_player';
import {ViewAnimationMap} from '../animation/view_animation_map';
import {ChangeDetectorRef, ChangeDetectorStatus} from '../change_detection/change_detection';
import {Injector} from '../di/injector';
import {ListWrapper} from '../facade/collection'; import {ListWrapper} from '../facade/collection';
import {isPresent} from '../facade/lang'; import {isPresent} from '../facade/lang';
import {WtfScopeFn, wtfCreateScope, wtfLeave} from '../profile/profile';
import {RenderComponentType, RenderDebugInfo, Renderer} from '../render/api'; import {RenderComponentType, RenderDebugInfo, Renderer} from '../render/api';
import {DebugContext, StaticNodeDebugInfo} from './debug_context';
import {AppElement} from './element'; import {AppElement} from './element';
import {ElementInjector} from './element_injector';
import {ExpressionChangedAfterItHasBeenCheckedException, ViewDestroyedException, ViewWrappedException} from './exceptions';
import {ViewRef_} from './view_ref'; import {ViewRef_} from './view_ref';
import {ViewType} from './view_type'; import {ViewType} from './view_type';
import {ViewUtils, ensureSlotCount, flattenNestedViewRenderNodes} from './view_utils'; import {ViewUtils, ensureSlotCount, flattenNestedViewRenderNodes} from './view_utils';
import {ChangeDetectorRef, ChangeDetectorStatus,} from '../change_detection/change_detection';
import {wtfCreateScope, wtfLeave, WtfScopeFn} from '../profile/profile';
import {ExpressionChangedAfterItHasBeenCheckedException, ViewDestroyedException, ViewWrappedException} from './exceptions';
import {StaticNodeDebugInfo, DebugContext} from './debug_context';
import {ElementInjector} from './element_injector';
import {Injector} from '../di/injector';
import {AnimationPlayer} from '../animation/animation_player';
import {AnimationGroupPlayer} from '../animation/animation_group_player';
import {ViewAnimationMap} from '../animation/view_animation_map';
var _scope_check: WtfScopeFn = wtfCreateScope(`AppView#check(ascii id)`); var _scope_check: WtfScopeFn = wtfCreateScope(`AppView#check(ascii id)`);
@ -196,7 +196,7 @@ export abstract class AppView<T> {
this.disposables[i](); this.disposables[i]();
} }
for (var i = 0; i < this.subscriptions.length; i++) { for (var i = 0; i < this.subscriptions.length; i++) {
ObservableWrapper.dispose(this.subscriptions[i]); this.subscriptions[i].unsubscribe();
} }
this.destroyInternal(); this.destroyInternal();
this.dirtyParentQueriesInternal(); this.dirtyParentQueriesInternal();

View File

@ -12,12 +12,14 @@
*/ */
import {ChangeDetectionStrategy} from '../src/change_detection/change_detection'; import {ChangeDetectionStrategy} from '../src/change_detection/change_detection';
import {Type} from '../src/facade/lang';
import {AnimationEntryMetadata} from './animation/metadata'; import {AnimationEntryMetadata} from './animation/metadata';
import {AttributeMetadata, ContentChildMetadata, ContentChildrenMetadata, QueryMetadata, ViewChildMetadata, ViewChildrenMetadata, ViewQueryMetadata} from './metadata/di'; import {AttributeMetadata, ContentChildMetadata, ContentChildrenMetadata, QueryMetadata, ViewChildMetadata, ViewChildrenMetadata, ViewQueryMetadata} from './metadata/di';
import {ComponentMetadata, ComponentMetadataType, DirectiveMetadata, DirectiveMetadataType, HostBindingMetadata, HostListenerMetadata, InputMetadata, OutputMetadata, PipeMetadata, PipeMetadataType} from './metadata/directives'; import {ComponentMetadata, ComponentMetadataType, DirectiveMetadata, DirectiveMetadataType, HostBindingMetadata, HostListenerMetadata, InputMetadata, OutputMetadata, PipeMetadata, PipeMetadataType} from './metadata/directives';
import {ModuleWithProviders, NgModuleMetadata, NgModuleMetadataType, SchemaMetadata} from './metadata/ng_module'; import {ModuleWithProviders, NgModuleMetadata, NgModuleMetadataType, SchemaMetadata} from './metadata/ng_module';
import {ViewEncapsulation} from './metadata/view'; import {ViewEncapsulation} from './metadata/view';
import {TypeDecorator, makeDecorator, makeParamDecorator, makePropDecorator} from './util/decorators';
export {ANALYZE_FOR_ENTRY_COMPONENTS, AttributeMetadata, ContentChildMetadata, ContentChildrenMetadata, QueryMetadata, ViewChildMetadata, ViewChildrenMetadata, ViewQueryMetadata} from './metadata/di'; export {ANALYZE_FOR_ENTRY_COMPONENTS, AttributeMetadata, ContentChildMetadata, ContentChildrenMetadata, QueryMetadata, ViewChildMetadata, ViewChildrenMetadata, ViewQueryMetadata} from './metadata/di';
export {ComponentMetadata, ComponentMetadataType, DirectiveMetadata, DirectiveMetadataType, HostBindingMetadata, HostListenerMetadata, InputMetadata, OutputMetadata, PipeMetadata, PipeMetadataType} from './metadata/directives'; export {ComponentMetadata, ComponentMetadataType, DirectiveMetadata, DirectiveMetadataType, HostBindingMetadata, HostListenerMetadata, InputMetadata, OutputMetadata, PipeMetadata, PipeMetadataType} from './metadata/directives';
@ -25,8 +27,6 @@ export {AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit,
export {CUSTOM_ELEMENTS_SCHEMA, ModuleWithProviders, NgModuleMetadata, NgModuleMetadataType, SchemaMetadata} from './metadata/ng_module'; export {CUSTOM_ELEMENTS_SCHEMA, ModuleWithProviders, NgModuleMetadata, NgModuleMetadataType, SchemaMetadata} from './metadata/ng_module';
export {ViewEncapsulation, ViewMetadata} from './metadata/view'; export {ViewEncapsulation, ViewMetadata} from './metadata/view';
import {makeDecorator, makeParamDecorator, makePropDecorator, TypeDecorator,} from './util/decorators';
import {Type} from '../src/facade/lang';
/** /**
* Interface for the {@link DirectiveMetadata} decorator function. * Interface for the {@link DirectiveMetadata} decorator function.

View File

@ -7,7 +7,6 @@
*/ */
import {Injectable} from '../di/decorators'; import {Injectable} from '../di/decorators';
import {ObservableWrapper} from '../facade/async';
import {Map, MapWrapper} from '../facade/collection'; import {Map, MapWrapper} from '../facade/collection';
import {BaseException} from '../facade/exceptions'; import {BaseException} from '../facade/exceptions';
import {scheduleMicroTask} from '../facade/lang'; import {scheduleMicroTask} from '../facade/lang';
@ -40,18 +39,22 @@ export class Testability {
/** @internal */ /** @internal */
_watchAngularEvents(): void { _watchAngularEvents(): void {
ObservableWrapper.subscribe(this._ngZone.onUnstable, (_) => { this._ngZone.onUnstable.subscribe({
this._didWork = true; next: () => {
this._isZoneStable = false; this._didWork = true;
this._isZoneStable = false;
}
}); });
this._ngZone.runOutsideAngular(() => { this._ngZone.runOutsideAngular(() => {
ObservableWrapper.subscribe(this._ngZone.onStable, (_) => { this._ngZone.onStable.subscribe({
NgZone.assertNotInAngularZone(); next: () => {
scheduleMicroTask(() => { NgZone.assertNotInAngularZone();
this._isZoneStable = true; scheduleMicroTask(() => {
this._runCallbacksIfReady(); this._isZoneStable = true;
}); this._runCallbacksIfReady();
});
}
}); });
}); });
} }

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {APP_INITIALIZER, ApplicationInitStatus} from '../src/application_init'; import {APP_INITIALIZER, ApplicationInitStatus} from '../src/application_init';
import {PromiseCompleter, PromiseWrapper} from '../src/facade/async';
import {TestBed, async, inject, withModule} from '../testing'; import {TestBed, async, inject, withModule} from '../testing';
export function main() { export function main() {
@ -25,12 +24,12 @@ export function main() {
}); });
describe('with async initializers', () => { describe('with async initializers', () => {
let completer: PromiseCompleter<any>; let resolve: (result: any) => void;
let promise: Promise<any>;
beforeEach(() => { beforeEach(() => {
completer = PromiseWrapper.completer(); promise = new Promise((res) => { resolve = res; });
TestBed.configureTestingModule({ TestBed.configureTestingModule(
providers: [{provide: APP_INITIALIZER, multi: true, useValue: () => completer.promise}] {providers: [{provide: APP_INITIALIZER, multi: true, useValue: () => promise}]});
});
}); });
it('should updat the status once all async initializers are done', it('should updat the status once all async initializers are done',
@ -38,7 +37,7 @@ export function main() {
let completerResolver = false; let completerResolver = false;
setTimeout(() => { setTimeout(() => {
completerResolver = true; completerResolver = true;
completer.resolve(); resolve(null);
}); });
expect(status.done).toBe(false); expect(status.done).toBe(false);
@ -49,4 +48,4 @@ export function main() {
}))); })));
}); });
}); });
} }

View File

@ -15,7 +15,6 @@ import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {DOCUMENT} from '@angular/platform-browser/src/dom/dom_tokens'; import {DOCUMENT} from '@angular/platform-browser/src/dom/dom_tokens';
import {expect} from '@angular/platform-browser/testing/matchers'; import {expect} from '@angular/platform-browser/testing/matchers';
import {PromiseCompleter, PromiseWrapper} from '../src/facade/async';
import {ExceptionHandler} from '../src/facade/exception_handler'; import {ExceptionHandler} from '../src/facade/exception_handler';
import {BaseException} from '../src/facade/exceptions'; import {BaseException} from '../src/facade/exceptions';
import {ConcreteType} from '../src/facade/lang'; import {ConcreteType} from '../src/facade/lang';
@ -143,11 +142,9 @@ export function main() {
it('should throw if an APP_INITIIALIZER is not yet resolved', it('should throw if an APP_INITIIALIZER is not yet resolved',
withModule( withModule(
{ {
providers: [{ providers: [
provide: APP_INITIALIZER, {provide: APP_INITIALIZER, useValue: () => new Promise(() => {}), multi: true}
useValue: () => PromiseWrapper.completer().promise, ]
multi: true
}]
}, },
inject([ApplicationRef], (ref: ApplicationRef_) => { inject([ApplicationRef], (ref: ApplicationRef_) => {
expect(() => ref.bootstrap(SomeComponent)) expect(() => ref.bootstrap(SomeComponent))
@ -164,16 +161,17 @@ export function main() {
inject([PlatformRef], (_platform: PlatformRef) => { defaultPlatform = _platform; })); inject([PlatformRef], (_platform: PlatformRef) => { defaultPlatform = _platform; }));
it('should wait for asynchronous app initializers', async(() => { it('should wait for asynchronous app initializers', async(() => {
let completer: PromiseCompleter<any> = PromiseWrapper.completer(); let resolve: (result: any) => void;
let promise: Promise<any> = new Promise((res) => { resolve = res; });
var initializerDone = false; var initializerDone = false;
setTimeout(() => { setTimeout(() => {
completer.resolve(true); resolve(true);
initializerDone = true; initializerDone = true;
}, 1); }, 1);
defaultPlatform defaultPlatform
.bootstrapModule(createModule( .bootstrapModule(
[{provide: APP_INITIALIZER, useValue: () => completer.promise, multi: true}])) createModule([{provide: APP_INITIALIZER, useValue: () => promise, multi: true}]))
.then(_ => { expect(initializerDone).toBe(true); }); .then(_ => { expect(initializerDone).toBe(true); });
})); }));
@ -250,17 +248,18 @@ export function main() {
beforeEach( beforeEach(
inject([PlatformRef], (_platform: PlatformRef) => { defaultPlatform = _platform; })); inject([PlatformRef], (_platform: PlatformRef) => { defaultPlatform = _platform; }));
it('should wait for asynchronous app initializers', async(() => { it('should wait for asynchronous app initializers', async(() => {
let completer: PromiseCompleter<any> = PromiseWrapper.completer(); let resolve: (result: any) => void;
let promise: Promise<any> = new Promise((res) => { resolve = res; });
var initializerDone = false; var initializerDone = false;
setTimeout(() => { setTimeout(() => {
completer.resolve(true); resolve(true);
initializerDone = true; initializerDone = true;
}, 1); }, 1);
const compilerFactory: CompilerFactory = const compilerFactory: CompilerFactory =
defaultPlatform.injector.get(CompilerFactory, null); defaultPlatform.injector.get(CompilerFactory, null);
const moduleFactory = compilerFactory.createCompiler().compileModuleSync(createModule( const moduleFactory = compilerFactory.createCompiler().compileModuleSync(
[{provide: APP_INITIALIZER, useValue: () => completer.promise, multi: true}])); createModule([{provide: APP_INITIALIZER, useValue: () => promise, multi: true}]));
defaultPlatform.bootstrapModuleFactory(moduleFactory).then(_ => { defaultPlatform.bootstrapModuleFactory(moduleFactory).then(_ => {
expect(initializerDone).toBe(true); expect(initializerDone).toBe(true);
}); });

View File

@ -6,20 +6,17 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal'; import {NgFor, NgIf} from '@angular/common';
import {expect} from '@angular/platform-browser/testing/matchers'; import {Injectable} from '@angular/core';
import {Component, Directive, Input} from '@angular/core/src/metadata';
import {TestComponentBuilder} from '@angular/core/testing'; import {TestComponentBuilder} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {By} from '@angular/platform-browser/src/dom/debug/by';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {expect} from '@angular/platform-browser/testing/matchers';
import {EventEmitter} from '../../src/facade/async'; import {EventEmitter} from '../../src/facade/async';
import {Injectable} from '@angular/core';
import {NgFor, NgIf} from '@angular/common';
import {By} from '@angular/platform-browser/src/dom/debug/by';
import {Directive, Component, Input} from '@angular/core/src/metadata';
@Injectable() @Injectable()
class Logger { class Logger {
logs: string[]; logs: string[];

View File

@ -6,9 +6,8 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {bind, provide} from '@angular/core'; import {bind, provide} from '@angular/core';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
export function main() { export function main() {
describe('provider', () => { describe('provider', () => {

View File

@ -6,8 +6,9 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {forwardRef, resolveForwardRef} from '@angular/core/src/di'; import {forwardRef, resolveForwardRef} from '@angular/core/src/di';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {Type} from '../../src/facade/lang'; import {Type} from '../../src/facade/lang';
export function main() { export function main() {

View File

@ -6,16 +6,15 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {Inject, InjectMetadata, Injectable, Injector, Optional, ReflectiveInjector, ReflectiveKey, SelfMetadata, forwardRef} from '@angular/core';
import {DependencyMetadata} from '@angular/core/src/di/metadata';
import {ReflectiveInjectorDynamicStrategy, ReflectiveInjectorInlineStrategy, ReflectiveInjector_, ReflectiveProtoInjector} from '@angular/core/src/di/reflective_injector';
import {ResolvedReflectiveProvider_} from '@angular/core/src/di/reflective_provider';
import {expect} from '@angular/platform-browser/testing/matchers'; import {expect} from '@angular/platform-browser/testing/matchers';
import {BaseException} from '../../src/facade/exceptions'; import {BaseException} from '../../src/facade/exceptions';
import {isBlank, isPresent, stringify} from '../../src/facade/lang'; import {isBlank, isPresent, stringify} from '../../src/facade/lang';
import {ReflectiveKey, ReflectiveInjector, Injector, forwardRef, Injectable, InjectMetadata, SelfMetadata, Optional, Inject,} from '@angular/core';
import {ReflectiveInjector_, ReflectiveInjectorInlineStrategy, ReflectiveInjectorDynamicStrategy, ReflectiveProtoInjector} from '@angular/core/src/di/reflective_injector';
import {DependencyMetadata} from '@angular/core/src/di/metadata';
import {ResolvedReflectiveProvider_} from '@angular/core/src/di/reflective_provider';
class CustomDependencyMetadata extends DependencyMetadata {} class CustomDependencyMetadata extends DependencyMetadata {}
class Engine {} class Engine {}

View File

@ -6,8 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit, beforeEachProviders,} from '@angular/core/testing/testing_internal'; import {beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {el, stringifyElement} from '@angular/platform-browser/testing/browser_util'; import {el, stringifyElement} from '@angular/platform-browser/testing/browser_util';

View File

@ -6,12 +6,14 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {discardPeriodicTasks, fakeAsync, flushMicrotasks, tick} from '@angular/core/testing';
import {Log, beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {Log, beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing/matchers'; import {expect} from '@angular/platform-browser/testing/matchers';
import {fakeAsync, flushMicrotasks, tick, discardPeriodicTasks,} from '@angular/core/testing';
import {TimerWrapper, PromiseWrapper} from '../../router-deprecated/src/facade/async';
import {BaseException} from '../../router-deprecated/src/facade/exceptions';
import {Parser} from '../../compiler/src/expression_parser/parser'; import {Parser} from '../../compiler/src/expression_parser/parser';
import {BaseException} from '../../router-deprecated/src/facade/exceptions';
const resolvedPromise = Promise.resolve(null);
export function main() { export function main() {
describe('fake async', () => { describe('fake async', () => {
@ -42,7 +44,7 @@ export function main() {
it('should flush microtasks before returning', () => { it('should flush microtasks before returning', () => {
var thenRan = false; var thenRan = false;
fakeAsync(() => { PromiseWrapper.resolve(null).then(_ => { thenRan = true; }); })(); fakeAsync(() => { resolvedPromise.then(_ => { thenRan = true; }); })();
expect(thenRan).toEqual(true); expect(thenRan).toEqual(true);
}); });
@ -54,7 +56,7 @@ export function main() {
describe('Promise', () => { describe('Promise', () => {
it('should run asynchronous code', fakeAsync(() => { it('should run asynchronous code', fakeAsync(() => {
var thenRan = false; var thenRan = false;
PromiseWrapper.resolve(null).then((_) => { thenRan = true; }); resolvedPromise.then((_) => { thenRan = true; });
expect(thenRan).toEqual(false); expect(thenRan).toEqual(false);
@ -65,7 +67,7 @@ export function main() {
it('should run chained thens', fakeAsync(() => { it('should run chained thens', fakeAsync(() => {
var log = new Log(); var log = new Log();
PromiseWrapper.resolve(null).then((_) => log.add(1)).then((_) => log.add(2)); resolvedPromise.then((_) => log.add(1)).then((_) => log.add(2));
expect(log.result()).toEqual(''); expect(log.result()).toEqual('');
@ -76,9 +78,9 @@ export function main() {
it('should run Promise created in Promise', fakeAsync(() => { it('should run Promise created in Promise', fakeAsync(() => {
var log = new Log(); var log = new Log();
PromiseWrapper.resolve(null).then((_) => { resolvedPromise.then((_) => {
log.add(1); log.add(1);
PromiseWrapper.resolve(null).then((_) => log.add(2)); resolvedPromise.then((_) => log.add(2));
}); });
expect(log.result()).toEqual(''); expect(log.result()).toEqual('');
@ -90,7 +92,7 @@ export function main() {
it('should complain if the test throws an exception during async calls', () => { it('should complain if the test throws an exception during async calls', () => {
expect(() => { expect(() => {
fakeAsync(() => { fakeAsync(() => {
PromiseWrapper.resolve(null).then((_) => { throw new BaseException('async'); }); resolvedPromise.then((_) => { throw new BaseException('async'); });
flushMicrotasks(); flushMicrotasks();
})(); })();
}).toThrowError('Uncaught (in promise): async'); }).toThrowError('Uncaught (in promise): async');
@ -107,7 +109,7 @@ export function main() {
describe('timers', () => { describe('timers', () => {
it('should run queued zero duration timer on zero tick', fakeAsync(() => { it('should run queued zero duration timer on zero tick', fakeAsync(() => {
var ran = false; var ran = false;
TimerWrapper.setTimeout(() => { ran = true; }, 0); setTimeout(() => { ran = true; }, 0);
expect(ran).toEqual(false); expect(ran).toEqual(false);
@ -118,7 +120,7 @@ export function main() {
it('should run queued timer after sufficient clock ticks', fakeAsync(() => { it('should run queued timer after sufficient clock ticks', fakeAsync(() => {
var ran = false; var ran = false;
TimerWrapper.setTimeout(() => { ran = true; }, 10); setTimeout(() => { ran = true; }, 10);
tick(6); tick(6);
expect(ran).toEqual(false); expect(ran).toEqual(false);
@ -129,7 +131,7 @@ export function main() {
it('should run queued timer only once', fakeAsync(() => { it('should run queued timer only once', fakeAsync(() => {
var cycles = 0; var cycles = 0;
TimerWrapper.setTimeout(() => { cycles++; }, 10); setTimeout(() => { cycles++; }, 10);
tick(10); tick(10);
expect(cycles).toEqual(1); expect(cycles).toEqual(1);
@ -143,8 +145,8 @@ export function main() {
it('should not run cancelled timer', fakeAsync(() => { it('should not run cancelled timer', fakeAsync(() => {
var ran = false; var ran = false;
var id = TimerWrapper.setTimeout(() => { ran = true; }, 10); var id = setTimeout(() => { ran = true; }, 10);
TimerWrapper.clearTimeout(id); clearTimeout(id);
tick(10); tick(10);
expect(ran).toEqual(false); expect(ran).toEqual(false);
@ -152,19 +154,19 @@ export function main() {
it('should throw an error on dangling timers', () => { it('should throw an error on dangling timers', () => {
expect(() => { expect(() => {
fakeAsync(() => { TimerWrapper.setTimeout(() => {}, 10); })(); fakeAsync(() => { setTimeout(() => {}, 10); })();
}).toThrowError('1 timer(s) still in the queue.'); }).toThrowError('1 timer(s) still in the queue.');
}); });
it('should throw an error on dangling periodic timers', () => { it('should throw an error on dangling periodic timers', () => {
expect(() => { expect(() => {
fakeAsync(() => { TimerWrapper.setInterval(() => {}, 10); })(); fakeAsync(() => { setInterval(() => {}, 10); })();
}).toThrowError('1 periodic timer(s) still in the queue.'); }).toThrowError('1 periodic timer(s) still in the queue.');
}); });
it('should run periodic timers', fakeAsync(() => { it('should run periodic timers', fakeAsync(() => {
var cycles = 0; var cycles = 0;
var id = TimerWrapper.setInterval(() => { cycles++; }, 10); var id = setInterval(() => { cycles++; }, 10);
tick(10); tick(10);
expect(cycles).toEqual(1); expect(cycles).toEqual(1);
@ -174,14 +176,13 @@ export function main() {
tick(10); tick(10);
expect(cycles).toEqual(3); expect(cycles).toEqual(3);
clearInterval(id);
TimerWrapper.clearInterval(id);
})); }));
it('should not run cancelled periodic timer', fakeAsync(() => { it('should not run cancelled periodic timer', fakeAsync(() => {
var ran = false; var ran = false;
var id = TimerWrapper.setInterval(() => { ran = true; }, 10); var id = setInterval(() => { ran = true; }, 10);
TimerWrapper.clearInterval(id); clearInterval(id);
tick(10); tick(10);
expect(ran).toEqual(false); expect(ran).toEqual(false);
@ -191,9 +192,9 @@ export function main() {
var cycles = 0; var cycles = 0;
var id: any /** TODO #9100 */; var id: any /** TODO #9100 */;
id = TimerWrapper.setInterval(() => { id = setInterval(() => {
cycles++; cycles++;
TimerWrapper.clearInterval(id); clearInterval(id);
}, 10); }, 10);
tick(10); tick(10);
@ -205,7 +206,7 @@ export function main() {
it('should clear periodic timers', fakeAsync(() => { it('should clear periodic timers', fakeAsync(() => {
var cycles = 0; var cycles = 0;
var id = TimerWrapper.setInterval(() => { cycles++; }, 10); var id = setInterval(() => { cycles++; }, 10);
tick(10); tick(10);
expect(cycles).toEqual(1); expect(cycles).toEqual(1);
@ -224,33 +225,32 @@ export function main() {
it('should process microtasks before timers', fakeAsync(() => { it('should process microtasks before timers', fakeAsync(() => {
var log = new Log(); var log = new Log();
PromiseWrapper.resolve(null).then((_) => log.add('microtask')); resolvedPromise.then((_) => log.add('microtask'));
TimerWrapper.setTimeout(() => log.add('timer'), 9); setTimeout(() => log.add('timer'), 9);
var id = TimerWrapper.setInterval(() => log.add('periodic timer'), 10); var id = setInterval(() => log.add('periodic timer'), 10);
expect(log.result()).toEqual(''); expect(log.result()).toEqual('');
tick(10); tick(10);
expect(log.result()).toEqual('microtask; timer; periodic timer'); expect(log.result()).toEqual('microtask; timer; periodic timer');
clearInterval(id);
TimerWrapper.clearInterval(id);
})); }));
it('should process micro-tasks created in timers before next timers', fakeAsync(() => { it('should process micro-tasks created in timers before next timers', fakeAsync(() => {
var log = new Log(); var log = new Log();
PromiseWrapper.resolve(null).then((_) => log.add('microtask')); resolvedPromise.then((_) => log.add('microtask'));
TimerWrapper.setTimeout(() => { setTimeout(() => {
log.add('timer'); log.add('timer');
PromiseWrapper.resolve(null).then((_) => log.add('t microtask')); resolvedPromise.then((_) => log.add('t microtask'));
}, 9); }, 9);
var id = TimerWrapper.setInterval(() => { var id = setInterval(() => {
log.add('periodic timer'); log.add('periodic timer');
PromiseWrapper.resolve(null).then((_) => log.add('pt microtask')); resolvedPromise.then((_) => log.add('pt microtask'));
}, 10); }, 10);
tick(10); tick(10);
@ -261,8 +261,7 @@ export function main() {
expect(log.result()) expect(log.result())
.toEqual( .toEqual(
'microtask; timer; t microtask; periodic timer; pt microtask; periodic timer; pt microtask'); 'microtask; timer; t microtask; periodic timer; pt microtask; periodic timer; pt microtask');
clearInterval(id);
TimerWrapper.clearInterval(id);
})); }));
}); });

View File

@ -6,19 +6,19 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal'; import {DebugElement, Injector, Type, ViewChild, ViewContainerRef} from '@angular/core';
import {expect} from '@angular/platform-browser/testing/matchers';
import {ComponentFixture, TestComponentBuilder} from '@angular/core/testing';
import {Predicate} from '../../src/facade/collection';
import {Injector, DebugElement, Type, ViewContainerRef, ViewChild} from '@angular/core';
import {Component} from '@angular/core/src/metadata';
import {DynamicComponentLoader} from '@angular/core/src/linker/dynamic_component_loader'; import {DynamicComponentLoader} from '@angular/core/src/linker/dynamic_component_loader';
import {ElementRef} from '@angular/core/src/linker/element_ref'; import {ElementRef} from '@angular/core/src/linker/element_ref';
import {DOCUMENT} from '@angular/platform-browser/src/dom/dom_tokens'; import {Component} from '@angular/core/src/metadata';
import {ComponentFixture, TestComponentBuilder} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {BaseException} from '../../src/facade/exceptions'; import {DOCUMENT} from '@angular/platform-browser/src/dom/dom_tokens';
import {PromiseWrapper} from '../../src/facade/promise';
import {el} from '@angular/platform-browser/testing/browser_util'; import {el} from '@angular/platform-browser/testing/browser_util';
import {expect} from '@angular/platform-browser/testing/matchers';
import {Predicate} from '../../src/facade/collection';
import {BaseException} from '../../src/facade/exceptions';
export function main() { export function main() {
describe('DynamicComponentLoader', function() { describe('DynamicComponentLoader', function() {
@ -98,10 +98,11 @@ export function main() {
async: AsyncTestCompleter) => { async: AsyncTestCompleter) => {
tcb.createAsync(MyComp3).then((tc: ComponentFixture<any>) => { tcb.createAsync(MyComp3).then((tc: ComponentFixture<any>) => {
tc.detectChanges(); tc.detectChanges();
PromiseWrapper.catchError(
loader.loadNextToLocation( loader
DynamicallyLoadedThrows, tc.componentInstance.viewContainerRef), .loadNextToLocation(
(error) => { DynamicallyLoadedThrows, tc.componentInstance.viewContainerRef)
.catch((error) => {
expect(error.message).toContain('ThrownInConstructor'); expect(error.message).toContain('ThrownInConstructor');
expect(() => tc.detectChanges()).not.toThrow(); expect(() => tc.detectChanges()).not.toThrow();
async.done(); async.done();

View File

@ -6,11 +6,12 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, expect, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal'; import {ANALYZE_FOR_ENTRY_COMPONENTS, Component, ComponentFactoryResolver, NoComponentFactoryError, ViewMetadata, forwardRef} from '@angular/core';
import {TestComponentBuilder, TestBed} from '@angular/core/testing'; import {TestBed, TestComponentBuilder} from '@angular/core/testing';
import {Component, ComponentFactoryResolver, NoComponentFactoryError, forwardRef, ANALYZE_FOR_ENTRY_COMPONENTS, ViewMetadata} from '@angular/core'; import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {stringify} from '../../src/facade/lang';
import {Console} from '../../src/console'; import {Console} from '../../src/console';
import {stringify} from '../../src/facade/lang';
export function main() { export function main() {
describe('jit', () => { declareTests({useJit: true}); }); describe('jit', () => { declareTests({useJit: true}); });

View File

@ -6,35 +6,27 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal'; import {AsyncPipe, NgFor, NgIf} from '@angular/common';
import {expect} from '@angular/platform-browser/testing/matchers';
import {fakeAsync, tick, ComponentFixture, TestBed, TestComponentBuilder} from '@angular/core/testing';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {isPresent, stringify, isBlank,} from '../../src/facade/lang';
import {BaseException} from '../../src/facade/exceptions';
import {PromiseWrapper, EventEmitter, ObservableWrapper, PromiseCompleter,} from '../../src/facade/async';
import {Injector, Injectable, forwardRef, OpaqueToken, Inject, Host, SkipSelf, SkipSelfMetadata, OnDestroy, ReflectiveInjector, Compiler} from '@angular/core';
import {NgIf, NgFor, AsyncPipe} from '@angular/common';
import {PipeTransform, ChangeDetectorRef, ChangeDetectionStrategy} from '@angular/core/src/change_detection/change_detection';
import {CompilerConfig} from '@angular/compiler'; import {CompilerConfig} from '@angular/compiler';
import {Compiler, Host, Inject, Injectable, Injector, OnDestroy, OpaqueToken, ReflectiveInjector, SkipSelf, SkipSelfMetadata, forwardRef} from '@angular/core';
import {Directive, Component, ViewMetadata, Attribute, Query, Pipe, Input, Output, HostBinding, HostListener} from '@angular/core/src/metadata'; import {ChangeDetectionStrategy, ChangeDetectorRef, PipeTransform} from '@angular/core/src/change_detection/change_detection';
import {QueryList} from '@angular/core/src/linker/query_list';
import {ViewContainerRef} from '@angular/core/src/linker/view_container_ref';
import {EmbeddedViewRef} from '@angular/core/src/linker/view_ref';
import {ComponentResolver} from '@angular/core/src/linker/component_resolver'; import {ComponentResolver} from '@angular/core/src/linker/component_resolver';
import {ElementRef} from '@angular/core/src/linker/element_ref'; import {ElementRef} from '@angular/core/src/linker/element_ref';
import {QueryList} from '@angular/core/src/linker/query_list';
import {TemplateRef, TemplateRef_} from '@angular/core/src/linker/template_ref'; import {TemplateRef, TemplateRef_} from '@angular/core/src/linker/template_ref';
import {ViewContainerRef} from '@angular/core/src/linker/view_container_ref';
import {EmbeddedViewRef} from '@angular/core/src/linker/view_ref';
import {Attribute, Component, Directive, HostBinding, HostListener, Input, Output, Pipe, Query, ViewMetadata} from '@angular/core/src/metadata';
import {Renderer} from '@angular/core/src/render'; import {Renderer} from '@angular/core/src/render';
import {el, dispatchEvent} from '@angular/platform-browser/testing/browser_util'; import {ComponentFixture, TestBed, TestComponentBuilder, fakeAsync, tick} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {dispatchEvent, el} from '@angular/platform-browser/testing/browser_util';
import {expect} from '@angular/platform-browser/testing/matchers';
import {EventEmitter} from '../../src/facade/async';
import {BaseException} from '../../src/facade/exceptions';
import {isBlank, isPresent, stringify} from '../../src/facade/lang';
const ANCHOR_ELEMENT = new OpaqueToken('AnchorElement'); const ANCHOR_ELEMENT = new OpaqueToken('AnchorElement');
@ -991,15 +983,17 @@ function declareTests({useJit}: {useJit: boolean}) {
expect(listener.msg).toEqual(''); expect(listener.msg).toEqual('');
var eventCount = 0; var eventCount = 0;
ObservableWrapper.subscribe(emitter.event, (_) => { emitter.event.subscribe({
eventCount++; next: () => {
if (eventCount === 1) { eventCount++;
expect(listener.msg).toEqual('fired !'); if (eventCount === 1) {
fixture.destroy(); expect(listener.msg).toEqual('fired !');
emitter.fireEvent('fired again !'); fixture.destroy();
} else { emitter.fireEvent('fired again !');
expect(listener.msg).toEqual('fired !'); } else {
async.done(); expect(listener.msg).toEqual('fired !');
async.done();
}
} }
}); });
@ -1029,10 +1023,12 @@ function declareTests({useJit}: {useJit: boolean}) {
myComp.ctxProp = ''; myComp.ctxProp = '';
expect(listener.msg).toEqual(''); expect(listener.msg).toEqual('');
ObservableWrapper.subscribe(emitter.event, (_) => { emitter.event.subscribe({
expect(listener.msg).toEqual('fired !'); next: () => {
expect(myComp.ctxProp).toEqual('fired !'); expect(listener.msg).toEqual('fired !');
async.done(); expect(myComp.ctxProp).toEqual('fired !');
async.done();
}
}); });
emitter.fireEvent('fired !'); emitter.fireEvent('fired !');
@ -1057,9 +1053,11 @@ function declareTests({useJit}: {useJit: boolean}) {
expect(dir.control).toEqual('one'); expect(dir.control).toEqual('one');
ObservableWrapper.subscribe(dir.controlChange, (_) => { dir.controlChange.subscribe({
expect(fixture.debugElement.componentInstance.ctxProp).toEqual('two'); next: () => {
async.done(); expect(fixture.debugElement.componentInstance.ctxProp).toEqual('two');
async.done();
}
}); });
dir.triggerChange('two'); dir.triggerChange('two');
@ -1551,7 +1549,7 @@ function declareTests({useJit}: {useJit: boolean}) {
template: `<directive-throwing-error></directive-throwing-error>` template: `<directive-throwing-error></directive-throwing-error>`
})); }));
PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => { tcb.createAsync(MyComp).catch((e) => {
var c = e.context; var c = e.context;
expect(getDOM().nodeName(c.componentRenderElement).toUpperCase()).toEqual('DIV'); expect(getDOM().nodeName(c.componentRenderElement).toUpperCase()).toEqual('DIV');
expect((<Injector>c.injector).get).toBeTruthy(); expect((<Injector>c.injector).get).toBeTruthy();
@ -1741,7 +1739,7 @@ function declareTests({useJit}: {useJit: boolean}) {
tcb = tcb.overrideView( tcb = tcb.overrideView(
MyComp, new ViewMetadata({template: '<div unknown="{{ctxProp}}"></div>'})); MyComp, new ViewMetadata({template: '<div unknown="{{ctxProp}}"></div>'}));
PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => { tcb.createAsync(MyComp).catch((e) => {
expect(e.message).toEqual( expect(e.message).toEqual(
`Template parse errors:\nCan't bind to 'unknown' since it isn't a known property of 'div'. ("<div [ERROR ->]unknown="{{ctxProp}}"></div>"): MyComp@0:5`); `Template parse errors:\nCan't bind to 'unknown' since it isn't a known property of 'div'. ("<div [ERROR ->]unknown="{{ctxProp}}"></div>"): MyComp@0:5`);
async.done(); async.done();
@ -2211,20 +2209,17 @@ class PushCmpWithHostEvent {
}) })
class PushCmpWithAsyncPipe { class PushCmpWithAsyncPipe {
numberOfChecks: number = 0; numberOfChecks: number = 0;
resolve: (result: any) => void;
promise: Promise<any>; promise: Promise<any>;
completer: PromiseCompleter<any>;
constructor() { constructor() {
this.completer = PromiseWrapper.completer(); this.promise = new Promise((resolve) => { this.resolve = resolve; });
this.promise = this.completer.promise;
} }
get field() { get field() {
this.numberOfChecks++; this.numberOfChecks++;
return this.promise; return this.promise;
} }
resolve(value: any) { this.completer.resolve(value); }
} }
@Component({selector: 'my-comp', directives: []}) @Component({selector: 'my-comp', directives: []})
@ -2324,7 +2319,7 @@ class DirectiveEmittingEvent {
this.event = new EventEmitter(); this.event = new EventEmitter();
} }
fireEvent(msg: string) { ObservableWrapper.callEmit(this.event, msg); } fireEvent(msg: string) { this.event.emit(msg); }
} }
@Directive({selector: '[update-host-attributes]', host: {'role': 'button'}}) @Directive({selector: '[update-host-attributes]', host: {'role': 'button'}})
@ -2466,7 +2461,7 @@ class DirectiveWithTwoWayBinding {
controlChange = new EventEmitter(); controlChange = new EventEmitter();
control: any = null; control: any = null;
triggerChange(value: any) { ObservableWrapper.callEmit(this.controlChange, value); } triggerChange(value: any) { this.controlChange.emit(value); }
} }
@Injectable() @Injectable()
@ -2661,7 +2656,7 @@ class DirectiveWithPropDecorators {
@HostListener('click', ['$event.target']) @HostListener('click', ['$event.target'])
onClick(target: any) { this.target = target; } onClick(target: any) { this.target = target; }
fireEvent(msg: any) { ObservableWrapper.callEmit(this.event, msg); } fireEvent(msg: any) { this.event.emit(msg); }
} }
@Component({selector: 'some-cmp'}) @Component({selector: 'some-cmp'})

View File

@ -6,12 +6,12 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing/matchers';
import {TestBed, TestComponentBuilder} from '@angular/core/testing';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {Component, Directive, AfterContentInit, AfterViewInit, QueryList, ContentChildren, ViewChildren, Input} from '@angular/core';
import {NgIf} from '@angular/common'; import {NgIf} from '@angular/common';
import {AfterContentInit, AfterViewInit, Component, ContentChildren, Directive, Input, QueryList, ViewChildren} from '@angular/core';
import {TestBed, TestComponentBuilder} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {expect} from '@angular/platform-browser/testing/matchers';
export function main() { export function main() {
describe('jit', () => { declareTests({useJit: true}); }); describe('jit', () => { declareTests({useJit: true}); });

View File

@ -6,15 +6,13 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal'; import {Component, Directive, ElementRef, TemplateRef, ViewContainerRef, ViewEncapsulation, ViewMetadata, forwardRef} from '@angular/core';
import {expect} from '@angular/platform-browser/testing/matchers';
import {ComponentFixture, TestComponentBuilder} from '@angular/core/testing';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {forwardRef, Component, Directive, ElementRef, TemplateRef, ViewContainerRef, ViewEncapsulation, ViewMetadata} from '@angular/core';
import {By,} from '@angular/platform-browser/src/dom/debug/by';
import {getAllDebugNodes} from '@angular/core/src/debug/debug_node'; import {getAllDebugNodes} from '@angular/core/src/debug/debug_node';
import {ComponentFixture, TestComponentBuilder} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {By} from '@angular/platform-browser/src/dom/debug/by';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {expect} from '@angular/platform-browser/testing/matchers';
export function main() { export function main() {
describe('projection', () => { describe('projection', () => {

View File

@ -6,15 +6,13 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEach, ddescribe, describe, iit, inject, it, xit,} from '@angular/core/testing/testing_internal'; import {NgFor, NgIf} from '@angular/common';
import {expect} from '@angular/platform-browser/testing/matchers'; import {AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, Component, ContentChild, ContentChildren, Directive, Query, QueryList, TemplateRef, ViewChild, ViewChildren, ViewContainerRef, ViewQuery, asNativeElements} from '@angular/core';
import {TestComponentBuilder} from '@angular/core/testing'; import {TestComponentBuilder} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing/matchers';
import {isPresent, stringify} from '../../src/facade/lang'; import {isPresent, stringify} from '../../src/facade/lang';
import {ObservableWrapper} from '../../src/facade/async';
import {asNativeElements, ViewContainerRef, Component, Directive, TemplateRef, Query, QueryList, ViewQuery, ContentChildren, ViewChildren, ContentChild, ViewChild, AfterContentInit, AfterViewInit, AfterContentChecked, AfterViewChecked} from '@angular/core';
import {NgIf, NgFor} from '@angular/common';
export function main() { export function main() {
describe('Query API', () => { describe('Query API', () => {
@ -418,10 +416,12 @@ export function main() {
var q = view.debugElement.children[0].references['q']; var q = view.debugElement.children[0].references['q'];
view.detectChanges(); view.detectChanges();
ObservableWrapper.subscribe(q.query.changes, (_) => { q.query.changes.subscribe({
expect(q.query.first.text).toEqual('1'); next: () => {
expect(q.query.last.text).toEqual('2'); expect(q.query.first.text).toEqual('1');
async.done(); expect(q.query.last.text).toEqual('2');
async.done();
}
}); });
view.debugElement.componentInstance.shouldShow = true; view.debugElement.componentInstance.shouldShow = true;
@ -445,10 +445,12 @@ export function main() {
var firedQ2 = false; var firedQ2 = false;
ObservableWrapper.subscribe(q2.query.changes, (_) => { firedQ2 = true; }); q2.query.changes.subscribe({next: () => { firedQ2 = true; }});
ObservableWrapper.subscribe(q1.query.changes, (_) => { q1.query.changes.subscribe({
expect(firedQ2).toBe(true); next: () => {
async.done(); expect(firedQ2).toBe(true);
async.done();
}
}); });
view.detectChanges(); view.detectChanges();

View File

@ -6,13 +6,13 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {describe, it, expect, beforeEach, ddescribe, iit, xit,} from '@angular/core/testing/testing_internal'; import {QueryList} from '@angular/core/src/linker/query_list';
import {fakeAsync, tick,} from '@angular/core/testing'; import {fakeAsync, tick} from '@angular/core/testing';
import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {iterateListLike} from '../../src/facade/collection'; import {iterateListLike} from '../../src/facade/collection';
import {StringWrapper} from '../../src/facade/lang'; import {StringWrapper} from '../../src/facade/lang';
import {ObservableWrapper} from '../../src/facade/async';
import {QueryList} from '@angular/core/src/linker/query_list';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
interface _JsQueryList { interface _JsQueryList {
filter(c: any): any; filter(c: any): any;
@ -124,7 +124,7 @@ export function main() {
describe('simple observable interface', () => { describe('simple observable interface', () => {
it('should fire callbacks on change', fakeAsync(() => { it('should fire callbacks on change', fakeAsync(() => {
var fires = 0; var fires = 0;
ObservableWrapper.subscribe(queryList.changes, (_) => { fires += 1; }); queryList.changes.subscribe({next: (_) => { fires += 1; }});
queryList.notifyOnChanges(); queryList.notifyOnChanges();
tick(); tick();
@ -139,7 +139,7 @@ export function main() {
it('should provides query list as an argument', fakeAsync(() => { it('should provides query list as an argument', fakeAsync(() => {
var recorded: any /** TODO #9100 */; var recorded: any /** TODO #9100 */;
ObservableWrapper.subscribe(queryList.changes, (v: any) => { recorded = v; }); queryList.changes.subscribe({next: (v: any) => { recorded = v; }});
queryList.reset(['one']); queryList.reset(['one']);
queryList.notifyOnChanges(); queryList.notifyOnChanges();

View File

@ -6,12 +6,11 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal'; import {NgClass, NgIf} from '@angular/common';
import {expect} from '@angular/platform-browser/testing/matchers'; import {Component, Injector, OpaqueToken, Pipe, PipeTransform, ViewMetadata, forwardRef} from '@angular/core';
import {TestBed, TestComponentBuilder} from '@angular/core/testing'; import {TestBed, TestComponentBuilder} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {Component, Pipe, PipeTransform, ViewMetadata, OpaqueToken, Injector, forwardRef} from '@angular/core'; import {expect} from '@angular/platform-browser/testing/matchers';
import {NgIf, NgClass} from '@angular/common';
export function main() { export function main() {
describe('jit', () => { declareTests({useJit: true}); }); describe('jit', () => { declareTests({useJit: true}); });

View File

@ -6,10 +6,10 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, ddescribe, describe, expect, inject, beforeEachProviders, beforeEach, afterEach, it,} from '@angular/core/testing/testing_internal';
import {TestBed, TestComponentBuilder} from '@angular/core/testing';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {Component} from '@angular/core/src/metadata'; import {Component} from '@angular/core/src/metadata';
import {TestBed, TestComponentBuilder} from '@angular/core/testing';
import {AsyncTestCompleter, afterEach, beforeEach, beforeEachProviders, ddescribe, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {DomSanitizationService} from '@angular/platform-browser/src/security/dom_sanitization_service'; import {DomSanitizationService} from '@angular/platform-browser/src/security/dom_sanitization_service';

View File

@ -6,13 +6,14 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {describe, ddescribe, it, iit, xit, xdescribe, beforeEach, beforeEachProviders, inject,} from '@angular/core/testing/testing_internal'; import {NgFor, NgIf} from '@angular/common';
import {expect} from '@angular/platform-browser/testing/matchers'; import {Attribute, ChangeDetectionStrategy, ChangeDetectorRef, Component, DebugElement, Directive, ElementRef, Host, Inject, InjectMetadata, Input, Optional, Pipe, PipeTransform, Self, SkipSelfMetadata, TemplateRef, Type, ViewContainerRef, ViewMetadata, forwardRef, provide} from '@angular/core';
import {fakeAsync, flushMicrotasks, tick, ComponentFixture, TestComponentBuilder} from '@angular/core/testing'; import {ComponentFixture, TestComponentBuilder, fakeAsync, flushMicrotasks, tick} from '@angular/core/testing';
import {isBlank, ConcreteType} from '../../src/facade/lang'; import {beforeEach, beforeEachProviders, ddescribe, describe, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {Type, ViewContainerRef, TemplateRef, ElementRef, ChangeDetectorRef, ChangeDetectionStrategy, Directive, Component, DebugElement, forwardRef, Input, PipeTransform, Attribute, ViewMetadata, provide, Optional, Inject, Self, InjectMetadata, Pipe, Host, SkipSelfMetadata} from '@angular/core';
import {NgIf, NgFor} from '@angular/common';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {expect} from '@angular/platform-browser/testing/matchers';
import {ConcreteType, isBlank} from '../../src/facade/lang';
const ALL_DIRECTIVES = [ const ALL_DIRECTIVES = [
forwardRef(() => SimpleDirective), forwardRef(() => SimpleDirective),

View File

@ -6,10 +6,9 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {Component, Directive} from '@angular/core'; import {Component, Directive} from '@angular/core';
import {reflector} from '@angular/core/src/reflection/reflection'; import {reflector} from '@angular/core/src/reflection/reflection';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
export function main() { export function main() {
describe('es5 decorators', () => { describe('es5 decorators', () => {

View File

@ -6,10 +6,9 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal'; import {Component, Directive, ElementRef, Input, QueryList, ViewChild, ViewChildren, ViewMetadata} from '@angular/core';
import {TestComponentBuilder} from '@angular/core/testing'; import {TestComponentBuilder} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {Component, ViewMetadata, Input, Directive, ViewChild, ViewChildren, QueryList, ElementRef} from '@angular/core';
export function main() { export function main() {
describe('ViewChild', () => { describe('ViewChild', () => {

View File

@ -6,13 +6,14 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {describe, it, iit, ddescribe, expect, beforeEach,} from '@angular/core/testing/testing_internal';
import {OnInit} from '@angular/core'; import {OnInit} from '@angular/core';
import {Reflector, ReflectionInfo} from '@angular/core/src/reflection/reflection'; import {ReflectionInfo, Reflector} from '@angular/core/src/reflection/reflection';
import {ReflectionCapabilities} from '@angular/core/src/reflection/reflection_capabilities'; import {ReflectionCapabilities} from '@angular/core/src/reflection/reflection_capabilities';
import {ClassDecorator, ParamDecorator, PropDecorator, classDecorator, paramDecorator, propDecorator, HasGetterAndSetterDecorators} from './reflector_common'; import {beforeEach, ddescribe, describe, expect, iit, it} from '@angular/core/testing/testing_internal';
import {browserDetection} from '@angular/platform-browser/testing/browser_util'; import {browserDetection} from '@angular/platform-browser/testing/browser_util';
import {ClassDecorator, HasGetterAndSetterDecorators, ParamDecorator, PropDecorator, classDecorator, paramDecorator, propDecorator} from './reflector_common';
class AType { class AType {
value: any /** TODO #9100 */; value: any /** TODO #9100 */;

View File

@ -7,11 +7,13 @@
*/ */
import {Injectable} from '@angular/core/src/di'; import {Injectable} from '@angular/core/src/di';
import {AsyncTestCompleter, SpyObject, inject, describe, ddescribe, it, iit, xit, xdescribe, expect, beforeEach,} from '@angular/core/testing/testing_internal';
import {Testability} from '@angular/core/src/testability/testability'; import {Testability} from '@angular/core/src/testability/testability';
import {NgZone} from '@angular/core/src/zone/ng_zone'; import {NgZone} from '@angular/core/src/zone/ng_zone';
import {AsyncTestCompleter, SpyObject, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {EventEmitter} from '../../src/facade/async';
import {normalizeBlank, scheduleMicroTask} from '../../src/facade/lang'; import {normalizeBlank, scheduleMicroTask} from '../../src/facade/lang';
import {PromiseWrapper, EventEmitter, ObservableWrapper} from '../../src/facade/async';
// Schedules a microtasks (using a resolved promise .then()) // Schedules a microtasks (using a resolved promise .then())
function microTask(fn: Function): void { function microTask(fn: Function): void {
@ -38,9 +40,9 @@ class MockNgZone extends NgZone {
this._onStableStream = new EventEmitter(false); this._onStableStream = new EventEmitter(false);
} }
unstable(): void { ObservableWrapper.callEmit(this._onUnstableStream, null); } unstable(): void { this._onUnstableStream.emit(null); }
stable(): void { ObservableWrapper.callEmit(this._onStableStream, null); } stable(): void { this._onStableStream.emit(null); }
} }
export function main() { export function main() {

View File

@ -6,12 +6,12 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {makeDecorator, makeParamDecorator, Class} from '@angular/core/src/util/decorators';
import {global} from '../../src/facade/lang';
import {Inject} from '@angular/core'; import {Inject} from '@angular/core';
import {reflector} from '@angular/core/src/reflection/reflection'; import {reflector} from '@angular/core/src/reflection/reflection';
import {Class, makeDecorator, makeParamDecorator} from '@angular/core/src/util/decorators';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {global} from '../../src/facade/lang';
class TestAnnotation { class TestAnnotation {
constructor(public arg: any) {} constructor(public arg: any) {}

View File

@ -6,12 +6,10 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, Log, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit,} from '@angular/core/testing/testing_internal';
import {NgZone, NgZoneError} from '@angular/core/src/zone/ng_zone'; import {NgZone, NgZoneError} from '@angular/core/src/zone/ng_zone';
import {AsyncTestCompleter, Log, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {browserDetection} from '@angular/platform-browser/testing/browser_util'; import {browserDetection} from '@angular/platform-browser/testing/browser_util';
import {ObservableWrapper, PromiseCompleter, PromiseWrapper, TimerWrapper} from '../../src/facade/async';
import {BaseException} from '../../src/facade/exceptions'; import {BaseException} from '../../src/facade/exceptions';
import {isPresent, scheduleMicroTask} from '../../src/facade/lang'; import {isPresent, scheduleMicroTask} from '../../src/facade/lang';
@ -21,7 +19,7 @@ var testTimeout = browserDetection.isEdge ? 1200 : 500;
// Schedules a macrotask (using a timer) // Schedules a macrotask (using a timer)
function macroTask(fn: (...args: any[]) => void, timer = 1): void { function macroTask(fn: (...args: any[]) => void, timer = 1): void {
// adds longer timers for passing tests in IE and Edge // adds longer timers for passing tests in IE and Edge
TimerWrapper.setTimeout(fn, needsLongerTimers ? timer : 1); setTimeout(fn, needsLongerTimers ? timer : 1);
} }
var _log: Log; var _log: Log;
@ -29,23 +27,27 @@ var _errors: any[];
var _traces: any[]; var _traces: any[];
var _zone: NgZone; var _zone: NgZone;
const resolvedPromise = Promise.resolve(null);
function logOnError() { function logOnError() {
ObservableWrapper.subscribe(_zone.onError, (ngErr: NgZoneError) => { _zone.onError.subscribe({
_errors.push(ngErr.error); next: (ngErr: NgZoneError) => {
_traces.push(ngErr.stackTrace); _errors.push(ngErr.error);
_traces.push(ngErr.stackTrace);
}
}); });
} }
function logOnUnstable() { function logOnUnstable() {
ObservableWrapper.subscribe(_zone.onUnstable, _log.fn('onUnstable')); _zone.onUnstable.subscribe({next: _log.fn('onUnstable')});
} }
function logOnMicrotaskEmpty() { function logOnMicrotaskEmpty() {
ObservableWrapper.subscribe(_zone.onMicrotaskEmpty, _log.fn('onMicrotaskEmpty')); _zone.onMicrotaskEmpty.subscribe({next: _log.fn('onMicrotaskEmpty')});
} }
function logOnStable() { function logOnStable() {
ObservableWrapper.subscribe(_zone.onStable, _log.fn('onStable')); _zone.onStable.subscribe({next: _log.fn('onStable')});
} }
function runNgZoneNoLog(fn: () => any) { function runNgZoneNoLog(fn: () => any) {
@ -85,18 +87,19 @@ export function main() {
it('should produce long stack traces', it('should produce long stack traces',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
macroTask(() => { macroTask(() => {
var c: PromiseCompleter<any> = PromiseWrapper.completer(); let resolve: (result: any) => void;
let promise: Promise<any> = new Promise((res) => { resolve = res; });
_zone.run(() => { _zone.run(() => {
TimerWrapper.setTimeout(() => { setTimeout(() => {
TimerWrapper.setTimeout(() => { setTimeout(() => {
c.resolve(null); resolve(null);
throw new BaseException('ccc'); throw new BaseException('ccc');
}, 0); }, 0);
}, 0); }, 0);
}); });
c.promise.then((_) => { promise.then((_) => {
expect(_traces.length).toBe(1); expect(_traces.length).toBe(1);
expect(_traces[0].length).toBeGreaterThan(1); expect(_traces[0].length).toBeGreaterThan(1);
async.done(); async.done();
@ -107,18 +110,19 @@ export function main() {
it('should produce long stack traces (when using microtasks)', it('should produce long stack traces (when using microtasks)',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
macroTask(() => { macroTask(() => {
var c: PromiseCompleter<any> = PromiseWrapper.completer(); let resolve: (result: any) => void;
let promise: Promise<any> = new Promise((res) => { resolve = res; });
_zone.run(() => { _zone.run(() => {
scheduleMicroTask(() => { scheduleMicroTask(() => {
scheduleMicroTask(() => { scheduleMicroTask(() => {
c.resolve(null); resolve(null);
throw new BaseException('ddd'); throw new BaseException('ddd');
}); });
}); });
}); });
c.promise.then((_) => { promise.then((_) => {
expect(_traces.length).toBe(1); expect(_traces.length).toBe(1);
expect(_traces[0].length).toBeGreaterThan(1); expect(_traces[0].length).toBeGreaterThan(1);
async.done(); async.done();
@ -141,18 +145,19 @@ export function main() {
it('should disable long stack traces', it('should disable long stack traces',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
macroTask(() => { macroTask(() => {
var c: PromiseCompleter<any> = PromiseWrapper.completer(); let resolve: (result: any) => void;
let promise: Promise<any> = new Promise((res) => { resolve = res; });
_zone.run(() => { _zone.run(() => {
TimerWrapper.setTimeout(() => { setTimeout(() => {
TimerWrapper.setTimeout(() => { setTimeout(() => {
c.resolve(null); resolve(null);
throw new BaseException('ccc'); throw new BaseException('ccc');
}, 0); }, 0);
}, 0); }, 0);
}); });
c.promise.then((_) => { promise.then((_) => {
expect(_traces.length).toBe(1); expect(_traces.length).toBe(1);
if (isPresent(_traces[0])) { if (isPresent(_traces[0])) {
// some browsers don't have stack traces. // some browsers don't have stack traces.
@ -180,7 +185,7 @@ function commonTests() {
it('should be false', () => { expect(_zone.hasPendingMacrotasks).toBe(false); }); it('should be false', () => { expect(_zone.hasPendingMacrotasks).toBe(false); });
it('should be true', () => { it('should be true', () => {
runNgZoneNoLog(() => { TimerWrapper.setTimeout(() => {}, 0); }); runNgZoneNoLog(() => { setTimeout(() => {}, 0); });
expect(_zone.hasPendingMacrotasks).toBe(true); expect(_zone.hasPendingMacrotasks).toBe(true);
}); });
}); });
@ -194,7 +199,7 @@ function commonTests() {
}); });
it('should be true when timer is scheduled', () => { it('should be true when timer is scheduled', () => {
runNgZoneNoLog(() => { TimerWrapper.setTimeout(() => {}, 0); }); runNgZoneNoLog(() => { setTimeout(() => {}, 0); });
expect(_zone.hasPendingMacrotasks).toBe(true); expect(_zone.hasPendingMacrotasks).toBe(true);
}); });
}); });
@ -231,12 +236,14 @@ function commonTests() {
runNgZoneNoLog(() => macroTask(_log.fn('run'))); runNgZoneNoLog(() => macroTask(_log.fn('run')));
var times = 0; var times = 0;
ObservableWrapper.subscribe(_zone.onMicrotaskEmpty, (_) => { _zone.onMicrotaskEmpty.subscribe({
times++; next: () => {
_log.add(`onMicrotaskEmpty ${times}`); times++;
if (times < 2) { _log.add(`onMicrotaskEmpty ${times}`);
// Scheduling a microtask causes a second digest if (times < 2) {
runNgZoneNoLog(() => { scheduleMicroTask(() => {}); }); // Scheduling a microtask causes a second digest
runNgZoneNoLog(() => { scheduleMicroTask(() => {}); });
}
} }
}); });
@ -265,27 +272,33 @@ function commonTests() {
// then verifies that those microtasks do not cause additional digests. // then verifies that those microtasks do not cause additional digests.
var turnStart = false; var turnStart = false;
ObservableWrapper.subscribe(_zone.onUnstable, (_) => { _zone.onUnstable.subscribe({
if (turnStart) throw 'Should not call this more than once'; next: () => {
_log.add('onUnstable'); if (turnStart) throw 'Should not call this more than once';
scheduleMicroTask(() => {}); _log.add('onUnstable');
turnStart = true; scheduleMicroTask(() => {});
turnStart = true;
}
}); });
var turnDone = false; var turnDone = false;
ObservableWrapper.subscribe(_zone.onMicrotaskEmpty, (_) => { _zone.onMicrotaskEmpty.subscribe({
if (turnDone) throw 'Should not call this more than once'; next: () => {
_log.add('onMicrotaskEmpty'); if (turnDone) throw 'Should not call this more than once';
scheduleMicroTask(() => {}); _log.add('onMicrotaskEmpty');
turnDone = true; scheduleMicroTask(() => {});
turnDone = true;
}
}); });
var eventDone = false; var eventDone = false;
ObservableWrapper.subscribe(_zone.onStable, (_) => { _zone.onStable.subscribe({
if (eventDone) throw 'Should not call this more than once'; next: () => {
_log.add('onStable'); if (eventDone) throw 'Should not call this more than once';
scheduleMicroTask(() => {}); _log.add('onStable');
eventDone = true; scheduleMicroTask(() => {});
eventDone = true;
}
}); });
macroTask(() => { _zone.run(_log.fn('run')); }); macroTask(() => { _zone.run(_log.fn('run')); });
@ -303,11 +316,13 @@ function commonTests() {
// the only practical use-case to run a callback inside the zone is // the only practical use-case to run a callback inside the zone is
// change detection after "onMicrotaskEmpty". That's the only case tested. // change detection after "onMicrotaskEmpty". That's the only case tested.
var turnDone = false; var turnDone = false;
ObservableWrapper.subscribe(_zone.onMicrotaskEmpty, (_) => { _zone.onMicrotaskEmpty.subscribe({
_log.add('onMyMicrotaskEmpty'); next: () => {
if (turnDone) return; _log.add('onMyMicrotaskEmpty');
_zone.run(() => { scheduleMicroTask(() => {}); }); if (turnDone) return;
turnDone = true; _zone.run(() => { scheduleMicroTask(() => {}); });
turnDone = true;
}
}); });
macroTask(() => { macroTask(() => {
@ -323,9 +338,11 @@ function commonTests() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
runNgZoneNoLog(() => macroTask(_log.fn('run'))); runNgZoneNoLog(() => macroTask(_log.fn('run')));
ObservableWrapper.subscribe(_zone.onStable, (_) => { _zone.onStable.subscribe({
NgZone.assertNotInAngularZone(); next: () => {
_log.add('onMyTaskDone'); NgZone.assertNotInAngularZone();
_log.add('onMyTaskDone');
}
}); });
macroTask(() => { macroTask(() => {
@ -378,10 +395,12 @@ function commonTests() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
runNgZoneNoLog(() => macroTask(_log.fn('start run'))); runNgZoneNoLog(() => macroTask(_log.fn('start run')));
ObservableWrapper.subscribe(_zone.onMicrotaskEmpty, (_) => { _zone.onMicrotaskEmpty.subscribe({
_log.add('onMicrotaskEmpty:started'); next: () => {
_zone.run(() => _log.add('nested run')); _log.add('onMicrotaskEmpty:started');
_log.add('onMicrotaskEmpty:finished'); _zone.run(() => _log.add('nested run'));
_log.add('onMicrotaskEmpty:finished');
}
}); });
macroTask(() => { macroTask(() => {
@ -407,24 +426,26 @@ function commonTests() {
it('should call onUnstable and onMicrotaskEmpty before and after each turn', it('should call onUnstable and onMicrotaskEmpty before and after each turn',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var a: PromiseCompleter<string>; var aResolve: (result: string) => void;
var b: PromiseCompleter<string>; var aPromise: Promise<string>;
var bResolve: (result: string) => void;
var bPromise: Promise<string>;
runNgZoneNoLog(() => { runNgZoneNoLog(() => {
macroTask(() => { macroTask(() => {
a = PromiseWrapper.completer(); aPromise = new Promise(res => { aResolve = res; });
b = PromiseWrapper.completer(); bPromise = new Promise(res => { bResolve = res; });
_log.add('run start'); _log.add('run start');
a.promise.then(_log.fn('a then')); aPromise.then(_log.fn('a then'));
b.promise.then(_log.fn('b then')); bPromise.then(_log.fn('b then'));
}); });
}); });
runNgZoneNoLog(() => { runNgZoneNoLog(() => {
macroTask(() => { macroTask(() => {
a.resolve('a'); aResolve('a');
b.resolve('b'); bResolve('b');
}); });
}); });
@ -448,24 +469,25 @@ function commonTests() {
it('should call onUnstable and onMicrotaskEmpty when an inner microtask is scheduled from outside angular', it('should call onUnstable and onMicrotaskEmpty when an inner microtask is scheduled from outside angular',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var completer: PromiseCompleter<any>; var resolve: (result: string) => void;
var promise: Promise<string>;
macroTask(() => { macroTask(() => {
NgZone.assertNotInAngularZone(); NgZone.assertNotInAngularZone();
completer = PromiseWrapper.completer(); promise = new Promise(res => { resolve = res; });
}); });
runNgZoneNoLog(() => { runNgZoneNoLog(() => {
macroTask(() => { macroTask(() => {
NgZone.assertInAngularZone(); NgZone.assertInAngularZone();
completer.promise.then(_log.fn('executedMicrotask')); promise.then(_log.fn('executedMicrotask'));
}); });
}); });
macroTask(() => { macroTask(() => {
NgZone.assertNotInAngularZone(); NgZone.assertNotInAngularZone();
_log.add('scheduling a microtask'); _log.add('scheduling a microtask');
completer.resolve(null); resolve(null);
}); });
macroTask(() => { macroTask(() => {
@ -488,19 +510,21 @@ function commonTests() {
runNgZoneNoLog(() => macroTask(_log.fn('run'))); runNgZoneNoLog(() => macroTask(_log.fn('run')));
var ran = false; var ran = false;
ObservableWrapper.subscribe(_zone.onMicrotaskEmpty, (_) => { _zone.onMicrotaskEmpty.subscribe({
_log.add('onMicrotaskEmpty(begin)'); next: () => {
_log.add('onMicrotaskEmpty(begin)');
if (!ran) { if (!ran) {
_zone.run(() => { _zone.run(() => {
scheduleMicroTask(() => { scheduleMicroTask(() => {
ran = true; ran = true;
_log.add('executedMicrotask'); _log.add('executedMicrotask');
});
}); });
}); }
}
_log.add('onMicrotaskEmpty(end)'); _log.add('onMicrotaskEmpty(end)');
}
}); });
macroTask(() => { macroTask(() => {
@ -525,18 +549,20 @@ function commonTests() {
}); });
var ran = false; var ran = false;
ObservableWrapper.subscribe(_zone.onMicrotaskEmpty, (_) => { _zone.onMicrotaskEmpty.subscribe({
_log.add('onMicrotaskEmpty(begin)'); next: () => {
if (!ran) { _log.add('onMicrotaskEmpty(begin)');
_log.add('onMicrotaskEmpty(scheduleMicroTask)'); if (!ran) {
_zone.run(() => { _log.add('onMicrotaskEmpty(scheduleMicroTask)');
scheduleMicroTask(() => { _zone.run(() => {
ran = true; scheduleMicroTask(() => {
_log.add('onMicrotaskEmpty(executeMicrotask)'); ran = true;
_log.add('onMicrotaskEmpty(executeMicrotask)');
});
}); });
}); }
_log.add('onMicrotaskEmpty(end)');
} }
_log.add('onMicrotaskEmpty(end)');
}); });
macroTask(() => { macroTask(() => {
@ -555,11 +581,11 @@ function commonTests() {
runNgZoneNoLog(() => { runNgZoneNoLog(() => {
macroTask(() => { macroTask(() => {
_log.add('run start'); _log.add('run start');
PromiseWrapper.resolve(null) resolvedPromise
.then((_) => { .then((_) => {
_log.add('promise then'); _log.add('promise then');
PromiseWrapper.resolve(null).then(_log.fn('promise foo')); resolvedPromise.then(_log.fn('promise foo'));
return PromiseWrapper.resolve(null); return Promise.resolve(null);
}) })
.then(_log.fn('promise bar')); .then(_log.fn('promise bar'));
_log.add('run end'); _log.add('run end');
@ -569,24 +595,28 @@ function commonTests() {
var donePromiseRan = false; var donePromiseRan = false;
var startPromiseRan = false; var startPromiseRan = false;
ObservableWrapper.subscribe(_zone.onUnstable, (_) => { _zone.onUnstable.subscribe({
_log.add('onUnstable(begin)'); next: () => {
if (!startPromiseRan) { _log.add('onUnstable(begin)');
_log.add('onUnstable(schedulePromise)'); if (!startPromiseRan) {
_zone.run(() => { scheduleMicroTask(_log.fn('onUnstable(executePromise)')); }); _log.add('onUnstable(schedulePromise)');
startPromiseRan = true; _zone.run(() => { scheduleMicroTask(_log.fn('onUnstable(executePromise)')); });
startPromiseRan = true;
}
_log.add('onUnstable(end)');
} }
_log.add('onUnstable(end)');
}); });
ObservableWrapper.subscribe(_zone.onMicrotaskEmpty, (_) => { _zone.onMicrotaskEmpty.subscribe({
_log.add('onMicrotaskEmpty(begin)'); next: () => {
if (!donePromiseRan) { _log.add('onMicrotaskEmpty(begin)');
_log.add('onMicrotaskEmpty(schedulePromise)'); if (!donePromiseRan) {
_zone.run(() => { scheduleMicroTask(_log.fn('onMicrotaskEmpty(executePromise)')); }); _log.add('onMicrotaskEmpty(schedulePromise)');
donePromiseRan = true; _zone.run(() => { scheduleMicroTask(_log.fn('onMicrotaskEmpty(executePromise)')); });
donePromiseRan = true;
}
_log.add('onMicrotaskEmpty(end)');
} }
_log.add('onMicrotaskEmpty(end)');
}); });
macroTask(() => { macroTask(() => {
@ -608,22 +638,24 @@ function commonTests() {
it('should call onUnstable and onMicrotaskEmpty before and after each turn, respectively', it('should call onUnstable and onMicrotaskEmpty before and after each turn, respectively',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var completerA: PromiseCompleter<any>; var aResolve: (result: string) => void;
var completerB: PromiseCompleter<any>; var aPromise: Promise<string>;
var bResolve: (result: string) => void;
var bPromise: Promise<string>;
runNgZoneNoLog(() => { runNgZoneNoLog(() => {
macroTask(() => { macroTask(() => {
completerA = PromiseWrapper.completer(); aPromise = new Promise(res => { aResolve = res; });
completerB = PromiseWrapper.completer(); bPromise = new Promise(res => { bResolve = res; });
completerA.promise.then(_log.fn('a then')); aPromise.then(_log.fn('a then'));
completerB.promise.then(_log.fn('b then')); bPromise.then(_log.fn('b then'));
_log.add('run start'); _log.add('run start');
}); });
}); });
runNgZoneNoLog(() => { macroTask(() => { completerA.resolve(null); }, 10); }); runNgZoneNoLog(() => { macroTask(() => { aResolve(null); }, 10); });
runNgZoneNoLog(() => { macroTask(() => { completerB.resolve(null); }, 20); }); runNgZoneNoLog(() => { macroTask(() => { bResolve(null); }, 20); });
macroTask(() => { macroTask(() => {
expect(_log.result()) expect(_log.result())
@ -665,9 +697,8 @@ function commonTests() {
runNgZoneNoLog(() => { runNgZoneNoLog(() => {
macroTask(() => { macroTask(() => {
_zone.runOutsideAngular(() => { _zone.runOutsideAngular(
promise = PromiseWrapper.resolve(4).then((x) => PromiseWrapper.resolve(x)); () => { promise = Promise.resolve(4).then((x) => Promise.resolve(x)); });
});
promise.then(_log.fn('promise then')); promise.then(_log.fn('promise then'));
_log.add('zone run'); _log.add('zone run');

View File

@ -6,16 +6,19 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {PromiseCompleter} from '../src/facade/promise';
/** /**
* Injectable completer that allows signaling completion of an asynchronous test. Used internally. * Injectable completer that allows signaling completion of an asynchronous test. Used internally.
*/ */
export class AsyncTestCompleter { export class AsyncTestCompleter {
private _completer = new PromiseCompleter<any>(); private _resolve: (result: any) => void;
done(value?: any) { this._completer.resolve(value); } private _reject: (err: any) => void;
private _promise: Promise<any> = new Promise((res, rej) => {
this._resolve = res;
this._reject = rej;
});
done(value?: any) { this._resolve(value); }
fail(error?: any, stackTrace?: string) { this._completer.reject(error, stackTrace); } fail(error?: any, stackTrace?: string) { this._reject(error); }
get promise(): Promise<any> { return this._completer.promise; } get promise(): Promise<any> { return this._promise; }
} }

View File

@ -7,7 +7,6 @@
*/ */
import {AnimationEntryMetadata, ChangeDetectorRef, ComponentFactory, ComponentRef, ComponentResolver, DebugElement, ElementRef, Injectable, Injector, NgZone, NgZoneError, OpaqueToken, ViewMetadata, getDebugNode} from '../index'; import {AnimationEntryMetadata, ChangeDetectorRef, ComponentFactory, ComponentRef, ComponentResolver, DebugElement, ElementRef, Injectable, Injector, NgZone, NgZoneError, OpaqueToken, ViewMetadata, getDebugNode} from '../index';
import {ObservableWrapper, PromiseCompleter, PromiseWrapper} from '../src/facade/async';
import {BaseException} from '../src/facade/exceptions'; import {BaseException} from '../src/facade/exceptions';
import {scheduleMicroTask} from '../src/facade/lang'; import {scheduleMicroTask} from '../src/facade/lang';
@ -58,7 +57,8 @@ export class ComponentFixture<T> {
private _autoDetect: boolean; private _autoDetect: boolean;
private _isStable: boolean = true; private _isStable: boolean = true;
private _completer: PromiseCompleter<any> = null; private _resolve: (result: any) => void;
private _promise: Promise<any> = null;
private _onUnstableSubscription: any /** TODO #9100 */ = null; private _onUnstableSubscription: any /** TODO #9100 */ = null;
private _onStableSubscription: any /** TODO #9100 */ = null; private _onStableSubscription: any /** TODO #9100 */ = null;
private _onMicrotaskEmptySubscription: any /** TODO #9100 */ = null; private _onMicrotaskEmptySubscription: any /** TODO #9100 */ = null;
@ -76,35 +76,39 @@ export class ComponentFixture<T> {
if (ngZone != null) { if (ngZone != null) {
this._onUnstableSubscription = this._onUnstableSubscription =
ObservableWrapper.subscribe(ngZone.onUnstable, (_) => { this._isStable = false; }); ngZone.onUnstable.subscribe({next: () => { this._isStable = false; }});
this._onMicrotaskEmptySubscription = this._onMicrotaskEmptySubscription = ngZone.onMicrotaskEmpty.subscribe({
ObservableWrapper.subscribe(ngZone.onMicrotaskEmpty, (_) => { next: () => {
if (this._autoDetect) { if (this._autoDetect) {
// Do a change detection run with checkNoChanges set to true to check // Do a change detection run with checkNoChanges set to true to check
// there are no changes on the second run. // there are no changes on the second run.
this.detectChanges(true); this.detectChanges(true);
} }
}); }
this._onStableSubscription = ObservableWrapper.subscribe(ngZone.onStable, (_) => { });
this._isStable = true; this._onStableSubscription = ngZone.onStable.subscribe({
// Check whether there is a pending whenStable() completer to resolve. next: () => {
if (this._completer !== null) { this._isStable = true;
// If so check whether there are no pending macrotasks before resolving. // Check whether there is a pending whenStable() completer to resolve.
// Do this check in the next tick so that ngZone gets a chance to update the state of if (this._promise !== null) {
// pending macrotasks. // If so check whether there are no pending macrotasks before resolving.
scheduleMicroTask(() => { // Do this check in the next tick so that ngZone gets a chance to update the state of
if (!this.ngZone.hasPendingMacrotasks) { // pending macrotasks.
if (this._completer !== null) { scheduleMicroTask(() => {
this._completer.resolve(true); if (!this.ngZone.hasPendingMacrotasks) {
this._completer = null; if (this._promise !== null) {
this._resolve(true);
this._resolve = null;
this._promise = null;
}
} }
} });
}); }
} }
}); });
this._onErrorSubscription = ObservableWrapper.subscribe( this._onErrorSubscription =
ngZone.onError, (error: NgZoneError) => { throw error.error; }); ngZone.onError.subscribe({next: (error: NgZoneError) => { throw error.error; }});
} }
} }
@ -161,12 +165,12 @@ export class ComponentFixture<T> {
*/ */
whenStable(): Promise<any> { whenStable(): Promise<any> {
if (this.isStable()) { if (this.isStable()) {
return PromiseWrapper.resolve(false); return Promise.resolve(false);
} else if (this._completer !== null) { } else if (this._promise !== null) {
return this._completer.promise; return this._promise;
} else { } else {
this._completer = new PromiseCompleter<any>(); this._promise = new Promise(res => { this._resolve = res; });
return this._completer.promise; return this._promise;
} }
} }
@ -176,19 +180,19 @@ export class ComponentFixture<T> {
destroy(): void { destroy(): void {
this.componentRef.destroy(); this.componentRef.destroy();
if (this._onUnstableSubscription != null) { if (this._onUnstableSubscription != null) {
ObservableWrapper.dispose(this._onUnstableSubscription); this._onUnstableSubscription.unsubscribe();
this._onUnstableSubscription = null; this._onUnstableSubscription = null;
} }
if (this._onStableSubscription != null) { if (this._onStableSubscription != null) {
ObservableWrapper.dispose(this._onStableSubscription); this._onStableSubscription.unsubscribe();
this._onStableSubscription = null; this._onStableSubscription = null;
} }
if (this._onMicrotaskEmptySubscription != null) { if (this._onMicrotaskEmptySubscription != null) {
ObservableWrapper.dispose(this._onMicrotaskEmptySubscription); this._onMicrotaskEmptySubscription.unsubscribe();
this._onMicrotaskEmptySubscription = null; this._onMicrotaskEmptySubscription = null;
} }
if (this._onErrorSubscription != null) { if (this._onErrorSubscription != null) {
ObservableWrapper.dispose(this._onErrorSubscription); this._onErrorSubscription.unsubscribe();
this._onErrorSubscription = null; this._onErrorSubscription = null;
} }
} }

View File

@ -7,7 +7,7 @@
*/ */
import {Injectable, NgZone} from '../index'; import {Injectable, NgZone} from '../index';
import {EventEmitter, ObservableWrapper} from '../src/facade/async'; import {EventEmitter} from '../src/facade/async';
/** /**
* A mock implementation of {@link NgZone}. * A mock implementation of {@link NgZone}.
@ -24,5 +24,5 @@ export class MockNgZone extends NgZone {
runOutsideAngular(fn: Function): any { return fn(); } runOutsideAngular(fn: Function): any { return fn(); }
simulateZoneExit(): void { ObservableWrapper.callNext(this.onStable, null); } simulateZoneExit(): void { this.onStable.emit(null); }
} }

View File

@ -7,7 +7,6 @@
*/ */
import {AnimationEntryMetadata, Compiler, ComponentFactory, Injectable, Injector, NgZone, OpaqueToken, ViewMetadata} from '../index'; import {AnimationEntryMetadata, Compiler, ComponentFactory, Injectable, Injector, NgZone, OpaqueToken, ViewMetadata} from '../index';
import {PromiseWrapper} from '../src/facade/async';
import {ConcreteType, Type, isPresent} from '../src/facade/lang'; import {ConcreteType, Type, isPresent} from '../src/facade/lang';
import {ComponentFixture} from './component_fixture'; import {ComponentFixture} from './component_fixture';
@ -119,9 +118,9 @@ export class TestComponentBuilder {
createFakeAsync<T>(rootComponentType: ConcreteType<T>): ComponentFixture<T> { createFakeAsync<T>(rootComponentType: ConcreteType<T>): ComponentFixture<T> {
let result: any /** TODO #9100 */; let result: any /** TODO #9100 */;
let error: any /** TODO #9100 */; let error: any /** TODO #9100 */;
PromiseWrapper.then(
this.createAsync(rootComponentType), (_result) => { result = _result; }, this.createAsync(rootComponentType)
(_error) => { error = _error; }); .then((_result) => { result = _result; }, (_error) => { error = _error; });
tick(); tick();
if (isPresent(error)) { if (isPresent(error)) {
throw error; throw error;

View File

@ -6,65 +6,12 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject'; import {Subject} from 'rxjs/Subject';
import {PromiseObservable} from 'rxjs/observable/PromiseObservable';
import {toPromise} from 'rxjs/operator/toPromise';
import {global, noop} from './lang'; import {global, noop} from './lang';
export {Observable} from 'rxjs/Observable'; export {Observable} from 'rxjs/Observable';
export {Subject} from 'rxjs/Subject'; export {Subject} from 'rxjs/Subject';
export {PromiseCompleter, PromiseWrapper} from './promise';
export class TimerWrapper {
static setTimeout(fn: (...args: any[]) => void, millis: number): number {
return global.setTimeout(fn, millis);
}
static clearTimeout(id: number): void { global.clearTimeout(id); }
static setInterval(fn: (...args: any[]) => void, millis: number): number {
return global.setInterval(fn, millis);
}
static clearInterval(id: number): void { global.clearInterval(id); }
}
export class ObservableWrapper {
// TODO(vsavkin): when we use rxnext, try inferring the generic type from the first arg
static subscribe<T>(
emitter: any, onNext: (value: T) => void, onError?: (exception: any) => void,
onComplete: () => void = () => {}): Object {
onError = (typeof onError === 'function') && onError || noop;
onComplete = (typeof onComplete === 'function') && onComplete || noop;
return emitter.subscribe({next: onNext, error: onError, complete: onComplete});
}
static isObservable(obs: any): boolean { return !!obs.subscribe; }
/**
* Returns whether `obs` has any subscribers listening to events.
*/
static hasSubscribers(obs: EventEmitter<any>): boolean { return obs.observers.length > 0; }
static dispose(subscription: any) { subscription.unsubscribe(); }
/**
* @deprecated - use callEmit() instead
*/
static callNext(emitter: EventEmitter<any>, value: any) { emitter.emit(value); }
static callEmit(emitter: EventEmitter<any>, value: any) { emitter.emit(value); }
static callError(emitter: EventEmitter<any>, error: any) { emitter.error(error); }
static callComplete(emitter: EventEmitter<any>) { emitter.complete(); }
static fromPromise(promise: Promise<any>): Observable<any> {
return PromiseObservable.create(promise);
}
static toPromise(obj: Observable<any>): Promise<any> { return toPromise.call(obj); }
}
/** /**
* Use by directives and components to emit custom Events. * Use by directives and components to emit custom Events.

View File

@ -1,61 +0,0 @@
/**
* @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
*/
export class PromiseCompleter<R> {
promise: Promise<R>;
resolve: (value?: R|PromiseLike<R>) => void;
reject: (error?: any, stackTrace?: string) => void;
constructor() {
this.promise = new Promise((res, rej) => {
this.resolve = res;
this.reject = rej;
});
}
}
export class PromiseWrapper {
static resolve<T>(obj: T): Promise<T> { return Promise.resolve(obj); }
static reject(obj: any, _: any): Promise<any> { return Promise.reject(obj); }
// Note: We can't rename this method into `catch`, as this is not a valid
// method name in Dart.
static catchError<T>(promise: Promise<T>, onError: (error: any) => T | PromiseLike<T>):
Promise<T> {
return promise.catch(onError);
}
static all<T>(promises: (T|Promise<T>)[]): Promise<T[]> {
if (promises.length == 0) return Promise.resolve([]);
return Promise.all(promises);
}
static then<T, U>(
promise: Promise<T>, success: (value: T) => U | PromiseLike<U>,
rejection?: (error: any, stack?: any) => U | PromiseLike<U>): Promise<U> {
return promise.then(success, rejection);
}
static wrap<T>(computation: () => T): Promise<T> {
return new Promise((res, rej) => {
try {
res(computation());
} catch (e) {
rej(e);
}
});
}
static scheduleMicrotask(computation: () => any): void {
PromiseWrapper.then(PromiseWrapper.resolve(null), computation, (_) => {});
}
static completer<T>(): PromiseCompleter<T> { return new PromiseCompleter<T>(); }
}

View File

@ -6,9 +6,9 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, describe, it, expect, beforeEach, ddescribe, iit, xit, inject,} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {browserDetection} from '@angular/platform-browser/testing/browser_util'; import {browserDetection} from '@angular/platform-browser/testing/browser_util';
import {ObservableWrapper, Observable, Subject, EventEmitter, PromiseWrapper} from '../src/async'; import {EventEmitter, Observable, Subject} from '../src/async';
export function main() { export function main() {
describe('EventEmitter', () => { describe('EventEmitter', () => {
@ -18,82 +18,88 @@ export function main() {
it('should call the next callback', it('should call the next callback',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ObservableWrapper.subscribe(emitter, (value) => { emitter.subscribe({
expect(value).toEqual(99); next: (value: any) => {
async.done(); expect(value).toEqual(99);
async.done();
}
}); });
emitter.emit(99);
ObservableWrapper.callEmit(emitter, 99);
})); }));
it('should call the throw callback', it('should call the throw callback',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ObservableWrapper.subscribe(emitter, (_) => {}, (error) => { emitter.subscribe({
expect(error).toEqual('Boom'); next: () => {},
async.done(); error: (error: any) => {
expect(error).toEqual('Boom');
async.done();
}
}); });
ObservableWrapper.callError(emitter, 'Boom'); emitter.error('Boom');
})); }));
it('should work when no throw callback is provided', it('should work when no throw callback is provided',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ObservableWrapper.subscribe(emitter, (_) => {}, (_) => { async.done(); }); emitter.subscribe({next: () => {}, error: (_: any) => { async.done(); }});
ObservableWrapper.callError(emitter, 'Boom'); emitter.error('Boom');
})); }));
it('should call the return callback', it('should call the return callback',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ObservableWrapper.subscribe(emitter, (_) => {}, (_) => {}, () => { async.done(); }); emitter.subscribe(
{next: () => {}, error: (_: any) => {}, complete: () => { async.done(); }});
ObservableWrapper.callComplete(emitter); emitter.complete();
})); }));
it('should subscribe to the wrapper synchronously', () => { it('should subscribe to the wrapper synchronously', () => {
var called = false; var called = false;
ObservableWrapper.subscribe(emitter, (value) => { called = true; }); emitter.subscribe({next: (value: any) => { called = true; }});
emitter.emit(99);
ObservableWrapper.callEmit(emitter, 99);
expect(called).toBe(true); expect(called).toBe(true);
}); });
it('delivers next and error events synchronously', it('delivers next and error events synchronously',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let log: any[] /** TODO #9100 */ = []; let log: any[] /** TODO #9100 */ = [];
ObservableWrapper.subscribe(
emitter, emitter.subscribe({
(x) => { next: (x: any) => {
log.push(x); log.push(x);
expect(log).toEqual([1, 2]); expect(log).toEqual([1, 2]);
}, },
(err) => { error: (err: any) => {
log.push(err); log.push(err);
expect(log).toEqual([1, 2, 3, 4]); expect(log).toEqual([1, 2, 3, 4]);
async.done(); async.done();
}); }
});
log.push(1); log.push(1);
ObservableWrapper.callEmit(emitter, 2); emitter.emit(2);
log.push(3); log.push(3);
ObservableWrapper.callError(emitter, 4); emitter.error(4);
log.push(5); log.push(5);
})); }));
it('delivers next and complete events synchronously', () => { it('delivers next and complete events synchronously', () => {
let log: any[] /** TODO #9100 */ = []; let log: any[] /** TODO #9100 */ = [];
ObservableWrapper.subscribe(
emitter, emitter.subscribe({
(x) => { next: (x: any) => {
log.push(x); log.push(x);
expect(log).toEqual([1, 2]); expect(log).toEqual([1, 2]);
}, },
null, error: null,
() => { complete: () => {
log.push(4); log.push(4);
expect(log).toEqual([1, 2, 3, 4]); expect(log).toEqual([1, 2, 3, 4]);
}); }
});
log.push(1); log.push(1);
ObservableWrapper.callEmit(emitter, 2); emitter.emit(2);
log.push(3); log.push(3);
ObservableWrapper.callComplete(emitter); emitter.complete();
log.push(5); log.push(5);
expect(log).toEqual([1, 2, 3, 4, 5]); expect(log).toEqual([1, 2, 3, 4, 5]);
}); });
@ -102,22 +108,22 @@ export function main() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var e = new EventEmitter(true); var e = new EventEmitter(true);
var log: any[] /** TODO #9100 */ = []; var log: any[] /** TODO #9100 */ = [];
ObservableWrapper.subscribe(e, (x) => { e.subscribe((x: any) => {
log.push(x); log.push(x);
expect(log).toEqual([1, 3, 2]); expect(log).toEqual([1, 3, 2]);
async.done(); async.done();
}); });
log.push(1); log.push(1);
ObservableWrapper.callEmit(e, 2); e.emit(2);
log.push(3); log.push(3);
})); }));
it('reports whether it has subscribers', () => { it('reports whether it has subscribers', () => {
var e = new EventEmitter(false); var e = new EventEmitter(false);
expect(ObservableWrapper.hasSubscribers(e)).toBe(false); expect(e.observers.length > 0).toBe(false);
ObservableWrapper.subscribe(e, (_) => {}); e.subscribe({next: () => {}});
expect(ObservableWrapper.hasSubscribers(e)).toBe(true); expect(e.observers.length > 0).toBe(true);
}); });
// TODO: vsavkin: add tests cases // TODO: vsavkin: add tests cases
@ -125,71 +131,4 @@ export function main() {
// should call dispose on the subscription on throw // should call dispose on the subscription on throw
// should call dispose on the subscription on return // should call dispose on the subscription on return
}); });
describe('ObservableWrapper', () => {
it('should correctly check isObservable for EventEmitter', () => {
var e = new EventEmitter(false);
expect(ObservableWrapper.isObservable(e)).toBe(true);
});
it('should correctly check isObservable for Subject', () => {
var e = new Subject();
expect(ObservableWrapper.isObservable(e)).toBe(true);
});
it('should subscribe to EventEmitters', () => {
let e = new EventEmitter(false);
ObservableWrapper.subscribe(e, (val) => {});
ObservableWrapper.callEmit(e, 1);
ObservableWrapper.callComplete(e);
});
});
// See ECMAScript 6 Spec 25.4.4.1
describe('PromiseWrapper', () => {
describe('#all', () => {
it('should combine lists of Promises',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var one = PromiseWrapper.completer();
var two = PromiseWrapper.completer();
var all = PromiseWrapper.all([one.promise, two.promise]);
var allCalled = false;
PromiseWrapper.then(one.promise, (_) => {
expect(allCalled).toBe(false);
two.resolve('two');
return null;
});
PromiseWrapper.then(all, (_) => {
allCalled = true;
async.done();
return null;
});
one.resolve('one');
}));
[null, true, false, 10, 'thing', {}, []].forEach(abruptCompletion => {
it(`should treat "${abruptCompletion}" as an "abrupt completion"`,
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var one = PromiseWrapper.completer();
var all = PromiseWrapper.all([one.promise, abruptCompletion]);
PromiseWrapper.then(all, (val) => {
expect(val[1]).toEqual(abruptCompletion);
async.done();
});
one.resolve('one');
}));
});
});
});
} }

View File

@ -8,7 +8,7 @@
import {Directive, Inject, Optional, Self, forwardRef} from '@angular/core'; import {Directive, Inject, Optional, Self, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper, PromiseWrapper} from '../facade/async'; import {EventEmitter} from '../facade/async';
import {ListWrapper} from '../facade/collection'; import {ListWrapper} from '../facade/collection';
import {isPresent} from '../facade/lang'; import {isPresent} from '../facade/lang';
import {AbstractControl, FormControl, FormGroup} from '../model'; import {AbstractControl, FormControl, FormGroup} from '../model';
@ -26,6 +26,8 @@ export const formDirectiveProvider: any = {
useExisting: forwardRef(() => NgForm) useExisting: forwardRef(() => NgForm)
}; };
const resolvedPromise = Promise.resolve(null);
/** /**
* If `NgForm` is bound in a component, `<form>` elements in that component will be * If `NgForm` is bound in a component, `<form>` elements in that component will be
* upgraded to use the Angular form system. * upgraded to use the Angular form system.
@ -117,7 +119,7 @@ export class NgForm extends ControlContainer implements Form {
get controls(): {[key: string]: AbstractControl} { return this.form.controls; } get controls(): {[key: string]: AbstractControl} { return this.form.controls; }
addControl(dir: NgModel): void { addControl(dir: NgModel): void {
PromiseWrapper.scheduleMicrotask(() => { resolvedPromise.then(() => {
const container = this._findContainer(dir.path); const container = this._findContainer(dir.path);
dir._control = <FormControl>container.registerControl(dir.name, dir.control); dir._control = <FormControl>container.registerControl(dir.name, dir.control);
setUpControl(dir.control, dir); setUpControl(dir.control, dir);
@ -128,7 +130,7 @@ export class NgForm extends ControlContainer implements Form {
getControl(dir: NgModel): FormControl { return <FormControl>this.form.find(dir.path); } getControl(dir: NgModel): FormControl { return <FormControl>this.form.find(dir.path); }
removeControl(dir: NgModel): void { removeControl(dir: NgModel): void {
PromiseWrapper.scheduleMicrotask(() => { resolvedPromise.then(() => {
var container = this._findContainer(dir.path); var container = this._findContainer(dir.path);
if (isPresent(container)) { if (isPresent(container)) {
container.removeControl(dir.name); container.removeControl(dir.name);
@ -137,7 +139,7 @@ export class NgForm extends ControlContainer implements Form {
} }
addFormGroup(dir: NgModelGroup): void { addFormGroup(dir: NgModelGroup): void {
PromiseWrapper.scheduleMicrotask(() => { resolvedPromise.then(() => {
var container = this._findContainer(dir.path); var container = this._findContainer(dir.path);
var group = new FormGroup({}); var group = new FormGroup({});
setUpFormContainer(group, dir); setUpFormContainer(group, dir);
@ -147,7 +149,7 @@ export class NgForm extends ControlContainer implements Form {
} }
removeFormGroup(dir: NgModelGroup): void { removeFormGroup(dir: NgModelGroup): void {
PromiseWrapper.scheduleMicrotask(() => { resolvedPromise.then(() => {
var container = this._findContainer(dir.path); var container = this._findContainer(dir.path);
if (isPresent(container)) { if (isPresent(container)) {
container.removeControl(dir.name); container.removeControl(dir.name);
@ -158,7 +160,7 @@ export class NgForm extends ControlContainer implements Form {
getFormGroup(dir: NgModelGroup): FormGroup { return <FormGroup>this.form.find(dir.path); } getFormGroup(dir: NgModelGroup): FormGroup { return <FormGroup>this.form.find(dir.path); }
updateModel(dir: NgControl, value: any): void { updateModel(dir: NgControl, value: any): void {
PromiseWrapper.scheduleMicrotask(() => { resolvedPromise.then(() => {
var ctrl = <FormControl>this.form.find(dir.path); var ctrl = <FormControl>this.form.find(dir.path);
ctrl.updateValue(value); ctrl.updateValue(value);
}); });
@ -168,7 +170,7 @@ export class NgForm extends ControlContainer implements Form {
onSubmit(): boolean { onSubmit(): boolean {
this._submitted = true; this._submitted = true;
ObservableWrapper.callEmit(this.ngSubmit, null); this.ngSubmit.emit(null);
return false; return false;
} }

View File

@ -8,7 +8,7 @@
import {Directive, Host, Inject, Input, OnChanges, OnDestroy, Optional, Output, Self, SimpleChanges, forwardRef} from '@angular/core'; import {Directive, Host, Inject, Input, OnChanges, OnDestroy, Optional, Output, Self, SimpleChanges, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper, PromiseWrapper} from '../facade/async'; import {EventEmitter} from '../facade/async';
import {BaseException} from '../facade/exceptions'; import {BaseException} from '../facade/exceptions';
import {FormControl} from '../model'; import {FormControl} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
@ -28,6 +28,8 @@ export const formControlBinding: any = {
useExisting: forwardRef(() => NgModel) useExisting: forwardRef(() => NgModel)
}; };
const resolvedPromise = Promise.resolve(null);
/** /**
* Binds a domain model to a form control. * Binds a domain model to a form control.
* *
@ -105,7 +107,7 @@ export class NgModel extends NgControl implements OnChanges,
viewToModelUpdate(newValue: any): void { viewToModelUpdate(newValue: any): void {
this.viewModel = newValue; this.viewModel = newValue;
ObservableWrapper.callEmit(this.update, newValue); this.update.emit(newValue);
} }
private _setUpControl(): void { private _setUpControl(): void {
@ -149,7 +151,7 @@ export class NgModel extends NgControl implements OnChanges,
} }
private _updateValue(value: any): void { private _updateValue(value: any): void {
PromiseWrapper.scheduleMicrotask( resolvedPromise.then(
() => { this.control.updateValue(value, {emitViewToModelChange: false}); }); () => { this.control.updateValue(value, {emitViewToModelChange: false}); });
} }
} }

View File

@ -8,7 +8,7 @@
import {Directive, Inject, Input, OnChanges, Optional, Output, Self, SimpleChanges, forwardRef} from '@angular/core'; import {Directive, Inject, Input, OnChanges, Optional, Output, Self, SimpleChanges, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper} from '../../facade/async'; import {EventEmitter} from '../../facade/async';
import {StringMapWrapper} from '../../facade/collection'; import {StringMapWrapper} from '../../facade/collection';
import {FormControl} from '../../model'; import {FormControl} from '../../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../../validators'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../../validators';
@ -110,7 +110,7 @@ export class FormControlDirective extends NgControl implements OnChanges {
viewToModelUpdate(newValue: any): void { viewToModelUpdate(newValue: any): void {
this.viewModel = newValue; this.viewModel = newValue;
ObservableWrapper.callEmit(this.update, newValue); this.update.emit(newValue);
} }
private _isControlChanged(changes: {[key: string]: any}): boolean { private _isControlChanged(changes: {[key: string]: any}): boolean {

View File

@ -8,7 +8,7 @@
import {Directive, Host, Inject, Input, OnChanges, OnDestroy, Optional, Output, Self, SimpleChanges, SkipSelf, forwardRef} from '@angular/core'; import {Directive, Host, Inject, Input, OnChanges, OnDestroy, Optional, Output, Self, SimpleChanges, SkipSelf, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper} from '../../facade/async'; import {EventEmitter} from '../../facade/async';
import {FormControl} from '../../model'; import {FormControl} from '../../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../../validators'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../../validators';
import {AbstractFormGroupDirective} from '../abstract_form_group_directive'; import {AbstractFormGroupDirective} from '../abstract_form_group_directive';
@ -134,7 +134,7 @@ export class FormControlName extends NgControl implements OnChanges, OnDestroy {
viewToModelUpdate(newValue: any): void { viewToModelUpdate(newValue: any): void {
this.viewModel = newValue; this.viewModel = newValue;
ObservableWrapper.callEmit(this.update, newValue); this.update.emit(newValue);
} }
get path(): string[] { return controlPath(this.name, this._parent); } get path(): string[] { return controlPath(this.name, this._parent); }

View File

@ -8,7 +8,7 @@
import {Directive, Inject, Input, OnChanges, Optional, Output, Self, SimpleChanges, forwardRef} from '@angular/core'; import {Directive, Inject, Input, OnChanges, Optional, Output, Self, SimpleChanges, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper} from '../../facade/async'; import {EventEmitter} from '../../facade/async';
import {ListWrapper, StringMapWrapper} from '../../facade/collection'; import {ListWrapper, StringMapWrapper} from '../../facade/collection';
import {BaseException} from '../../facade/exceptions'; import {BaseException} from '../../facade/exceptions';
import {isBlank} from '../../facade/lang'; import {isBlank} from '../../facade/lang';
@ -182,7 +182,7 @@ export class FormGroupDirective extends ControlContainer implements Form,
onSubmit(): boolean { onSubmit(): boolean {
this._submitted = true; this._submitted = true;
ObservableWrapper.callEmit(this.ngSubmit, null); this.ngSubmit.emit(null);
return false; return false;
} }

View File

@ -6,14 +6,17 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {PromiseObservable} from 'rxjs/observable/PromiseObservable';
import {composeAsyncValidators, composeValidators} from './directives/shared'; import {composeAsyncValidators, composeValidators} from './directives/shared';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators'; import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
import {EventEmitter, Observable, ObservableWrapper} from './facade/async'; import {EventEmitter, Observable} from './facade/async';
import {ListWrapper, StringMapWrapper} from './facade/collection'; import {ListWrapper, StringMapWrapper} from './facade/collection';
import {BaseException} from './facade/exceptions'; import {BaseException} from './facade/exceptions';
import {isBlank, isPresent, isPromise, normalizeBool} from './facade/lang'; import {isBlank, isPresent, isPromise, normalizeBool} from './facade/lang';
/** /**
* Indicates that a FormControl is valid, i.e. that no errors exist in the input value. * Indicates that a FormControl is valid, i.e. that no errors exist in the input value.
*/ */
@ -55,7 +58,7 @@ function _find(control: AbstractControl, path: Array<string|number>| string, del
} }
function toObservable(r: any): Observable<any> { function toObservable(r: any): Observable<any> {
return isPromise(r) ? ObservableWrapper.fromPromise(r) : r; return isPromise(r) ? PromiseObservable.create(r) : r;
} }
function coerceToValidator(validator: ValidatorFn | ValidatorFn[]): ValidatorFn { function coerceToValidator(validator: ValidatorFn | ValidatorFn[]): ValidatorFn {
@ -193,8 +196,8 @@ export abstract class AbstractControl {
} }
if (emitEvent) { if (emitEvent) {
ObservableWrapper.callEmit(this._valueChanges, this._value); this._valueChanges.emit(this._value);
ObservableWrapper.callEmit(this._statusChanges, this._status); this._statusChanges.emit(this._status);
} }
if (isPresent(this._parent) && !onlySelf) { if (isPresent(this._parent) && !onlySelf) {
@ -211,14 +214,14 @@ export abstract class AbstractControl {
this._status = PENDING; this._status = PENDING;
this._cancelExistingSubscription(); this._cancelExistingSubscription();
var obs = toObservable(this.asyncValidator(this)); var obs = toObservable(this.asyncValidator(this));
this._asyncValidationSubscription = ObservableWrapper.subscribe( this._asyncValidationSubscription = obs.subscribe(
obs, (res: {[key: string]: any}) => this.setErrors(res, {emitEvent: emitEvent})); {next: (res: {[key: string]: any}) => this.setErrors(res, {emitEvent: emitEvent})});
} }
} }
private _cancelExistingSubscription(): void { private _cancelExistingSubscription(): void {
if (isPresent(this._asyncValidationSubscription)) { if (isPresent(this._asyncValidationSubscription)) {
ObservableWrapper.dispose(this._asyncValidationSubscription); this._asyncValidationSubscription.unsubscribe();
} }
} }
@ -287,7 +290,7 @@ export abstract class AbstractControl {
this._status = this._calculateStatus(); this._status = this._calculateStatus();
if (emitEvent) { if (emitEvent) {
ObservableWrapper.callEmit(this._statusChanges, this._status); this._statusChanges.emit(this._status);
} }
if (isPresent(this._parent)) { if (isPresent(this._parent)) {

View File

@ -7,13 +7,14 @@
*/ */
import {OpaqueToken} from '@angular/core'; import {OpaqueToken} from '@angular/core';
import {toPromise} from 'rxjs/operator/toPromise';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators'; import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
import {ObservableWrapper} from './facade/async';
import {StringMapWrapper} from './facade/collection'; import {StringMapWrapper} from './facade/collection';
import {isBlank, isPresent, isPromise, isString} from './facade/lang'; import {isBlank, isPresent, isPromise, isString} from './facade/lang';
import {PromiseWrapper} from './facade/promise';
import {AbstractControl} from './model'; import {AbstractControl} from './model';
/** /**
* Providers for validators to be used for {@link FormControl}s in a form. * Providers for validators to be used for {@link FormControl}s in a form.
* *
@ -127,13 +128,13 @@ export class Validators {
return function(control: AbstractControl) { return function(control: AbstractControl) {
let promises = _executeAsyncValidators(control, presentValidators).map(_convertToPromise); let promises = _executeAsyncValidators(control, presentValidators).map(_convertToPromise);
return PromiseWrapper.all(promises).then(_mergeErrors); return Promise.all(promises).then(_mergeErrors);
}; };
} }
} }
function _convertToPromise(obj: any): Promise<any> { function _convertToPromise(obj: any): Promise<any> {
return isPromise(obj) ? obj : ObservableWrapper.toPromise(obj); return isPromise(obj) ? obj : toPromise.call(obj);
} }
function _executeValidators(control: AbstractControl, validators: ValidatorFn[]): any[] { function _executeValidators(control: AbstractControl, validators: ValidatorFn[]): any[] {

View File

@ -6,19 +6,14 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {SimpleChange} from '@angular/core/src/change_detection';
import {fakeAsync, flushMicrotasks, tick} from '@angular/core/testing';
import {Log, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {Log, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {CheckboxControlValueAccessor, ControlValueAccessor, DefaultValueAccessor, FormArray, FormArrayName, FormControl, FormControlDirective, FormControlName, FormGroup, FormGroupDirective, FormGroupName, NgControl, NgForm, NgModel, NgModelGroup, SelectControlValueAccessor, SelectMultipleControlValueAccessor, Validator, Validators} from '@angular/forms';
import {fakeAsync, flushMicrotasks, tick,} from '@angular/core/testing'; import {composeValidators, selectValueAccessor} from '@angular/forms/src/directives/shared';
import {SpyNgControl, SpyValueAccessor} from './spies'; import {SpyNgControl, SpyValueAccessor} from './spies';
import {FormGroup, FormControl, FormArray, FormArrayName, FormControlName, FormGroupName, NgModelGroup, FormGroupDirective, ControlValueAccessor, Validators, NgForm, NgModel, FormControlDirective, NgControl, DefaultValueAccessor, CheckboxControlValueAccessor, SelectControlValueAccessor, SelectMultipleControlValueAccessor, Validator} from '@angular/forms';
import {selectValueAccessor, composeValidators} from '@angular/forms/src/directives/shared';
import {TimerWrapper} from '../src/facade/async';
import {PromiseWrapper} from '../src/facade/promise';
import {SimpleChange} from '@angular/core/src/change_detection';
class DummyControlValueAccessor implements ControlValueAccessor { class DummyControlValueAccessor implements ControlValueAccessor {
writtenValue: any; writtenValue: any;
@ -34,14 +29,15 @@ class CustomValidatorDirective implements Validator {
function asyncValidator(expected: any /** TODO #9100 */, timeout = 0) { function asyncValidator(expected: any /** TODO #9100 */, timeout = 0) {
return (c: any /** TODO #9100 */) => { return (c: any /** TODO #9100 */) => {
var completer = PromiseWrapper.completer(); var resolve: (result: any) => void;
var promise = new Promise(res => { resolve = res; });
var res = c.value != expected ? {'async': true} : null; var res = c.value != expected ? {'async': true} : null;
if (timeout == 0) { if (timeout == 0) {
completer.resolve(res); resolve(res);
} else { } else {
TimerWrapper.setTimeout(() => { completer.resolve(res); }, timeout); setTimeout(() => { resolve(res); }, timeout);
} }
return completer.promise; return promise;
}; };
} }

View File

@ -9,11 +9,9 @@
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal'; import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {FormBuilder, FormControl} from '@angular/forms'; import {FormBuilder, FormControl} from '@angular/forms';
import {PromiseWrapper} from '../src/facade/promise';
export function main() { export function main() {
function syncValidator(_: any /** TODO #9100 */): any /** TODO #9100 */ { return null; } function syncValidator(_: any /** TODO #9100 */): any /** TODO #9100 */ { return null; }
function asyncValidator(_: any /** TODO #9100 */) { return PromiseWrapper.resolve(null); } function asyncValidator(_: any /** TODO #9100 */) { return Promise.resolve(null); }
describe('Form Builder', () => { describe('Form Builder', () => {
var b: any /** TODO #9100 */; var b: any /** TODO #9100 */;

View File

@ -10,36 +10,36 @@ import {fakeAsync, flushMicrotasks, tick} from '@angular/core/testing';
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {FormArray, FormControl, FormGroup, Validators} from '@angular/forms'; import {FormArray, FormControl, FormGroup, Validators} from '@angular/forms';
import {EventEmitter, ObservableWrapper, TimerWrapper} from '../src/facade/async'; import {EventEmitter} from '../src/facade/async';
import {isPresent} from '../src/facade/lang'; import {isPresent} from '../src/facade/lang';
import {PromiseWrapper} from '../src/facade/promise';
export function main() { export function main() {
function asyncValidator(expected: any /** TODO #9100 */, timeouts = {}) { function asyncValidator(expected: any /** TODO #9100 */, timeouts = {}) {
return (c: any /** TODO #9100 */) => { return (c: any /** TODO #9100 */) => {
var completer = PromiseWrapper.completer(); var resolve: (result: any) => void;
var promise = new Promise(res => { resolve = res; });
var t = isPresent((timeouts as any /** TODO #9100 */)[c.value]) ? var t = isPresent((timeouts as any /** TODO #9100 */)[c.value]) ?
(timeouts as any /** TODO #9100 */)[c.value] : (timeouts as any /** TODO #9100 */)[c.value] :
0; 0;
var res = c.value != expected ? {'async': true} : null; var res = c.value != expected ? {'async': true} : null;
if (t == 0) { if (t == 0) {
completer.resolve(res); resolve(res);
} else { } else {
TimerWrapper.setTimeout(() => { completer.resolve(res); }, t); setTimeout(() => { resolve(res); }, t);
} }
return completer.promise; return promise;
}; };
} }
function asyncValidatorReturningObservable(c: FormControl) { function asyncValidatorReturningObservable(c: FormControl) {
var e = new EventEmitter(); var e = new EventEmitter();
PromiseWrapper.scheduleMicrotask(() => ObservableWrapper.callEmit(e, {'async': true})); Promise.resolve(null).then(() => { e.emit({'async': true}); });
return e; return e;
} }
function otherAsyncValidator() { return PromiseWrapper.resolve({'other': true}); } function otherAsyncValidator() { return Promise.resolve({'other': true}); }
describe('Form Model', () => { describe('Form Model', () => {
describe('FormControl', () => { describe('FormControl', () => {
@ -295,15 +295,16 @@ export function main() {
}); });
it('should fire an event', fakeAsync(() => { it('should fire an event', fakeAsync(() => {
ObservableWrapper.subscribe(
c.valueChanges, (value) => { expect(value).toEqual('newValue'); }); c.valueChanges.subscribe(
{next: (value: any) => { expect(value).toEqual('newValue'); }});
c.updateValue('newValue'); c.updateValue('newValue');
tick(); tick();
})); }));
it('should not fire an event when explicitly specified', fakeAsync(() => { it('should not fire an event when explicitly specified', fakeAsync(() => {
ObservableWrapper.subscribe(c.valueChanges, (value) => { throw 'Should not happen'; }); c.valueChanges.subscribe({next: (value: any) => { throw 'Should not happen'; }});
c.updateValue('newValue', {emitEvent: false}); c.updateValue('newValue', {emitEvent: false});
@ -442,18 +443,22 @@ export function main() {
it('should fire an event after the value has been updated', it('should fire an event after the value has been updated',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ObservableWrapper.subscribe(c.valueChanges, (value) => { c.valueChanges.subscribe({
expect(c.value).toEqual('new'); next: (value: any) => {
expect(value).toEqual('new'); expect(c.value).toEqual('new');
async.done(); expect(value).toEqual('new');
async.done();
}
}); });
c.updateValue('new'); c.updateValue('new');
})); }));
it('should fire an event after the status has been updated to invalid', fakeAsync(() => { it('should fire an event after the status has been updated to invalid', fakeAsync(() => {
ObservableWrapper.subscribe(c.statusChanges, (status) => { c.statusChanges.subscribe({
expect(c.status).toEqual('INVALID'); next: (status: any) => {
expect(status).toEqual('INVALID'); expect(c.status).toEqual('INVALID');
expect(status).toEqual('INVALID');
}
}); });
c.updateValue(''); c.updateValue('');
@ -464,9 +469,9 @@ export function main() {
var c = new FormControl('old', Validators.required, asyncValidator('expected')); var c = new FormControl('old', Validators.required, asyncValidator('expected'));
var log: any[] /** TODO #9100 */ = []; var log: any[] /** TODO #9100 */ = [];
ObservableWrapper.subscribe(c.valueChanges, (value) => log.push(`value: '${value}'`)); c.valueChanges.subscribe({next: (value: any) => log.push(`value: '${value}'`)});
ObservableWrapper.subscribe(
c.statusChanges, (status) => log.push(`status: '${status}'`)); c.statusChanges.subscribe({next: (status: any) => log.push(`status: '${status}'`)});
c.updateValue(''); c.updateValue('');
tick(); tick();
@ -504,9 +509,11 @@ export function main() {
it('should return a cold observable', it('should return a cold observable',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
c.updateValue('will be ignored'); c.updateValue('will be ignored');
ObservableWrapper.subscribe(c.valueChanges, (value) => { c.valueChanges.subscribe({
expect(value).toEqual('new'); next: (value: any) => {
async.done(); expect(value).toEqual('new');
async.done();
}
}); });
c.updateValue('new'); c.updateValue('new');
})); }));
@ -999,10 +1006,12 @@ export function main() {
it('should fire an event after the value has been updated', it('should fire an event after the value has been updated',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ObservableWrapper.subscribe(g.valueChanges, (value) => { g.valueChanges.subscribe({
expect(g.value).toEqual({'one': 'new1', 'two': 'old2'}); next: (value: any) => {
expect(value).toEqual({'one': 'new1', 'two': 'old2'}); expect(g.value).toEqual({'one': 'new1', 'two': 'old2'});
async.done(); expect(value).toEqual({'one': 'new1', 'two': 'old2'});
async.done();
}
}); });
c1.updateValue('new1'); c1.updateValue('new1');
})); }));
@ -1011,12 +1020,14 @@ export function main() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var controlCallbackIsCalled = false; var controlCallbackIsCalled = false;
ObservableWrapper.subscribe(
c1.valueChanges, (value) => { controlCallbackIsCalled = true; });
ObservableWrapper.subscribe(g.valueChanges, (value) => { c1.valueChanges.subscribe({next: (value: any) => { controlCallbackIsCalled = true; }});
expect(controlCallbackIsCalled).toBe(true);
async.done(); g.valueChanges.subscribe({
next: (value: any) => {
expect(controlCallbackIsCalled).toBe(true);
async.done();
}
}); });
c1.updateValue('new1'); c1.updateValue('new1');
@ -1024,9 +1035,11 @@ export function main() {
it('should fire an event when a control is excluded', it('should fire an event when a control is excluded',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ObservableWrapper.subscribe(g.valueChanges, (value) => { g.valueChanges.subscribe({
expect(value).toEqual({'one': 'old1'}); next: (value: any) => {
async.done(); expect(value).toEqual({'one': 'old1'});
async.done();
}
}); });
g.exclude('two'); g.exclude('two');
@ -1036,9 +1049,11 @@ export function main() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
g.exclude('two'); g.exclude('two');
ObservableWrapper.subscribe(g.valueChanges, (value) => { g.valueChanges.subscribe({
expect(value).toEqual({'one': 'old1', 'two': 'old2'}); next: (value: any) => {
async.done(); expect(value).toEqual({'one': 'old1', 'two': 'old2'});
async.done();
}
}); });
g.include('two'); g.include('two');
@ -1048,14 +1063,16 @@ export function main() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var loggedValues: any[] /** TODO #9100 */ = []; var loggedValues: any[] /** TODO #9100 */ = [];
ObservableWrapper.subscribe(g.valueChanges, (value) => { g.valueChanges.subscribe({
loggedValues.push(value); next: (value: any) => {
loggedValues.push(value);
if (loggedValues.length == 2) { if (loggedValues.length == 2) {
expect(loggedValues).toEqual([ expect(loggedValues).toEqual([
{'one': 'new1', 'two': 'old2'}, {'one': 'new1', 'two': 'new2'} {'one': 'new1', 'two': 'old2'}, {'one': 'new1', 'two': 'new2'}
]); ]);
async.done(); async.done();
}
} }
}); });
@ -1075,12 +1092,14 @@ export function main() {
it('should fire a statusChange if child has async validation change', it('should fire a statusChange if child has async validation change',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const loggedValues: string[] = []; const loggedValues: string[] = [];
ObservableWrapper.subscribe(group.statusChanges, (status: string) => { group.statusChanges.subscribe({
loggedValues.push(status); next: (status: string) => {
if (loggedValues.length === 2) { loggedValues.push(status);
expect(loggedValues).toEqual(['PENDING', 'INVALID']); if (loggedValues.length === 2) {
expect(loggedValues).toEqual(['PENDING', 'INVALID']);
}
async.done();
} }
async.done();
}); });
control.updateValue(''); control.updateValue('');
})); }));
@ -1545,10 +1564,12 @@ export function main() {
it('should fire an event after the value has been updated', it('should fire an event after the value has been updated',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ObservableWrapper.subscribe(a.valueChanges, (value) => { a.valueChanges.subscribe({
expect(a.value).toEqual(['new1', 'old2']); next: (value: any) => {
expect(value).toEqual(['new1', 'old2']); expect(a.value).toEqual(['new1', 'old2']);
async.done(); expect(value).toEqual(['new1', 'old2']);
async.done();
}
}); });
c1.updateValue('new1'); c1.updateValue('new1');
})); }));
@ -1557,12 +1578,14 @@ export function main() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var controlCallbackIsCalled = false; var controlCallbackIsCalled = false;
ObservableWrapper.subscribe(
c1.valueChanges, (value) => { controlCallbackIsCalled = true; });
ObservableWrapper.subscribe(a.valueChanges, (value) => { c1.valueChanges.subscribe({next: (value: any) => { controlCallbackIsCalled = true; }});
expect(controlCallbackIsCalled).toBe(true);
async.done(); a.valueChanges.subscribe({
next: (value: any) => {
expect(controlCallbackIsCalled).toBe(true);
async.done();
}
}); });
c1.updateValue('new1'); c1.updateValue('new1');
@ -1570,9 +1593,11 @@ export function main() {
it('should fire an event when a control is removed', it('should fire an event when a control is removed',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ObservableWrapper.subscribe(a.valueChanges, (value) => { a.valueChanges.subscribe({
expect(value).toEqual(['old1']); next: (value: any) => {
async.done(); expect(value).toEqual(['old1']);
async.done();
}
}); });
a.removeAt(1); a.removeAt(1);
@ -1582,9 +1607,11 @@ export function main() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
a.removeAt(1); a.removeAt(1);
ObservableWrapper.subscribe(a.valueChanges, (value) => { a.valueChanges.subscribe({
expect(value).toEqual(['old1', 'old2']); next: (value: any) => {
async.done(); expect(value).toEqual(['old1', 'old2']);
async.done();
}
}); });
a.push(c2); a.push(c2);

View File

@ -15,9 +15,7 @@ import {By} from '@angular/platform-browser/src/dom/debug/by';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {dispatchEvent} from '@angular/platform-browser/testing/browser_util'; import {dispatchEvent} from '@angular/platform-browser/testing/browser_util';
import {ObservableWrapper} from '../src/facade/async';
import {ListWrapper} from '../src/facade/collection'; import {ListWrapper} from '../src/facade/collection';
import {PromiseWrapper} from '../src/facade/promise';
export function main() { export function main() {
describe('reactive forms integration tests', () => { describe('reactive forms integration tests', () => {
@ -85,8 +83,8 @@ export function main() {
input.nativeElement.value = 'updatedValue'; input.nativeElement.value = 'updatedValue';
ObservableWrapper.subscribe(
form.valueChanges, (value) => { throw 'Should not happen'; }); form.valueChanges.subscribe({next: (value) => { throw 'Should not happen'; }});
dispatchEvent(input.nativeElement, 'change'); dispatchEvent(input.nativeElement, 'change');
async.done(); async.done();
@ -894,11 +892,13 @@ export function main() {
expect(input.componentInstance.value).toEqual('!aa!'); expect(input.componentInstance.value).toEqual('!aa!');
input.componentInstance.value = '!bb!'; input.componentInstance.value = '!bb!';
ObservableWrapper.subscribe(input.componentInstance.onInput, (value) => { input.componentInstance.onInput.subscribe({
expect(fixture.debugElement.componentInstance.form.value).toEqual({ next: (value: any) => {
'name': 'bb' expect(fixture.debugElement.componentInstance.form.value).toEqual({
}); 'name': 'bb'
async.done(); });
async.done();
}
}); });
input.componentInstance.dispatchChangeEvent(); input.componentInstance.dispatchChangeEvent();
}); });
@ -1360,7 +1360,6 @@ export function main() {
tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => { tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => {
fixture.debugElement.componentInstance.myGroup = new FormGroup({}); fixture.debugElement.componentInstance.myGroup = new FormGroup({});
;
expect(() => fixture.detectChanges()) expect(() => fixture.detectChanges())
.toThrowError(new RegExp( .toThrowError(new RegExp(
`ngModel cannot be used to register form controls with a parent formGroup directive.`)); `ngModel cannot be used to register form controls with a parent formGroup directive.`));
@ -1475,21 +1474,20 @@ class MyInput implements ControlValueAccessor {
writeValue(value: any /** TODO #9100 */) { this.value = `!${value}!`; } writeValue(value: any /** TODO #9100 */) { this.value = `!${value}!`; }
registerOnChange(fn: any /** TODO #9100 */) { ObservableWrapper.subscribe(this.onInput, fn); } registerOnChange(fn: any /** TODO #9100 */) { this.onInput.subscribe({next: fn}); }
registerOnTouched(fn: any /** TODO #9100 */) {} registerOnTouched(fn: any /** TODO #9100 */) {}
dispatchChangeEvent() { dispatchChangeEvent() { this.onInput.emit(this.value.substring(1, this.value.length - 1)); }
ObservableWrapper.callEmit(this.onInput, this.value.substring(1, this.value.length - 1));
}
} }
function uniqLoginAsyncValidator(expectedValue: string) { function uniqLoginAsyncValidator(expectedValue: string) {
return (c: any /** TODO #9100 */) => { return (c: any /** TODO #9100 */) => {
var completer = PromiseWrapper.completer(); var resolve: (result: any) => void;
var promise = new Promise(res => { resolve = res; });
var res = (c.value == expectedValue) ? null : {'uniqLogin': true}; var res = (c.value == expectedValue) ? null : {'uniqLogin': true};
completer.resolve(res); resolve(res);
return completer.promise; return promise;
}; };
} }

View File

@ -14,8 +14,6 @@ import {FormsModule, NgForm} from '@angular/forms';
import {By} from '@angular/platform-browser/src/dom/debug/by'; import {By} from '@angular/platform-browser/src/dom/debug/by';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {dispatchEvent} from '@angular/platform-browser/testing/browser_util'; import {dispatchEvent} from '@angular/platform-browser/testing/browser_util';
import {ObservableWrapper} from '../src/facade/async';
import {ListWrapper} from '../src/facade/collection'; import {ListWrapper} from '../src/facade/collection';
export function main() { export function main() {
@ -170,10 +168,10 @@ export function main() {
let formValidity: string; let formValidity: string;
let formValue: Object; let formValue: Object;
ObservableWrapper.subscribe(
form.statusChanges, (status: string) => { formValidity = status; });
ObservableWrapper.subscribe(form.valueChanges, (value: string) => { formValue = value; }); form.statusChanges.subscribe({next: (status: string) => { formValidity = status; }});
form.valueChanges.subscribe({next: (value: string) => { formValue = value; }});
tick(); tick();

View File

@ -12,8 +12,7 @@ import {AbstractControl, FormControl, Validators} from '@angular/forms';
import {Observable} from 'rxjs/Observable'; import {Observable} from 'rxjs/Observable';
import {normalizeAsyncValidator} from '../src/directives/normalize_validator'; import {normalizeAsyncValidator} from '../src/directives/normalize_validator';
import {EventEmitter, ObservableWrapper, TimerWrapper} from '../src/facade/async'; import {EventEmitter} from '../src/facade/async';
import {PromiseWrapper} from '../src/facade/promise';
export function main() { export function main() {
function validator(key: string, error: any) { function validator(key: string, error: any) {
@ -133,14 +132,14 @@ export function main() {
return (c: any /** TODO #9100 */) => { return (c: any /** TODO #9100 */) => {
var emitter = new EventEmitter(); var emitter = new EventEmitter();
var res = c.value != expected ? response : null; var res = c.value != expected ? response : null;
Promise.resolve(null).then(() => {
PromiseWrapper.scheduleMicrotask(() => { emitter.emit(res);
ObservableWrapper.callEmit(emitter, res);
// this is required because of a bug in ObservableWrapper // this is required because of a bug in ObservableWrapper
// where callComplete can fire before callEmit // where callComplete can fire before callEmit
// remove this one the bug is fixed // remove this one the bug is fixed
TimerWrapper.setTimeout(() => { ObservableWrapper.callComplete(emitter); }, 0); setTimeout(() => { emitter.complete(); }, 0);
}); });
return emitter; return emitter;
}; };
} }

Some files were not shown because too many files have changed in this diff Show More