From aec51d616b079308bc4480924e81be4f22ae4215 Mon Sep 17 00:00:00 2001 From: Tobias Bosch Date: Wed, 20 May 2015 17:19:46 -0700 Subject: [PATCH] =?UTF-8?q?refactor(ts'ify):=20ts=E2=80=99ify=20mocks,=20d?= =?UTF-8?q?irectives=20and=20test=5Flib?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Also cleans up global types. --- modules/angular2/{angular2.js => angular2.ts} | 0 modules/angular2/angular2_sfx.dart | 2 + modules/angular2/angular2_sfx.es6 | 2 +- .../{annotations.js => annotations.ts} | 6 +- modules/angular2/{core.js => core.ts} | 1 - .../{di_annotations.js => di_annotations.ts} | 1 - .../angular2/{di_errors.js => di_errors.ts} | 1 - .../angular2/{directives.js => directives.ts} | 13 +- modules/angular2/globals.d.ts | 12 +- modules/angular2/{pipes.js => pipes.ts} | 0 .../src/change_detection/parser/lexer.ts | 8 +- .../src/change_detection/parser/parser.ts | 1 - .../pipes/iterable_changes.ts | 1 - .../src/core/compiler/element_binder.ts | 2 +- .../src/core/compiler/element_injector.ts | 2 +- modules/angular2/src/core/compiler/view.ts | 2 +- modules/angular2/src/core/zone/ng_zone.ts | 2 + .../src/directives/{class.js => class.ts} | 21 +- .../src/directives/{ng_for.js => ng_for.ts} | 30 +- .../src/directives/{ng_if.js => ng_if.ts} | 20 +- ...{ng_non_bindable.js => ng_non_bindable.ts} | 7 +- .../directives/{ng_switch.js => ng_switch.ts} | 54 +-- modules/angular2/src/facade/async.ts | 2 +- modules/angular2/src/facade/browser.ts | 2 +- modules/angular2/src/facade/collection.ts | 2 +- modules/angular2/src/facade/lang.ts | 35 +- modules/angular2/src/mock/ng_zone_mock.js | 15 - modules/angular2/src/mock/ng_zone_mock.ts | 9 + ...lver_mock.js => template_resolver_mock.ts} | 24 +- .../src/mock/{xhr_mock.js => xhr_mock.ts} | 16 +- .../render/dom/compiler/compile_element.ts | 9 +- .../angular2/src/render/dom/dom_renderer.ts | 2 +- .../src/render/dom/events/hammer_gestures.ts | 4 +- .../src/render/dom/shadow_dom/shadow_css.ts | 3 +- .../src/render/dom/shadow_dom/util.ts | 2 +- modules/angular2/src/render/dom/view/view.ts | 2 +- .../{benchmark_util.js => benchmark_util.ts} | 14 +- modules/angular2/src/test_lib/e2e_util.dart | 2 + .../test_lib/{e2e_util.es6 => e2e_util.ts} | 20 +- .../{fake_async.es6 => fake_async.ts} | 48 +-- .../{lang_utils.es6 => lang_utils.ts} | 2 +- modules/angular2/src/test_lib/perf_util.es6 | 5 +- modules/angular2/src/test_lib/perf_utils.dart | 2 + .../src/test_lib/{test_bed.js => test_bed.ts} | 47 +-- .../{test_injector.js => test_injector.ts} | 59 +-- modules/angular2/src/test_lib/test_lib.es6 | 358 ------------------ modules/angular2/src/test_lib/test_lib.ts | 352 +++++++++++++++++ .../src/test_lib/{utils.js => utils.ts} | 26 +- modules/angular2/{test.js => test.ts} | 0 modules/angular2/{test_lib.js => test_lib.ts} | 0 modules/angular2/tsd.json | 31 +- 51 files changed, 610 insertions(+), 671 deletions(-) rename modules/angular2/{angular2.js => angular2.ts} (100%) create mode 100644 modules/angular2/angular2_sfx.dart rename modules/angular2/{annotations.js => annotations.ts} (69%) rename modules/angular2/{core.js => core.ts} (99%) rename modules/angular2/{di_annotations.js => di_annotations.ts} (99%) rename modules/angular2/{di_errors.js => di_errors.ts} (98%) rename modules/angular2/{directives.js => directives.ts} (83%) rename modules/angular2/{pipes.js => pipes.ts} (100%) rename modules/angular2/src/directives/{class.js => class.ts} (56%) rename modules/angular2/src/directives/{ng_for.js => ng_for.ts} (80%) rename modules/angular2/src/directives/{ng_if.js => ng_if.ts} (73%) rename modules/angular2/src/directives/{ng_non_bindable.js => ng_non_bindable.ts} (79%) rename modules/angular2/src/directives/{ng_switch.js => ng_switch.ts} (84%) delete mode 100644 modules/angular2/src/mock/ng_zone_mock.js create mode 100644 modules/angular2/src/mock/ng_zone_mock.ts rename modules/angular2/src/mock/{template_resolver_mock.js => template_resolver_mock.ts} (85%) rename modules/angular2/src/mock/{xhr_mock.js => xhr_mock.ts} (87%) rename modules/angular2/src/test_lib/{benchmark_util.js => benchmark_util.ts} (78%) create mode 100644 modules/angular2/src/test_lib/e2e_util.dart rename modules/angular2/src/test_lib/{e2e_util.es6 => e2e_util.ts} (55%) rename modules/angular2/src/test_lib/{fake_async.es6 => fake_async.ts} (72%) rename modules/angular2/src/test_lib/{lang_utils.es6 => lang_utils.ts} (71%) create mode 100644 modules/angular2/src/test_lib/perf_utils.dart rename modules/angular2/src/test_lib/{test_bed.js => test_bed.ts} (78%) rename modules/angular2/src/test_lib/{test_injector.js => test_injector.ts} (78%) delete mode 100644 modules/angular2/src/test_lib/test_lib.es6 create mode 100644 modules/angular2/src/test_lib/test_lib.ts rename modules/angular2/src/test_lib/{utils.js => utils.ts} (71%) rename modules/angular2/{test.js => test.ts} (100%) rename modules/angular2/{test_lib.js => test_lib.ts} (100%) diff --git a/modules/angular2/angular2.js b/modules/angular2/angular2.ts similarity index 100% rename from modules/angular2/angular2.js rename to modules/angular2/angular2.ts diff --git a/modules/angular2/angular2_sfx.dart b/modules/angular2/angular2_sfx.dart new file mode 100644 index 0000000000..37273e309d --- /dev/null +++ b/modules/angular2/angular2_sfx.dart @@ -0,0 +1,2 @@ +library angular2.sfx; +// empty as we don't have a version for Dart \ No newline at end of file diff --git a/modules/angular2/angular2_sfx.es6 b/modules/angular2/angular2_sfx.es6 index f9a8bf972f..35f5d3914a 100644 --- a/modules/angular2/angular2_sfx.es6 +++ b/modules/angular2/angular2_sfx.es6 @@ -1,5 +1,5 @@ import * as angular from './angular2'; -// the router should have its own SFX bundle +// the router should have its own SFX bundle // But currently the module arithemtic 'angular2/router_sfx - angular2/angular2', // is not support by system builder. import * as router from './router'; diff --git a/modules/angular2/annotations.js b/modules/angular2/annotations.ts similarity index 69% rename from modules/angular2/annotations.js rename to modules/angular2/annotations.ts index 8b28ec370e..16519190da 100644 --- a/modules/angular2/annotations.js +++ b/modules/angular2/annotations.ts @@ -3,8 +3,10 @@ * @public * @description * - * Annotations provide the additional information that Angular requires in order to run your application. This module - * contains {@link Component}, {@link Directive}, and {@link View} annotations, as well as {@link Parent} and {@link Ancestor} annotations that are + * Annotations provide the additional information that Angular requires in order to run your + * application. This module + * contains {@link Component}, {@link Directive}, and {@link View} annotations, as well as {@link + * Parent} and {@link Ancestor} annotations that are * used by Angular to resolve dependencies. * */ diff --git a/modules/angular2/core.js b/modules/angular2/core.ts similarity index 99% rename from modules/angular2/core.js rename to modules/angular2/core.ts index 518edd0518..72059d0fc0 100644 --- a/modules/angular2/core.js +++ b/modules/angular2/core.ts @@ -23,4 +23,3 @@ export * from './src/core/compiler/dynamic_component_loader'; export {ViewRef, ProtoViewRef} from './src/core/compiler/view_ref'; export {ViewContainerRef} from './src/core/compiler/view_container_ref'; export {ElementRef} from './src/core/compiler/element_ref'; - diff --git a/modules/angular2/di_annotations.js b/modules/angular2/di_annotations.ts similarity index 99% rename from modules/angular2/di_annotations.js rename to modules/angular2/di_annotations.ts index 32d7df5c2b..186676b48b 100644 --- a/modules/angular2/di_annotations.js +++ b/modules/angular2/di_annotations.ts @@ -4,4 +4,3 @@ * @description * Annotations which control how the dependencies are resolved by the {@link Injector}. */ - diff --git a/modules/angular2/di_errors.js b/modules/angular2/di_errors.ts similarity index 98% rename from modules/angular2/di_errors.js rename to modules/angular2/di_errors.ts index 807936b10f..589f7b7f47 100644 --- a/modules/angular2/di_errors.js +++ b/modules/angular2/di_errors.ts @@ -4,4 +4,3 @@ * @description * Errors thrown by the {@link Injector}. */ - diff --git a/modules/angular2/directives.js b/modules/angular2/directives.ts similarity index 83% rename from modules/angular2/directives.js rename to modules/angular2/directives.ts index 3db81eebc9..580faafe32 100644 --- a/modules/angular2/directives.js +++ b/modules/angular2/directives.ts @@ -5,7 +5,7 @@ * Common directives shipped with Angular. */ -import {CONST_EXPR} from './src/facade/lang'; +import {CONST_EXPR, Type} from './src/facade/lang'; import {NgFor} from './src/directives/ng_for'; import {NgIf} from './src/directives/ng_if'; import {NgNonBindable} from './src/directives/ng_non_bindable'; @@ -18,9 +18,11 @@ export * from './src/directives/ng_non_bindable'; export * from './src/directives/ng_switch'; /** - * A collection of the Angular core directives that are likely to be used in each and every Angular application. + * A collection of the Angular core directives that are likely to be used in each and every Angular + * application. * - * This collection can be used to quickly enumerate all the built-in directives in the `@View` annotation. For example, + * This collection can be used to quickly enumerate all the built-in directives in the `@View` + * annotation. For example, * instead of writing: * * ``` @@ -57,6 +59,5 @@ export * from './src/directives/ng_switch'; * ``` * */ -export const coreDirectives:List = CONST_EXPR([ - NgFor, NgIf, NgNonBindable, NgSwitch, NgSwitchWhen, NgSwitchDefault -]); +export const coreDirectives: List = + CONST_EXPR([NgFor, NgIf, NgNonBindable, NgSwitch, NgSwitchWhen, NgSwitchDefault]); diff --git a/modules/angular2/globals.d.ts b/modules/angular2/globals.d.ts index f544935e04..599b9c31c8 100644 --- a/modules/angular2/globals.d.ts +++ b/modules/angular2/globals.d.ts @@ -2,18 +2,16 @@ * This file contains declarations of global symbols we reference in our code */ -/// /// declare var assert: any; -declare var global: Window; declare type int = number; interface List extends Array {} interface StringMap extends Object {} -interface Window { +interface BrowserNodeGlobal { Object: typeof Object; Array: typeof Array; Map: typeof Map; @@ -22,10 +20,12 @@ interface Window { RegExp: typeof RegExp; JSON: typeof JSON; Math: typeof Math; - assert: typeof assert; - gc(): void; + assert(condition): void; Reflect: any; zone: Zone; - Hammer: HammerStatic; getAngularTestability: Function; + setTimeout: Function; + clearTimeout: Function; + setInterval: Function; + clearInterval: Function; } diff --git a/modules/angular2/pipes.js b/modules/angular2/pipes.ts similarity index 100% rename from modules/angular2/pipes.js rename to modules/angular2/pipes.ts diff --git a/modules/angular2/src/change_detection/parser/lexer.ts b/modules/angular2/src/change_detection/parser/lexer.ts index c45745d40d..0a8784572e 100644 --- a/modules/angular2/src/change_detection/parser/lexer.ts +++ b/modules/angular2/src/change_detection/parser/lexer.ts @@ -1,12 +1,6 @@ import {Injectable} from 'angular2/src/di/decorators'; import {List, ListWrapper, SetWrapper} from "angular2/src/facade/collection"; -import { - int, - NumberWrapper, - StringJoiner, - StringWrapper, - BaseException -} from "angular2/src/facade/lang"; +import {NumberWrapper, StringJoiner, StringWrapper, BaseException} from "angular2/src/facade/lang"; export const TOKEN_TYPE_CHARACTER = 1; export const TOKEN_TYPE_IDENTIFIER = 2; diff --git a/modules/angular2/src/change_detection/parser/parser.ts b/modules/angular2/src/change_detection/parser/parser.ts index 2998da0458..edded16539 100644 --- a/modules/angular2/src/change_detection/parser/parser.ts +++ b/modules/angular2/src/change_detection/parser/parser.ts @@ -1,6 +1,5 @@ import {Injectable} from 'angular2/src/di/decorators'; import { - int, isBlank, isPresent, BaseException, diff --git a/modules/angular2/src/change_detection/pipes/iterable_changes.ts b/modules/angular2/src/change_detection/pipes/iterable_changes.ts index 996322560a..dd8d65d2d2 100644 --- a/modules/angular2/src/change_detection/pipes/iterable_changes.ts +++ b/modules/angular2/src/change_detection/pipes/iterable_changes.ts @@ -7,7 +7,6 @@ import { } from 'angular2/src/facade/collection'; import { - int, isBlank, isPresent, stringify, diff --git a/modules/angular2/src/core/compiler/element_binder.ts b/modules/angular2/src/core/compiler/element_binder.ts index 6d73f557db..7038d39554 100644 --- a/modules/angular2/src/core/compiler/element_binder.ts +++ b/modules/angular2/src/core/compiler/element_binder.ts @@ -1,5 +1,5 @@ import {AST} from 'angular2/change_detection'; -import {int, isBlank, isPresent, BaseException} from 'angular2/src/facade/lang'; +import {isBlank, isPresent, BaseException} from 'angular2/src/facade/lang'; import * as eiModule from './element_injector'; import {DirectiveBinding} from './element_injector'; import {List, StringMap} from 'angular2/src/facade/collection'; diff --git a/modules/angular2/src/core/compiler/element_injector.ts b/modules/angular2/src/core/compiler/element_injector.ts index 9955420eb7..179f2890cc 100644 --- a/modules/angular2/src/core/compiler/element_injector.ts +++ b/modules/angular2/src/core/compiler/element_injector.ts @@ -1,4 +1,4 @@ -import {isPresent, isBlank, Type, int, BaseException, stringify} from 'angular2/src/facade/lang'; +import {isPresent, isBlank, Type, BaseException, stringify} from 'angular2/src/facade/lang'; import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; import {List, ListWrapper, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import { diff --git a/modules/angular2/src/core/compiler/view.ts b/modules/angular2/src/core/compiler/view.ts index 336b66395f..d921224481 100644 --- a/modules/angular2/src/core/compiler/view.ts +++ b/modules/angular2/src/core/compiler/view.ts @@ -18,7 +18,7 @@ import { DirectiveBinding } from './element_injector'; import {ElementBinder} from './element_binder'; -import {int, isPresent, isBlank, BaseException} from 'angular2/src/facade/lang'; +import {isPresent, isBlank, BaseException} from 'angular2/src/facade/lang'; import * as renderApi from 'angular2/src/render/api'; import {EventDispatcher} from 'angular2/src/render/api'; diff --git a/modules/angular2/src/core/zone/ng_zone.ts b/modules/angular2/src/core/zone/ng_zone.ts index 5c4ace24e7..1b5c800f5c 100644 --- a/modules/angular2/src/core/zone/ng_zone.ts +++ b/modules/angular2/src/core/zone/ng_zone.ts @@ -1,6 +1,8 @@ import {List, ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {normalizeBlank, isPresent, global} from 'angular2/src/facade/lang'; +export interface NgZoneZone extends Zone { _innerZone: boolean; } + /** * A wrapper around zones that lets you schedule tasks after it has executed a task. * diff --git a/modules/angular2/src/directives/class.js b/modules/angular2/src/directives/class.ts similarity index 56% rename from modules/angular2/src/directives/class.js rename to modules/angular2/src/directives/class.ts index 18f69c3f7e..87517a3f70 100644 --- a/modules/angular2/src/directives/class.js +++ b/modules/angular2/src/directives/class.ts @@ -1,21 +1,15 @@ -import {Directive} from 'angular2/src/core/annotations_impl/annotations'; +import {Directive} from 'angular2/annotations'; +import {ElementRef} from 'angular2/core'; + import {isPresent} from 'angular2/src/facade/lang'; import {DOM} from 'angular2/src/dom/dom_adapter'; -import {ElementRef} from 'angular2/src/core/compiler/element_ref'; -@Directive({ - selector: '[class]', - properties: { - 'iterableChanges': 'class | keyValDiff' - } -}) +@Directive({selector: '[class]', properties: {'iterableChanges': 'class | keyValDiff'}}) export class CSSClass { _domEl; - constructor(ngEl: ElementRef) { - this._domEl = ngEl.domElement; - } + constructor(ngEl: ElementRef) { this._domEl = ngEl.domElement; } - _toggleClass(className, enabled):void { + _toggleClass(className, enabled): void { if (enabled) { DOM.addClass(this._domEl, className); } else { @@ -26,7 +20,8 @@ export class CSSClass { set iterableChanges(changes) { if (isPresent(changes)) { changes.forEachAddedItem((record) => { this._toggleClass(record.key, record.currentValue); }); - changes.forEachChangedItem((record) => { this._toggleClass(record.key, record.currentValue); }); + changes.forEachChangedItem( + (record) => { this._toggleClass(record.key, record.currentValue); }); changes.forEachRemovedItem((record) => { if (record.previousValue) { DOM.removeClass(this._domEl, record.key); diff --git a/modules/angular2/src/directives/ng_for.js b/modules/angular2/src/directives/ng_for.ts similarity index 80% rename from modules/angular2/src/directives/ng_for.js rename to modules/angular2/src/directives/ng_for.ts index d72fc2e6f5..eafe19a230 100644 --- a/modules/angular2/src/directives/ng_for.js +++ b/modules/angular2/src/directives/ng_for.ts @@ -1,6 +1,5 @@ -import {Directive} from 'angular2/src/core/annotations_impl/annotations'; -import {ViewContainerRef} from 'angular2/src/core/compiler/view_container_ref'; -import {ViewRef, ProtoViewRef} from 'angular2/src/core/compiler/view_ref'; +import {Directive} from 'angular2/annotations'; +import {ViewContainerRef, ViewRef, ProtoViewRef} from 'angular2/core'; import {isPresent, isBlank} from 'angular2/src/facade/lang'; import {ListWrapper} from 'angular2/src/facade/collection'; @@ -36,16 +35,12 @@ import {ListWrapper} from 'angular2/src/facade/collection'; * * @exportedAs angular2/directives */ -@Directive({ - selector: '[ng-for][ng-for-of]', - properties: { - 'iterableChanges': 'ngForOf | iterableDiff' - } -}) -export class NgFor { +@Directive( + {selector: '[ng-for][ng-for-of]', properties: {'iterableChanges': 'ngForOf | iterableDiff'}}) +export class NgFor { viewContainer: ViewContainerRef; protoViewRef: ProtoViewRef; - constructor(viewContainer:ViewContainerRef, protoViewRef: ProtoViewRef) { + constructor(viewContainer: ViewContainerRef, protoViewRef: ProtoViewRef) { this.viewContainer = viewContainer; this.protoViewRef = protoViewRef; } @@ -59,19 +54,16 @@ export class NgFor { // TODO(rado): check if change detection can produce a change record that is // easier to consume than current. var recordViewTuples = []; - changes.forEachRemovedItem( - (removedRecord) => ListWrapper.push(recordViewTuples, new RecordViewTuple(removedRecord, null)) - ); + changes.forEachRemovedItem((removedRecord) => ListWrapper.push( + recordViewTuples, new RecordViewTuple(removedRecord, null))); - changes.forEachMovedItem( - (movedRecord) => ListWrapper.push(recordViewTuples, new RecordViewTuple(movedRecord, null)) - ); + changes.forEachMovedItem((movedRecord) => ListWrapper.push( + recordViewTuples, new RecordViewTuple(movedRecord, null))); var insertTuples = NgFor.bulkRemove(recordViewTuples, this.viewContainer); changes.forEachAddedItem( - (addedRecord) => ListWrapper.push(insertTuples, new RecordViewTuple(addedRecord, null)) - ); + (addedRecord) => ListWrapper.push(insertTuples, new RecordViewTuple(addedRecord, null))); NgFor.bulkInsert(insertTuples, this.viewContainer, this.protoViewRef); diff --git a/modules/angular2/src/directives/ng_if.js b/modules/angular2/src/directives/ng_if.ts similarity index 73% rename from modules/angular2/src/directives/ng_if.js rename to modules/angular2/src/directives/ng_if.ts index dcf71365de..c132e9ddb1 100644 --- a/modules/angular2/src/directives/ng_if.js +++ b/modules/angular2/src/directives/ng_if.ts @@ -1,19 +1,20 @@ -import {Directive} from 'angular2/src/core/annotations_impl/annotations'; -import {ViewContainerRef} from 'angular2/src/core/compiler/view_container_ref'; -import {ProtoViewRef} from 'angular2/src/core/compiler/view_ref'; +import {Directive} from 'angular2/annotations'; +import {ViewContainerRef, ProtoViewRef} from 'angular2/core'; import {isBlank} from 'angular2/src/facade/lang'; /** * Removes or recreates a portion of the DOM tree based on an {expression}. * - * If the expression assigned to `if` evaluates to a false value then the element is removed from the + * If the expression assigned to `if` evaluates to a false value then the element is removed from + * the * DOM, otherwise a clone of the element is reinserted into the DOM. * * # Example: * * ``` *
- * + * * {{errorCount}} errors detected *
* ``` @@ -26,18 +27,13 @@ import {isBlank} from 'angular2/src/facade/lang'; * * @exportedAs angular2/directives */ -@Directive({ - selector: '[ng-if]', - properties: { - 'ngIf': 'ngIf' - } -}) +@Directive({selector: '[ng-if]', properties: {'ngIf': 'ngIf'}}) export class NgIf { viewContainer: ViewContainerRef; protoViewRef: ProtoViewRef; prevCondition: boolean; - constructor(viewContainer: ViewContainerRef, protoViewRef:ProtoViewRef) { + constructor(viewContainer: ViewContainerRef, protoViewRef: ProtoViewRef) { this.viewContainer = viewContainer; this.prevCondition = null; this.protoViewRef = protoViewRef; diff --git a/modules/angular2/src/directives/ng_non_bindable.js b/modules/angular2/src/directives/ng_non_bindable.ts similarity index 79% rename from modules/angular2/src/directives/ng_non_bindable.js rename to modules/angular2/src/directives/ng_non_bindable.ts index 5610ad8d27..718f1a3a21 100644 --- a/modules/angular2/src/directives/ng_non_bindable.js +++ b/modules/angular2/src/directives/ng_non_bindable.ts @@ -1,4 +1,4 @@ -import {Directive} from 'angular2/src/core/annotations_impl/annotations'; +import {Directive} from 'angular2/annotations'; /** * The `NgNonBindable` directive tells Angular not to compile or bind the contents of the current @@ -15,9 +15,6 @@ import {Directive} from 'angular2/src/core/annotations_impl/annotations'; * * @exportedAs angular2/directives */ -@Directive({ - selector: '[ng-non-bindable]', - compileChildren: false -}) +@Directive({selector: '[ng-non-bindable]', compileChildren: false}) export class NgNonBindable { } diff --git a/modules/angular2/src/directives/ng_switch.js b/modules/angular2/src/directives/ng_switch.ts similarity index 84% rename from modules/angular2/src/directives/ng_switch.js rename to modules/angular2/src/directives/ng_switch.ts index 8d3f2440fc..03c6bb1660 100644 --- a/modules/angular2/src/directives/ng_switch.js +++ b/modules/angular2/src/directives/ng_switch.ts @@ -1,11 +1,9 @@ -import {Directive} from 'angular2/src/core/annotations_impl/annotations'; -import {ViewContainerRef} from 'angular2/src/core/compiler/view_container_ref'; -import {ProtoViewRef} from 'angular2/src/core/compiler/view_ref'; +import {Directive, Parent} from 'angular2/annotations'; +import {ViewContainerRef, ProtoViewRef} from 'angular2/core'; import {isPresent, isBlank, normalizeBlank} from 'angular2/src/facade/lang'; import {ListWrapper, List, MapWrapper, Map} from 'angular2/src/facade/collection'; -import {Parent} from 'angular2/src/core/annotations_impl/visibility'; -class SwitchView { +export class SwitchView { _viewContainerRef: ViewContainerRef; _protoViewRef: ProtoViewRef; @@ -14,13 +12,9 @@ class SwitchView { this._viewContainerRef = viewContainerRef; } - create() { - this._viewContainerRef.create(this._protoViewRef); - } + create() { this._viewContainerRef.create(this._protoViewRef); } - destroy() { - this._viewContainerRef.clear(); - } + destroy() { this._viewContainerRef.clear(); } } /** @@ -50,16 +44,11 @@ class SwitchView { * * @exportedAs angular2/directives */ -@Directive({ - selector: '[ng-switch]', - properties: { - 'ngSwitch': 'ngSwitch' - } -}) +@Directive({selector: '[ng-switch]', properties: {'ngSwitch': 'ngSwitch'}}) export class NgSwitch { _switchValue: any; _useDefault: boolean; - _valueViews: Map; + _valueViews: Map>; _activeViews: List; constructor() { @@ -84,7 +73,7 @@ export class NgSwitch { this._switchValue = value; } - _onWhenValueChanged(oldWhen, newWhen, view: SwitchView):void { + _onWhenValueChanged(oldWhen, newWhen, view: SwitchView): void { this._deregisterView(oldWhen, view); this._registerView(newWhen, view); @@ -107,7 +96,7 @@ export class NgSwitch { } } - _emptyAllActiveViews():void { + _emptyAllActiveViews(): void { var activeContainers = this._activeViews; for (var i = 0; i < activeContainers.length; i++) { activeContainers[i].destroy(); @@ -115,7 +104,7 @@ export class NgSwitch { this._activeViews = ListWrapper.create(); } - _activateViews(views: List):void { + _activateViews(views: List): void { // TODO(vicb): assert(this._activeViews.length === 0); if (isPresent(views)) { for (var i = 0; i < views.length; i++) { @@ -134,7 +123,7 @@ export class NgSwitch { ListWrapper.push(views, view); } - _deregisterView(value, view: SwitchView):void { + _deregisterView(value, view: SwitchView): void { // `_whenDefault` is used a marker for non-registered whens if (value == _whenDefault) return; var views = MapWrapper.get(this._valueViews, value); @@ -164,27 +153,21 @@ export class NgSwitch { * * @exportedAs angular2/directives */ -@Directive({ - selector: '[ng-switch-when]', - properties: { - 'ngSwitchWhen' : 'ngSwitchWhen' - } -}) +@Directive({selector: '[ng-switch-when]', properties: {'ngSwitchWhen': 'ngSwitchWhen'}}) export class NgSwitchWhen { _value: any; _switch: NgSwitch; _view: SwitchView; - constructor(viewContainer: ViewContainerRef, protoViewRef: ProtoViewRef, @Parent() sswitch: NgSwitch) { + constructor(viewContainer: ViewContainerRef, protoViewRef: ProtoViewRef, + @Parent() sswitch: NgSwitch) { // `_whenDefault` is used as a marker for a not yet initialized value this._value = _whenDefault; this._switch = sswitch; this._view = new SwitchView(viewContainer, protoViewRef); } - onDestroy() { - this._switch - } + onDestroy() { this._switch } set ngSwitchWhen(value) { this._switch._onWhenValueChanged(this._value, value, this._view); @@ -206,11 +189,10 @@ export class NgSwitchWhen { * * @exportedAs angular2/directives */ -@Directive({ - selector: '[ng-switch-default]' -}) +@Directive({selector: '[ng-switch-default]'}) export class NgSwitchDefault { - constructor(viewContainer: ViewContainerRef, protoViewRef: ProtoViewRef, @Parent() sswitch: NgSwitch) { + constructor(viewContainer: ViewContainerRef, protoViewRef: ProtoViewRef, + @Parent() sswitch: NgSwitch) { sswitch._registerView(_whenDefault, new SwitchView(viewContainer, protoViewRef)); } } diff --git a/modules/angular2/src/facade/async.ts b/modules/angular2/src/facade/async.ts index e26c069626..a81ccfa4fd 100644 --- a/modules/angular2/src/facade/async.ts +++ b/modules/angular2/src/facade/async.ts @@ -1,7 +1,7 @@ /// /// -import {int, global, isPresent} from 'angular2/src/facade/lang'; +import {global, isPresent} from 'angular2/src/facade/lang'; import {List} from 'angular2/src/facade/collection'; import * as Rx from 'rx'; diff --git a/modules/angular2/src/facade/browser.ts b/modules/angular2/src/facade/browser.ts index 51ef45ef2b..8c69d7f478 100644 --- a/modules/angular2/src/facade/browser.ts +++ b/modules/angular2/src/facade/browser.ts @@ -6,7 +6,7 @@ var win = window; export {win as window}; export var document = window.document; export var location = window.location; -export var gc = window.gc ? () => window.gc() : () => null; +export var gc = window['gc'] ? () => window['gc']() : () => null; export const Event = Event; export const MouseEvent = MouseEvent; export const KeyboardEvent = KeyboardEvent; diff --git a/modules/angular2/src/facade/collection.ts b/modules/angular2/src/facade/collection.ts index a574016919..47659c5755 100644 --- a/modules/angular2/src/facade/collection.ts +++ b/modules/angular2/src/facade/collection.ts @@ -1,4 +1,4 @@ -import {int, isJsObject, global} from 'angular2/src/facade/lang'; +import {isJsObject, global} from 'angular2/src/facade/lang'; export var List = global.Array; export var Map = global.Map; diff --git a/modules/angular2/src/facade/lang.ts b/modules/angular2/src/facade/lang.ts index 56e8f9926f..7ce9e27ec9 100644 --- a/modules/angular2/src/facade/lang.ts +++ b/modules/angular2/src/facade/lang.ts @@ -1,4 +1,4 @@ -var _global = typeof window === 'undefined' ? global : window; +var _global: BrowserNodeGlobal = (typeof window === 'undefined' ? global : window); export {_global as global}; export var Type = Function; @@ -19,23 +19,20 @@ export class BaseException extends Error { export var Math = _global.Math; export var Date = _global.Date; -var assertionsEnabled_ = typeof assert !== 'undefined'; - -var int; -// global assert support, as Dart has it... -// TODO: `assert` calls need to be removed in production code! -if (assertionsEnabled_) { - _global.assert = assert; - // `int` is not a valid JS type - int = assert.define('int', - function(value) { return typeof value === 'number' && value % 1 === 0; }); -} else { - int = {}; - _global.assert = function() {}; +var assertionsEnabled_ = typeof _global['assert'] !== 'undefined'; +export function assertionsEnabled(): boolean { + return assertionsEnabled_; } -export {int}; - +// TODO: remove calls to assert in production environment +// Note: Can't just export this and import in in other files +// as `assert` is a reserved keyword in Dart +_global.assert = + function assert(condition) { + if (assertionsEnabled_) { + _global['assert'].call(condition); + } + } // This function is needed only to properly support Dart's const expressions // see https://github.com/angular/ts2dart/pull/151 for more info export function CONST_EXPR(expr: T): T { @@ -114,7 +111,7 @@ export class StringWrapper { } static replaceAllMapped(s: string, from: RegExp, cb: Function): string { - return s.replace(from, function(...matches) { + return s.replace(from, function(... matches) { // Remove offset & string from the result array matches.splice(-2, 2); // The callback receives match, p1, ..., pn @@ -232,10 +229,6 @@ export function isJsObject(o): boolean { return o !== null && (typeof o === "function" || typeof o === "object"); } -export function assertionsEnabled(): boolean { - return assertionsEnabled_; -} - export function print(obj) { if (obj instanceof Error) { console.log(obj.stack); diff --git a/modules/angular2/src/mock/ng_zone_mock.js b/modules/angular2/src/mock/ng_zone_mock.js deleted file mode 100644 index b0b1660d35..0000000000 --- a/modules/angular2/src/mock/ng_zone_mock.js +++ /dev/null @@ -1,15 +0,0 @@ -import {NgZone} from 'angular2/src/core/zone/ng_zone'; - -export class MockNgZone extends NgZone { - constructor() { - super({enableLongStackTrace: false}); - } - - run(fn) { - return fn(); - } - - runOutsideAngular(fn) { - return fn(); - } -} diff --git a/modules/angular2/src/mock/ng_zone_mock.ts b/modules/angular2/src/mock/ng_zone_mock.ts new file mode 100644 index 0000000000..c2ddbf42b7 --- /dev/null +++ b/modules/angular2/src/mock/ng_zone_mock.ts @@ -0,0 +1,9 @@ +import {NgZone} from 'angular2/src/core/zone/ng_zone'; + +export class MockNgZone extends NgZone { + constructor() { super({enableLongStackTrace: false}); } + + run(fn) { return fn(); } + + runOutsideAngular(fn) { return fn(); } +} diff --git a/modules/angular2/src/mock/template_resolver_mock.js b/modules/angular2/src/mock/template_resolver_mock.ts similarity index 85% rename from modules/angular2/src/mock/template_resolver_mock.js rename to modules/angular2/src/mock/template_resolver_mock.ts index 51862abcca..c50b52a752 100644 --- a/modules/angular2/src/mock/template_resolver_mock.js +++ b/modules/angular2/src/mock/template_resolver_mock.ts @@ -8,7 +8,7 @@ export class MockTemplateResolver extends TemplateResolver { _templates: Map; _inlineTemplates: Map; _templateCache: Map; - _directiveOverrides: Map; + _directiveOverrides: Map>; constructor() { super(); @@ -62,7 +62,8 @@ export class MockTemplateResolver extends TemplateResolver { /** * Returns the {@link View} for a component: - * - Set the {@link View} to the overridden template when it exists or fallback to the default `TemplateResolver`, + * - Set the {@link View} to the overridden template when it exists or fallback to the default + * `TemplateResolver`, * see `setView`. * - Override the directives, see `overrideTemplateDirective`. * - Override the @View definition, see `setInlineTemplate`. @@ -91,24 +92,18 @@ export class MockTemplateResolver extends TemplateResolver { MapWrapper.forEach(overrides, (to, from) => { var srcIndex = directives.indexOf(from); if (srcIndex == -1) { - throw new BaseException(`Overriden directive ${stringify(from)} not found in the template of ${stringify(component)}`); + throw new BaseException( + `Overriden directive ${stringify(from)} not found in the template of ${stringify(component)}`); } directives[srcIndex] = to; }); - view = new View({ - template: view.template, - templateUrl: view.templateUrl, - directives: directives - }); + view = new View( + {template: view.template, templateUrl: view.templateUrl, directives: directives}); } var inlineTemplate = MapWrapper.get(this._inlineTemplates, component); if (isPresent(inlineTemplate)) { - view = new View({ - template: inlineTemplate, - templateUrl: null, - directives: view.directives - }); + view = new View({template: inlineTemplate, templateUrl: null, directives: view.directives}); } MapWrapper.set(this._templateCache, component, view); @@ -127,7 +122,8 @@ export class MockTemplateResolver extends TemplateResolver { var cached = MapWrapper.get(this._templateCache, component); if (isPresent(cached)) { - throw new BaseException(`The component ${stringify(component)} has already been compiled, its configuration can not be changed`); + throw new BaseException( + `The component ${stringify(component)} has already been compiled, its configuration can not be changed`); } } } diff --git a/modules/angular2/src/mock/xhr_mock.js b/modules/angular2/src/mock/xhr_mock.ts similarity index 87% rename from modules/angular2/src/mock/xhr_mock.js rename to modules/angular2/src/mock/xhr_mock.ts index 15cbe4316c..4eea76363f 100644 --- a/modules/angular2/src/mock/xhr_mock.js +++ b/modules/angular2/src/mock/xhr_mock.ts @@ -4,9 +4,9 @@ import {isBlank, isPresent, normalizeBlank, BaseException} from 'angular2/src/fa import {PromiseWrapper, Promise} from 'angular2/src/facade/async'; export class MockXHR extends XHR { - _expectations: List<_Expectation>; - _definitions: Map; - _requests: List; + private _expectations: List<_Expectation>; + private _definitions: Map; + private _requests: List>; constructor() { super(); @@ -26,9 +26,7 @@ export class MockXHR extends XHR { ListWrapper.push(this._expectations, expectation); } - when(url: string, response: string) { - MapWrapper.set(this._definitions, url, response); - } + when(url: string, response: string) { MapWrapper.set(this._definitions, url, response); } flush() { if (this._requests.length === 0) { @@ -55,7 +53,7 @@ export class MockXHR extends XHR { throw new BaseException(`Unsatisfied requests: ${ListWrapper.join(urls, ', ')}`); } - _processRequest(request: _PendingRequest) { + private _processRequest(request: _PendingRequest) { var url = request.url; if (this._expectations.length > 0) { @@ -94,9 +92,7 @@ class _PendingRequest { } } - getPromise(): Promise { - return this.completer.promise; - } + getPromise(): Promise { return this.completer.promise; } } class _Expectation { diff --git a/modules/angular2/src/render/dom/compiler/compile_element.ts b/modules/angular2/src/render/dom/compiler/compile_element.ts index 9c41f8fd08..01e70a83b9 100644 --- a/modules/angular2/src/render/dom/compiler/compile_element.ts +++ b/modules/angular2/src/render/dom/compiler/compile_element.ts @@ -1,13 +1,6 @@ import {List, Map, ListWrapper, MapWrapper} from 'angular2/src/facade/collection'; import {DOM} from 'angular2/src/dom/dom_adapter'; -import { - int, - isBlank, - isPresent, - Type, - StringJoiner, - assertionsEnabled -} from 'angular2/src/facade/lang'; +import {isBlank, isPresent, Type, StringJoiner, assertionsEnabled} from 'angular2/src/facade/lang'; import {ProtoViewBuilder, ElementBinderBuilder} from '../view/proto_view_builder'; diff --git a/modules/angular2/src/render/dom/dom_renderer.ts b/modules/angular2/src/render/dom/dom_renderer.ts index a18051fc0e..bc80ba38c7 100644 --- a/modules/angular2/src/render/dom/dom_renderer.ts +++ b/modules/angular2/src/render/dom/dom_renderer.ts @@ -1,5 +1,5 @@ import {Inject, Injectable} from 'angular2/di'; -import {int, isPresent, isBlank, BaseException, RegExpWrapper} from 'angular2/src/facade/lang'; +import {isPresent, isBlank, BaseException, RegExpWrapper} from 'angular2/src/facade/lang'; import {ListWrapper, MapWrapper, Map, StringMapWrapper, List} from 'angular2/src/facade/collection'; import {DOM} from 'angular2/src/dom/dom_adapter'; diff --git a/modules/angular2/src/render/dom/events/hammer_gestures.ts b/modules/angular2/src/render/dom/events/hammer_gestures.ts index 268be36ae9..5bfaad4322 100644 --- a/modules/angular2/src/render/dom/events/hammer_gestures.ts +++ b/modules/angular2/src/render/dom/events/hammer_gestures.ts @@ -1,3 +1,5 @@ +/// + import {HammerGesturesPluginCommon} from './hammer_common'; import {isPresent, BaseException} from 'angular2/src/facade/lang'; @@ -7,7 +9,7 @@ export class HammerGesturesPlugin extends HammerGesturesPluginCommon { supports(eventName: string): boolean { if (!super.supports(eventName)) return false; - if (!isPresent(window.Hammer)) { + if (!isPresent(window['Hammer'])) { throw new BaseException(`Hammer.js is not loaded, can not bind ${eventName} event`); } diff --git a/modules/angular2/src/render/dom/shadow_dom/shadow_css.ts b/modules/angular2/src/render/dom/shadow_dom/shadow_css.ts index 89bb745ac0..735ba10236 100644 --- a/modules/angular2/src/render/dom/shadow_dom/shadow_css.ts +++ b/modules/angular2/src/render/dom/shadow_dom/shadow_css.ts @@ -7,8 +7,7 @@ import { RegExpMatcherWrapper, isPresent, isBlank, - BaseException, - int + BaseException } from 'angular2/src/facade/lang'; /** diff --git a/modules/angular2/src/render/dom/shadow_dom/util.ts b/modules/angular2/src/render/dom/shadow_dom/util.ts index 708a0c8aa5..1e3bb20dd6 100644 --- a/modules/angular2/src/render/dom/shadow_dom/util.ts +++ b/modules/angular2/src/render/dom/shadow_dom/util.ts @@ -1,4 +1,4 @@ -import {isBlank, isPresent, int} from 'angular2/src/facade/lang'; +import {isBlank, isPresent} from 'angular2/src/facade/lang'; import {MapWrapper, Map} from 'angular2/src/facade/collection'; import {DOM} from 'angular2/src/dom/dom_adapter'; diff --git a/modules/angular2/src/render/dom/view/view.ts b/modules/angular2/src/render/dom/view/view.ts index 3e4864a69b..a6a78bd651 100644 --- a/modules/angular2/src/render/dom/view/view.ts +++ b/modules/angular2/src/render/dom/view/view.ts @@ -1,7 +1,7 @@ import {DOM} from 'angular2/src/dom/dom_adapter'; import {ListWrapper, MapWrapper, Map, StringMapWrapper, List} from 'angular2/src/facade/collection'; import {Locals} from 'angular2/change_detection'; -import {int, isPresent, isBlank, BaseException} from 'angular2/src/facade/lang'; +import {isPresent, isBlank, BaseException} from 'angular2/src/facade/lang'; import {DomViewContainer} from './view_container'; import {DomProtoView} from './proto_view'; diff --git a/modules/angular2/src/test_lib/benchmark_util.js b/modules/angular2/src/test_lib/benchmark_util.ts similarity index 78% rename from modules/angular2/src/test_lib/benchmark_util.js rename to modules/angular2/src/test_lib/benchmark_util.ts index 13f8f7d118..38b69fd556 100644 --- a/modules/angular2/src/test_lib/benchmark_util.js +++ b/modules/angular2/src/test_lib/benchmark_util.ts @@ -4,16 +4,16 @@ import {NumberWrapper, BaseException, isBlank} from 'angular2/src/facade/lang'; var DOM = new BrowserDomAdapter(); -export function getIntParameter(name:string) { +export function getIntParameter(name: string) { return NumberWrapper.parseInt(getStringParameter(name), 10); } -export function getStringParameter(name:string) { - var els = DOM.querySelectorAll(document, `input[name="${name}"]`) +export function getStringParameter(name: string) { + var els = DOM.querySelectorAll(document, `input[name="${name}"]`); var value; var el; - for (var i=0; i +/// -module.exports = { - verifyNoBrowserErrors: verifyNoBrowserErrors, - clickAll: clickAll -}; +import webdriver = require('selenium-webdriver'); -function clickAll(buttonSelectors) { - buttonSelectors.forEach(function(selector) { - $(selector).click(); - }); +export var browser: protractor.IBrowser = global['browser']; +export var $: cssSelectorHelper = global['$']; + +export function clickAll(buttonSelectors) { + buttonSelectors.forEach(function(selector) { $(selector).click(); }); } -function verifyNoBrowserErrors() { +export function verifyNoBrowserErrors() { // TODO(tbosch): Bug in ChromeDriver: Need to execute at least one command // so that the browser logs can be read out! browser.executeScript('1+1'); @@ -25,4 +24,3 @@ function verifyNoBrowserErrors() { expect(filteredLog.length).toEqual(0); }); } - diff --git a/modules/angular2/src/test_lib/fake_async.es6 b/modules/angular2/src/test_lib/fake_async.ts similarity index 72% rename from modules/angular2/src/test_lib/fake_async.es6 rename to modules/angular2/src/test_lib/fake_async.ts index a559012d6e..947690ee43 100644 --- a/modules/angular2/src/test_lib/fake_async.es6 +++ b/modules/angular2/src/test_lib/fake_async.ts @@ -1,12 +1,19 @@ +/// + import {BaseException, global} from 'angular2/src/facade/lang'; import {ListWrapper} from 'angular2/src/facade/collection'; +import {NgZoneZone} from 'angular2/src/core/zone/ng_zone'; var _scheduler; -var _microtasks:List = []; +var _microtasks: List = []; var _pendingPeriodicTimers: List = []; var _pendingTimers: List = []; var _error = null; +interface FakeAsyncZone extends NgZoneZone { + _inFakeAsyncZone: boolean; +} + /** * Wraps a function to be executed in the fakeAsync zone: * - microtasks are manually executed by calling `flushMicrotasks()`, @@ -19,11 +26,11 @@ var _error = null; */ export function fakeAsync(fn: Function): Function { // TODO(vicb) re-enable once the jasmine patch from zone.js is applied - //if (global.zone._inFakeAsyncZone) { + // if (global.zone._inFakeAsyncZone) { // throw new Error('fakeAsync() calls can not be nested'); //} - var fakeAsyncZone = global.zone.fork({ + var fakeAsyncZone = global.zone.fork({ setTimeout: _setTimeout, clearTimeout: _clearTimeout, setInterval: _setInterval, @@ -32,18 +39,18 @@ export function fakeAsync(fn: Function): Function { _inFakeAsyncZone: true }); - return function(...args) { - _scheduler = global.jasmine.DelayedFunctionScheduler(); + return function(... args) { + // TODO(tbosch): This class should already be part of the jasmine typings but it is not... + _scheduler = new (jasmine).DelayedFunctionScheduler(); ListWrapper.clear(_microtasks); ListWrapper.clear(_pendingPeriodicTimers); ListWrapper.clear(_pendingTimers); - var res = fakeAsyncZone.run(() => { - var res = fn(...args); - }); + var res = fakeAsyncZone.run(() => { var res = fn(... args); }); if (_pendingPeriodicTimers.length > 0) { - throw new BaseException(`${_pendingPeriodicTimers.length} periodic timer(s) still in the queue.`); + throw new BaseException( + `${_pendingPeriodicTimers.length} periodic timer(s) still in the queue.`); } if (_pendingTimers.length > 0) { @@ -60,7 +67,8 @@ export function fakeAsync(fn: Function): Function { /** * Simulates the asynchronous passage of time for the timers in the fakeAsync zone. * - * The microtasks queue is drained at the very start of this function and after any timer callback has been executed. + * The microtasks queue is drained at the very start of this function and after any timer callback + * has been executed. * * @param {number} millis Number of millisecond, defaults to 0 */ @@ -81,7 +89,7 @@ export function flushMicrotasks(): void { } } -function _setTimeout(fn: Function, delay: number, ...args): number { +function _setTimeout(fn: Function, delay: number, ... args): number { var cb = _fnAndFlush(fn); var id = _scheduler.scheduleFunction(cb, delay, args); ListWrapper.push(_pendingTimers, id); @@ -94,7 +102,7 @@ function _clearTimeout(id: number) { return _scheduler.removeFunctionWithId(id); } -function _setInterval(fn: Function, interval: number, ...args) { +function _setInterval(fn: Function, interval: number, ... args) { var cb = _fnAndFlush(fn); var id = _scheduler.scheduleFunction(cb, interval, args, true); _pendingPeriodicTimers.push(id); @@ -106,11 +114,10 @@ function _clearInterval(id: number) { return _scheduler.removeFunctionWithId(id); } -function _fnAndFlush(fn: Function): void { - return () => { - fn.apply(global, arguments); - flushMicrotasks(); - } +function _fnAndFlush(fn: Function): Function { + return (... args) => { fn.apply(global, args); + flushMicrotasks(); +} } function _scheduleMicrotask(microtask: Function): void { @@ -118,14 +125,11 @@ function _scheduleMicrotask(microtask: Function): void { } function _dequeueTimer(id: number): Function { - return function() { - ListWrapper.remove(_pendingTimers, id); - } + return function() { ListWrapper.remove(_pendingTimers, id); } } function _assertInFakeAsyncZone(): void { - if (!global.zone._inFakeAsyncZone) { + if (!(global.zone)._inFakeAsyncZone) { throw new Error('The code should be running in the fakeAsync zone to call this function'); } } - diff --git a/modules/angular2/src/test_lib/lang_utils.es6 b/modules/angular2/src/test_lib/lang_utils.ts similarity index 71% rename from modules/angular2/src/test_lib/lang_utils.es6 rename to modules/angular2/src/test_lib/lang_utils.ts index b3c42ff193..cb4fbfa1ee 100644 --- a/modules/angular2/src/test_lib/lang_utils.es6 +++ b/modules/angular2/src/test_lib/lang_utils.ts @@ -2,7 +2,7 @@ export function getTypeOf(instance) { return instance.constructor; } -export function instantiateType(type: Function, params: Array = []) { +export function instantiateType(type: Function, params: Array = []) { var instance = Object.create(type.prototype); instance.constructor.apply(instance, params); return instance; diff --git a/modules/angular2/src/test_lib/perf_util.es6 b/modules/angular2/src/test_lib/perf_util.es6 index c857f5d06a..ea683f5c8a 100644 --- a/modules/angular2/src/test_lib/perf_util.es6 +++ b/modules/angular2/src/test_lib/perf_util.es6 @@ -1,4 +1,5 @@ var testUtil = require('./e2e_util'); + var benchpress = require('benchpress/benchpress'); module.exports = { @@ -47,7 +48,7 @@ function runBenchmark(config) { } function getScaleFactor(possibleScalings) { - return browser.executeScript('return navigator.userAgent').then(function(userAgent) { + return browser.executeScript('return navigator.userAgent').then(function(userAgent:string) { var scaleFactor = 1; possibleScalings.forEach(function(entry) { if (userAgent.match(entry.userAgent)) { @@ -60,7 +61,7 @@ function getScaleFactor(possibleScalings) { function applyScaleFactor(value, scaleFactor, method) { if (method === 'log2') { - return value + Math.log2(scaleFactor); + return value + Math.log(scaleFactor) / Math.LN2; } else if (method === 'sqrt') { return value * Math.sqrt(scaleFactor); } else if (method === 'linear') { diff --git a/modules/angular2/src/test_lib/perf_utils.dart b/modules/angular2/src/test_lib/perf_utils.dart new file mode 100644 index 0000000000..6a3eb75233 --- /dev/null +++ b/modules/angular2/src/test_lib/perf_utils.dart @@ -0,0 +1,2 @@ +library angular2.perf_util; +// empty as this file is node.js specific and should not be transpiled to dart \ No newline at end of file diff --git a/modules/angular2/src/test_lib/test_bed.js b/modules/angular2/src/test_lib/test_bed.ts similarity index 78% rename from modules/angular2/src/test_lib/test_bed.js rename to modules/angular2/src/test_lib/test_bed.ts index db40461a55..d6cb58cebe 100644 --- a/modules/angular2/src/test_lib/test_bed.js +++ b/modules/angular2/src/test_lib/test_bed.ts @@ -1,4 +1,4 @@ -import {Injector, bind} from 'angular2/di'; +import {Injector, bind, Injectable} from 'angular2/di'; import {Type, isPresent, BaseException} from 'angular2/src/facade/lang'; import {Promise} from 'angular2/src/facade/async'; @@ -10,7 +10,10 @@ import {View} from 'angular2/src/core/annotations_impl/view'; import {TemplateResolver} from 'angular2/src/core/compiler/template_resolver'; import {AppView} from 'angular2/src/core/compiler/view'; import {internalView} from 'angular2/src/core/compiler/view_ref'; -import {DynamicComponentLoader, ComponentRef} from 'angular2/src/core/compiler/dynamic_component_loader'; +import { + DynamicComponentLoader, + ComponentRef +} from 'angular2/src/core/compiler/dynamic_component_loader'; import {queryView, viewRootNodes, el} from './utils'; import {instantiateType, getTypeOf} from './lang_utils'; @@ -21,12 +24,11 @@ import {DOM} from 'angular2/src/dom/dom_adapter'; /** * @exportedAs angular2/test */ +@Injectable() export class TestBed { _injector: Injector; - constructor(injector: Injector) { - this._injector = injector; - } + constructor(injector: Injector) { this._injector = injector; } /** * Overrides the {@link View} of a {@link Component}. @@ -70,11 +72,13 @@ export class TestBed { * * @param {Type} component * @param {*} context - * @param {string} html Use as the component template when specified (shortcut for setInlineTemplate) + * @param {string} html Use as the component template when specified (shortcut for + * setInlineTemplate) * @return {Promise} */ createView(component: Type, - {context = null, html = null}: {context:any, html: string} = {}): Promise { + {context = null, + html = null}: {context?: any, html?: string} = {}): Promise { if (isBlank(component) && isBlank(context)) { throw new BaseException('You must specified at least a component or a context'); } @@ -94,14 +98,15 @@ export class TestBed { DOM.appendChild(doc.body, rootEl); var componentBinding = bind(component).toValue(context); - return this._injector.get(DynamicComponentLoader).loadAsRoot(componentBinding,'#root', this._injector).then((hostComponentRef) => { - return new ViewProxy(hostComponentRef); - }); + return this._injector.get(DynamicComponentLoader) + .loadAsRoot(componentBinding, '#root', this._injector) + .then((hostComponentRef) => { return new ViewProxy(hostComponentRef); }); } } /** - * Proxy to `AppView` return by `createView` in {@link TestBed} which offers a high level API for tests. + * Proxy to `AppView` return by `createView` in {@link TestBed} which offers a high level API for + * tests. */ export class ViewProxy { _componentRef: ComponentRef; @@ -112,33 +117,23 @@ export class ViewProxy { this._view = internalView(componentRef.hostView).componentChildViews[0]; } - get context(): any { - return this._view.context; - } + get context(): any { return this._view.context; } - get rootNodes(): List { - return viewRootNodes(this._view); - } + get rootNodes(): List { return viewRootNodes(this._view); } detectChanges(): void { this._view.changeDetector.detectChanges(); this._view.changeDetector.checkNoChanges(); } - querySelector(selector) { - return queryView(this._view, selector); - } + querySelector(selector) { return queryView(this._view, selector); } - destroy() { - this._componentRef.dispose(); - } + destroy() { this._componentRef.dispose(); } /** * @returns `AppView` returns the underlying `AppView`. * * Prefer using the other methods which hide implementation details. */ - get rawView(): AppView { - return this._view; - } + get rawView(): AppView { return this._view; } } diff --git a/modules/angular2/src/test_lib/test_injector.js b/modules/angular2/src/test_lib/test_injector.ts similarity index 78% rename from modules/angular2/src/test_lib/test_injector.js rename to modules/angular2/src/test_lib/test_injector.ts index 1541900933..18b971849b 100644 --- a/modules/angular2/src/test_lib/test_injector.js +++ b/modules/angular2/src/test_lib/test_injector.ts @@ -1,16 +1,24 @@ -import {bind} from 'angular2/di'; +import {bind, Binding} from 'angular2/di'; import {Compiler, CompilerCache} from 'angular2/src/core/compiler/compiler'; import {Reflector, reflector} from 'angular2/src/reflection/reflection'; -import {Parser, Lexer, ChangeDetection, DynamicChangeDetection, - PipeRegistry, defaultPipeRegistry} from 'angular2/change_detection'; +import { + Parser, + Lexer, + ChangeDetection, + DynamicChangeDetection, + PipeRegistry, + defaultPipeRegistry +} from 'angular2/change_detection'; import {ExceptionHandler} from 'angular2/src/core/exception_handler'; import {TemplateLoader} from 'angular2/src/render/dom/compiler/template_loader'; import {TemplateResolver} from 'angular2/src/core/compiler/template_resolver'; import {DirectiveResolver} from 'angular2/src/core/compiler/directive_resolver'; import {DynamicComponentLoader} from 'angular2/src/core/compiler/dynamic_component_loader'; import {ShadowDomStrategy} from 'angular2/src/render/dom/shadow_dom/shadow_dom_strategy'; -import {EmulatedUnscopedShadowDomStrategy} from 'angular2/src/render/dom/shadow_dom/emulated_unscoped_shadow_dom_strategy'; +import { + EmulatedUnscopedShadowDomStrategy +} from 'angular2/src/render/dom/shadow_dom/emulated_unscoped_shadow_dom_strategy'; import {XHR} from 'angular2/src/services/xhr'; import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper'; import {UrlResolver} from 'angular2/src/services/url_resolver'; @@ -31,7 +39,7 @@ import {TestBed} from './test_bed'; import {Injector} from 'angular2/di'; import {List, ListWrapper} from 'angular2/src/facade/collection'; -import {FunctionWrapper} from 'angular2/src/facade/lang'; +import {FunctionWrapper, Type} from 'angular2/src/facade/lang'; import {AppViewPool, APP_VIEW_POOL_CAPACITY} from 'angular2/src/core/compiler/view_pool'; import {AppViewManager} from 'angular2/src/core/compiler/view_manager'; @@ -50,7 +58,8 @@ import {DefaultDomCompiler} from 'angular2/src/render/dom/compiler/compiler'; */ function _getRootBindings() { return [ - bind(Reflector).toValue(reflector), + bind(Reflector) + .toValue(reflector), ]; } @@ -67,15 +76,17 @@ function _getAppBindings() { // The document is only available in browser environment try { appDoc = DOM.defaultDoc(); - } catch(e) { + } catch (e) { appDoc = null; } return [ - bind(DOCUMENT_TOKEN).toValue(appDoc), - bind(ShadowDomStrategy).toFactory( - (styleUrlResolver, doc) => new EmulatedUnscopedShadowDomStrategy(styleUrlResolver, doc.head), - [StyleUrlResolver, DOCUMENT_TOKEN]), + bind(DOCUMENT_TOKEN) + .toValue(appDoc), + bind(ShadowDomStrategy) + .toFactory((styleUrlResolver, doc) => + new EmulatedUnscopedShadowDomStrategy(styleUrlResolver, doc.head), + [StyleUrlResolver, DOCUMENT_TOKEN]), DomRenderer, DefaultDomCompiler, bind(Renderer).toAlias(DomRenderer), @@ -103,16 +114,19 @@ function _getAppBindings() { StyleInliner, TestBed, bind(NgZone).toClass(MockNgZone), - bind(EventManager).toFactory((zone) => { - var plugins = [ - new DomEventsPlugin(), - ]; - return new EventManager(plugins, zone); - }, [NgZone]), + bind(EventManager) + .toFactory((zone) => + { + var plugins = [ + new DomEventsPlugin(), + ]; + return new EventManager(plugins, zone); + }, + [NgZone]), ]; } -export function createTestInjector(bindings: List):Injector { +export function createTestInjector(bindings: List>): Injector { var rootInjector = Injector.resolveAndCreate(_getRootBindings()); return rootInjector.resolveAndCreateChild(ListWrapper.concat(_getAppBindings(), bindings)); } @@ -147,22 +161,21 @@ export function createTestInjector(bindings: List):Injector { * @return {FunctionWithParamTokens} * @exportedAs angular2/test */ -export function inject(tokens: List, fn: Function):FunctionWithParamTokens { +export function inject(tokens: List, fn: Function): FunctionWithParamTokens { return new FunctionWithParamTokens(tokens, fn); } export class FunctionWithParamTokens { - _tokens: List; + _tokens: List; _fn: Function; - constructor(tokens: List, fn: Function) { + constructor(tokens: List, fn: Function) { this._tokens = tokens; this._fn = fn; } - execute(injector: Injector):void { + execute(injector: Injector): void { var params = ListWrapper.map(this._tokens, (t) => injector.get(t)); FunctionWrapper.apply(this._fn, params); } } - diff --git a/modules/angular2/src/test_lib/test_lib.es6 b/modules/angular2/src/test_lib/test_lib.es6 deleted file mode 100644 index b388f6f374..0000000000 --- a/modules/angular2/src/test_lib/test_lib.es6 +++ /dev/null @@ -1,358 +0,0 @@ -import {DOM} from 'angular2/src/dom/dom_adapter'; -import {StringMapWrapper} from 'angular2/src/facade/collection'; -import {global} from 'angular2/src/facade/lang'; - -import {bind} from 'angular2/di'; - -import {createTestInjector, FunctionWithParamTokens, inject} from './test_injector'; - -export {inject} from './test_injector'; - -export {proxy} from 'rtts_assert/rtts_assert'; - -var _global = typeof window === 'undefined' ? global : window; - -export var afterEach = _global.afterEach; -export var expect = _global.expect; - -export var IS_DARTIUM = false; - -export class AsyncTestCompleter { - _done: Function; - - constructor(done: Function) { - this._done = done; - } - - done() { - this._done(); - } -} - -var jsmBeforeEach = _global.beforeEach; -var jsmDescribe = _global.describe; -var jsmDDescribe = _global.fdescribe; -var jsmXDescribe = _global.xdescribe; -var jsmIt = _global.it; -var jsmIIt = _global.fit; -var jsmXIt = _global.xit; - -var runnerStack = []; -var inIt = false; - -var testBindings; - -class BeforeEachRunner { - constructor(parent: BeforeEachRunner) { - this._fns = []; - this._parent = parent; - } - - beforeEach(fn: FunctionWithParamTokens) { - this._fns.push(fn); - } - - run(injector) { - if (this._parent) this._parent.run(injector); - this._fns.forEach((fn) => fn.execute(injector)); - } -} - -// Reset the test bindings before each test -jsmBeforeEach(() => { testBindings = []; }); - -function _describe(jsmFn, ...args) { - var parentRunner = runnerStack.length === 0 ? null : runnerStack[runnerStack.length - 1]; - var runner = new BeforeEachRunner(parentRunner); - runnerStack.push(runner); - var suite = jsmFn(...args); - runnerStack.pop(); - return suite; -} - -export function describe(...args) { - return _describe(jsmDescribe, ...args); -} - -export function ddescribe(...args) { - return _describe(jsmDDescribe, ...args); -} - -export function xdescribe(...args) { - return _describe(jsmXDescribe, ...args); -} - -export function beforeEach(fn) { - if (runnerStack.length > 0) { - // Inside a describe block, beforeEach() uses a BeforeEachRunner - var runner = runnerStack[runnerStack.length - 1]; - if (!(fn instanceof FunctionWithParamTokens)) { - fn = inject([], fn); - } - runner.beforeEach(fn); - } else { - // Top level beforeEach() are delegated to jasmine - jsmBeforeEach(fn); - } -} - -/** - * Allows overriding default bindings defined in test_injector.js. - * - * The given function must return a list of DI bindings. - * - * Example: - * - * beforeEachBindings(() => [ - * bind(Compiler).toClass(MockCompiler), - * bind(SomeToken).toValue(myValue), - * ]); - */ -export function beforeEachBindings(fn) { - jsmBeforeEach(() => { - var bindings = fn(); - if (!bindings) return; - testBindings = [...testBindings, ...bindings]; - }); -} - -function _it(jsmFn, name, fn) { - var runner = runnerStack[runnerStack.length - 1]; - - jsmFn(name, function(done) { - var async = false; - - var completerBinding = bind(AsyncTestCompleter).toFactory(() => { - // Mark the test as async when an AsyncTestCompleter is injected in an it() - if (!inIt) throw new Error('AsyncTestCompleter can only be injected in an "it()"'); - async = true; - return new AsyncTestCompleter(done); - }); - - var injector = createTestInjector([...testBindings, completerBinding]); - runner.run(injector); - - if (!(fn instanceof FunctionWithParamTokens)) { - fn = inject([], fn); - } - - inIt = true; - fn.execute(injector); - inIt = false; - - if (!async) done(); - }); -} - -export function it(name, fn) { - return _it(jsmIt, name, fn); -} - -export function xit(name, fn) { - return _it(jsmXIt, name, fn); -} - -export function iit(name, fn) { - return _it(jsmIIt, name, fn); -} - -// To make testing consistent between dart and js -_global.print = function(msg) { - if (_global.dump) { - _global.dump(msg); - } else { - _global.console.log(msg); - } -}; - -// Some Map polyfills don't polyfill Map.toString correctly, which -// gives us bad error messages in tests. -// The only way to do this in Jasmine is to monkey patch a method -// to the object :-( -_global.Map.prototype.jasmineToString = function() { - var m = this; - if (!m) { - return ''+m; - } - var res = []; - m.forEach( (v,k) => { - res.push(`${k}:${v}`); - }); - return `{ ${res.join(',')} }`; -} - -_global.beforeEach(function() { - jasmine.addMatchers({ - // Custom handler for Map as Jasmine does not support it yet - toEqual: function(util, customEqualityTesters) { - return { - compare: function(actual, expected) { - return { - pass: util.equals(actual, expected, [compareMap]) - }; - } - }; - - function compareMap(actual, expected) { - if (actual instanceof Map) { - var pass = actual.size === expected.size; - if (pass) { - actual.forEach( (v,k) => { - pass = pass && util.equals(v, expected.get(k)); - }); - } - return pass; - } else { - return undefined; - } - } - }, - - toBePromise: function() { - return { - compare: function (actual, expectedClass) { - var pass = typeof actual === 'object' && typeof actual.then === 'function'; - return { - pass: pass, - get message() { - return 'Expected ' + actual + ' to be a promise'; - } - }; - } - }; - }, - - toBeAnInstanceOf: function() { - return { - compare: function(actual, expectedClass) { - var pass = typeof actual === 'object' && actual instanceof expectedClass; - return { - pass: pass, - get message() { - return 'Expected ' + actual + ' to be an instance of ' + expectedClass; - } - }; - } - }; - }, - - toHaveText: function() { - return { - compare: function(actual, expectedText) { - var actualText = elementText(actual); - return { - pass: actualText == expectedText, - get message() { - return 'Expected ' + actualText + ' to be equal to ' + expectedText; - } - }; - } - }; - }, - - toImplement: function() { - return { - compare: function(actualObject, expectedInterface) { - var objProps = Object.keys(actualObject.constructor.prototype); - var intProps = Object.keys(expectedInterface.prototype); - - var missedMethods = []; - intProps.forEach((k) => { - if (!actualObject.constructor.prototype[k]) missedMethods.push(k); - }); - - return { - pass: missedMethods.length == 0, - get message() { - return 'Expected ' + actualObject + ' to have the following methods: ' + missedMethods.join(", "); - } - }; - } - }; - } - }); -}); - -export class SpyObject { - constructor(type = null) { - if (type) { - for (var prop in type.prototype) { - var m = null; - try { - m = type.prototype[prop]; - } catch (e) { - // As we are creating spys for abstract classes, - // these classes might have getters that throw when they are accessed. - // As we are only auto creating spys for methods, this - // should not matter. - } - if (typeof m === 'function') { - this.spy(prop); - } - } - } - } - spy(name){ - if (! this[name]) { - this[name] = this._createGuinnessCompatibleSpy(); - } - return this[name]; - } - - static stub(object = null, config = null, overrides = null) { - if (!(object instanceof SpyObject)) { - overrides = config; - config = object; - object = new SpyObject(); - } - - var m = StringMapWrapper.merge(config, overrides); - StringMapWrapper.forEach(m, (value, key) => { - object.spy(key).andReturn(value); - }); - return object; - } - - rttsAssert(value) { - return true; - } - - _createGuinnessCompatibleSpy(){ - var newSpy = jasmine.createSpy(); - newSpy.andCallFake = newSpy.and.callFake; - newSpy.andReturn = newSpy.and.returnValue; - // return null by default to satisfy our rtts asserts - newSpy.and.returnValue(null); - return newSpy; - } -} - -function elementText(n) { - var hasNodes = (n) => {var children = DOM.childNodes(n); return children && children.length > 0;} - - if (n instanceof Array) { - return n.map((nn) => elementText(nn)).join(""); - } - - if (DOM.isCommentNode(n)) { - return ''; - } - - if (DOM.isElementNode(n) && DOM.tagName(n) == 'CONTENT') { - return elementText(Array.prototype.slice.apply(DOM.getDistributedNodes(n))); - } - - if (DOM.hasShadowRoot(n)) { - return elementText(DOM.childNodesAsList(DOM.getShadowRoot(n))); - } - - if (hasNodes(n)) { - return elementText(DOM.childNodesAsList(n)); - } - - return DOM.getText(n); -} - -export function isInInnerZone(): boolean { - return global.zone._innerZone === true; -} diff --git a/modules/angular2/src/test_lib/test_lib.ts b/modules/angular2/src/test_lib/test_lib.ts new file mode 100644 index 0000000000..00e015b832 --- /dev/null +++ b/modules/angular2/src/test_lib/test_lib.ts @@ -0,0 +1,352 @@ +/// + +import {DOM} from 'angular2/src/dom/dom_adapter'; +import {StringMapWrapper} from 'angular2/src/facade/collection'; +import {global} from 'angular2/src/facade/lang'; +import {NgZoneZone} from 'angular2/src/core/zone/ng_zone'; + +import {bind} from 'angular2/di'; + +import {createTestInjector, FunctionWithParamTokens, inject} from './test_injector'; + +export {inject} from './test_injector'; + +export function proxy() { +} + +var _global: jasmine.GlobalPolluter = (typeof window === 'undefined' ? global : window); + +export var afterEach = _global.afterEach; +export var expect = _global.expect; + +export var IS_DARTIUM = false; + +export class AsyncTestCompleter { + _done: Function; + + constructor(done: Function) { this._done = done; } + + done() { this._done(); } +} + +var jsmBeforeEach = _global.beforeEach; +var jsmDescribe = _global.describe; +var jsmDDescribe = _global.fdescribe; +var jsmXDescribe = _global.xdescribe; +var jsmIt = _global.it; +var jsmIIt = _global.fit; +var jsmXIt = _global.xit; + +var runnerStack = []; +var inIt = false; + +var testBindings; + +class BeforeEachRunner { + _fns: List; + _parent: BeforeEachRunner; + constructor(parent: BeforeEachRunner) { + this._fns = []; + this._parent = parent; + } + + beforeEach(fn: FunctionWithParamTokens) { this._fns.push(fn); } + + run(injector) { + if (this._parent) this._parent.run(injector); + this._fns.forEach((fn) => fn.execute(injector)); + } +} + +// Reset the test bindings before each test +jsmBeforeEach(() => { testBindings = []; }); + +function _describe(jsmFn, ... args) { + var parentRunner = runnerStack.length === 0 ? null : runnerStack[runnerStack.length - 1]; + var runner = new BeforeEachRunner(parentRunner); + runnerStack.push(runner); + var suite = jsmFn(... args); + runnerStack.pop(); + return suite; +} + +export function describe(... args) { + return _describe(jsmDescribe, ... args); +} + +export function ddescribe(... args) { + return _describe(jsmDDescribe, ... args); +} + +export function xdescribe(... args) { + return _describe(jsmXDescribe, ... args); +} + +export function beforeEach(fn) { + if (runnerStack.length > 0) { + // Inside a describe block, beforeEach() uses a BeforeEachRunner + var runner = runnerStack[runnerStack.length - 1]; + if (!(fn instanceof FunctionWithParamTokens)) { + fn = inject([], fn); + } + runner.beforeEach(fn); + } else { + // Top level beforeEach() are delegated to jasmine + jsmBeforeEach(fn); + } +} + +/** + * Allows overriding default bindings defined in test_injector.js. + * + * The given function must return a list of DI bindings. + * + * Example: + * + * beforeEachBindings(() => [ + * bind(Compiler).toClass(MockCompiler), + * bind(SomeToken).toValue(myValue), + * ]); + */ +export function beforeEachBindings(fn) { + jsmBeforeEach(() => { + var bindings = fn(); + if (!bindings) return; + testBindings = [... testBindings, ... bindings]; + }); +} + +function _it(jsmFn, name, fn) { + var runner = runnerStack[runnerStack.length - 1]; + + jsmFn(name, function(done) { + var async = false; + + var completerBinding = + bind(AsyncTestCompleter) + .toFactory(() => { + // Mark the test as async when an AsyncTestCompleter is injected in an it() + if (!inIt) throw new Error('AsyncTestCompleter can only be injected in an "it()"'); + async = true; + return new AsyncTestCompleter(done); + }); + + var injector = createTestInjector([... testBindings, completerBinding]); + runner.run(injector); + + if (!(fn instanceof FunctionWithParamTokens)) { + fn = inject([], fn); + } + + inIt = true; + fn.execute(injector); + inIt = false; + + if (!async) done(); + }); +} + +export function it(name, fn) { + return _it(jsmIt, name, fn); +} + +export function xit(name, fn) { + return _it(jsmXIt, name, fn); +} + +export function iit(name, fn) { + return _it(jsmIIt, name, fn); +} + +// Some Map polyfills don't polyfill Map.toString correctly, which +// gives us bad error messages in tests. +// The only way to do this in Jasmine is to monkey patch a method +// to the object :-( +Map.prototype['jasmineToString'] = + function() { + var m = this; + if (!m) { + return '' + m; + } + var res = []; + m.forEach((v, k) => { res.push(`${k}:${v}`); }); + return `{ ${res.join(',')} }`; + } + + _global.beforeEach(function() { + jasmine.addMatchers({ + // Custom handler for Map as Jasmine does not support it yet + toEqual: function(util, customEqualityTesters) { + return { + compare: function(actual, expected) { + return {pass: util.equals(actual, expected, [compareMap])}; + } + }; + + function compareMap(actual, expected) { + if (actual instanceof Map) { + var pass = actual.size === expected.size; + if (pass) { + actual.forEach((v, k) => { pass = pass && util.equals(v, expected.get(k)); }); + } + return pass; + } else { + return undefined; + } + } + }, + + toBePromise: function() { + return { + compare: function(actual, expectedClass) { + var pass = typeof actual === 'object' && typeof actual.then === 'function'; + return { + pass: pass, + get message() { return 'Expected ' + actual + ' to be a promise'; } + }; + } + }; + }, + + toBeAnInstanceOf: function() { + return { + compare: function(actual, expectedClass) { + var pass = typeof actual === 'object' && actual instanceof expectedClass; + return { + pass: pass, + get message() { + return 'Expected ' + actual + ' to be an instance of ' + expectedClass; + } + }; + } + }; + }, + + toHaveText: function() { + return { + compare: function(actual, expectedText) { + var actualText = elementText(actual); + return { + pass: actualText == expectedText, + get message() { + return 'Expected ' + actualText + ' to be equal to ' + expectedText; + } + }; + } + }; + }, + + toImplement: function() { + return { + compare: function(actualObject, expectedInterface) { + var objProps = Object.keys(actualObject.constructor.prototype); + var intProps = Object.keys(expectedInterface.prototype); + + var missedMethods = []; + intProps.forEach((k) => { + if (!actualObject.constructor.prototype[k]) missedMethods.push(k); + }); + + return { + pass: missedMethods.length == 0, + get message() { + return 'Expected ' + actualObject + ' to have the following methods: ' + + missedMethods.join(", "); + } + }; + } + }; + } + }); + }); + +export interface GuinessCompatibleSpy extends jasmine.Spy { + /** By chaining the spy with and.returnValue, all calls to the function will return a specific + * value. */ + andReturn(val: any): void; + /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied + * function. */ + andCallFake(fn: Function): GuinessCompatibleSpy; +} + +export class SpyObject { + constructor(type = null) { + if (type) { + for (var prop in type.prototype) { + var m = null; + try { + m = type.prototype[prop]; + } catch (e) { + // As we are creating spys for abstract classes, + // these classes might have getters that throw when they are accessed. + // As we are only auto creating spys for methods, this + // should not matter. + } + if (typeof m === 'function') { + this.spy(prop); + } + } + } + } + spy(name) { + if (!this[name]) { + this[name] = this._createGuinnessCompatibleSpy(name); + } + return this[name]; + } + + static stub(object = null, config = null, overrides = null) { + if (!(object instanceof SpyObject)) { + overrides = config; + config = object; + object = new SpyObject(); + } + + var m = StringMapWrapper.merge(config, overrides); + StringMapWrapper.forEach(m, (value, key) => { object.spy(key).andReturn(value); }); + return object; + } + + rttsAssert(value) { return true; } + + _createGuinnessCompatibleSpy(name): GuinessCompatibleSpy { + var newSpy: GuinessCompatibleSpy = jasmine.createSpy(name); + newSpy.andCallFake = newSpy.and.callFake; + newSpy.andReturn = newSpy.and.returnValue; + // return null by default to satisfy our rtts asserts + newSpy.and.returnValue(null); + return newSpy; + } +} + +function elementText(n) { + var hasNodes = (n) => { var children = DOM.childNodes(n); + return children && children.length > 0; +} + +if (n instanceof Array) { + return n.map((nn) => elementText(nn)).join(""); +} + +if (DOM.isCommentNode(n)) { + return ''; +} + +if (DOM.isElementNode(n) && DOM.tagName(n) == 'CONTENT') { + return elementText(Array.prototype.slice.apply(DOM.getDistributedNodes(n))); +} + +if (DOM.hasShadowRoot(n)) { + return elementText(DOM.childNodesAsList(DOM.getShadowRoot(n))); +} + +if (hasNodes(n)) { + return elementText(DOM.childNodesAsList(n)); +} + +return DOM.getText(n); +} + +export function isInInnerZone(): boolean { + return (global.zone)._innerZone === true; +} diff --git a/modules/angular2/src/test_lib/utils.js b/modules/angular2/src/test_lib/utils.ts similarity index 71% rename from modules/angular2/src/test_lib/utils.js rename to modules/angular2/src/test_lib/utils.ts index 2ec39a98ca..588af3e211 100644 --- a/modules/angular2/src/test_lib/utils.js +++ b/modules/angular2/src/test_lib/utils.ts @@ -4,32 +4,28 @@ import {isPresent} from 'angular2/src/facade/lang'; import {resolveInternalDomView} from 'angular2/src/render/dom/view/view'; export class Log { - _result:List; + _result: List; - constructor() { - this._result = []; - } + constructor() { this._result = []; } - add(value):void { - ListWrapper.push(this._result, value); - } + add(value): void { ListWrapper.push(this._result, value); } fn(value) { return (a1 = null, a2 = null, a3 = null, a4 = null, a5 = null) => { ListWrapper.push(this._result, value); - } - } - - result():string { - return ListWrapper.join(this._result, "; "); } } -export function viewRootNodes(view):List { +result(): string { + return ListWrapper.join(this._result, "; "); +} +} + +export function viewRootNodes(view): List { return resolveInternalDomView(view.render).rootNodes; } -export function queryView(view, selector:string) { +export function queryView(view, selector: string) { var rootNodes = viewRootNodes(view); for (var i = 0; i < rootNodes.length; ++i) { var res = DOM.querySelector(rootNodes[i], selector); @@ -44,6 +40,6 @@ export function dispatchEvent(element, eventType) { DOM.dispatchEvent(element, DOM.createEvent(eventType)); } -export function el(html:string) { +export function el(html: string) { return DOM.firstChild(DOM.content(DOM.createTemplate(html))); } diff --git a/modules/angular2/test.js b/modules/angular2/test.ts similarity index 100% rename from modules/angular2/test.js rename to modules/angular2/test.ts diff --git a/modules/angular2/test_lib.js b/modules/angular2/test_lib.ts similarity index 100% rename from modules/angular2/test_lib.js rename to modules/angular2/test_lib.ts diff --git a/modules/angular2/tsd.json b/modules/angular2/tsd.json index c04d5adc31..1337e157e1 100644 --- a/modules/angular2/tsd.json +++ b/modules/angular2/tsd.json @@ -14,16 +14,19 @@ "jasmine/jasmine.d.ts": { "commit": "055b3172e8eb374a75826710c4d08677872620d3" }, + "node/node.d.ts": { + "commit": "d5f92f93bdb49f332fa662ff1d0cc8700f02e4dc" + }, "rx/rx.all.d.ts": { "commit": "3882d337bb0808cde9fe4c08012508a48c135482" }, - "rx/rx.d.ts" : { + "rx/rx.d.ts": { "commit": "3882d337bb0808cde9fe4c08012508a48c135482" }, - "rx/rx-lite.d.ts" : { + "rx/rx-lite.d.ts": { "commit": "3882d337bb0808cde9fe4c08012508a48c135482" }, - "rx/rx.aggregates.d.ts" : { + "rx/rx.aggregates.d.ts": { "commit": "3882d337bb0808cde9fe4c08012508a48c135482" }, "rx/rx.time.d.ts": { @@ -32,31 +35,31 @@ "rx/rx.time-lite.d.ts": { "commit": "3882d337bb0808cde9fe4c08012508a48c135482" }, - "rx/rx.async.d.ts" : { + "rx/rx.async.d.ts": { "commit": "3882d337bb0808cde9fe4c08012508a48c135482" }, - "rx/rx.async-lite.d.ts" : { + "rx/rx.async-lite.d.ts": { "commit": "3882d337bb0808cde9fe4c08012508a48c135482" }, - "rx/rx.binding.d.ts" : { + "rx/rx.binding.d.ts": { "commit": "3882d337bb0808cde9fe4c08012508a48c135482" }, - "rx/rx.binding-lite.d.ts" : { + "rx/rx.binding-lite.d.ts": { "commit": "3882d337bb0808cde9fe4c08012508a48c135482" }, - "rx/rx.coincidence.d.ts" : { + "rx/rx.coincidence.d.ts": { "commit": "3882d337bb0808cde9fe4c08012508a48c135482" }, - "rx/rx.coincidence-lite.d.ts" : { + "rx/rx.coincidence-lite.d.ts": { "commit": "3882d337bb0808cde9fe4c08012508a48c135482" }, - "rx/rx.experimental.d.ts" : { + "rx/rx.experimental.d.ts": { "commit": "3882d337bb0808cde9fe4c08012508a48c135482" }, - "rx/rx.joinpatterns.d.ts" : { + "rx/rx.joinpatterns.d.ts": { "commit": "3882d337bb0808cde9fe4c08012508a48c135482" }, - "rx/rx.virtualtime.d.ts" : { + "rx/rx.virtualtime.d.ts": { "commit": "3882d337bb0808cde9fe4c08012508a48c135482" }, "rx/rx.testing.d.ts": { @@ -68,12 +71,14 @@ "rx/rx.backpressure-lite.d.ts": { "commit": "3882d337bb0808cde9fe4c08012508a48c135482" }, - "selenium-webdriver/selenium-webdriver.d.ts": { "commit": "be0b6b394f77a59e192ad7cfec18078706e44db5" }, "zone/zone.d.ts": { "commit": "055b3172e8eb374a75826710c4d08677872620d3" + }, + "angular-protractor/angular-protractor.d.ts": { + "commit": "4207593c012565a7ea800ed861ffbe5011e7a501" } } }