refactor(ts'ify): ts’ify mocks, directives and test_lib

Also cleans up global types.
This commit is contained in:
Tobias Bosch 2015-05-20 17:19:46 -07:00
parent c5996529c3
commit aec51d616b
51 changed files with 610 additions and 671 deletions

View File

@ -0,0 +1,2 @@
library angular2.sfx;
// empty as we don't have a version for Dart

View File

@ -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';

View File

@ -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.
*
*/

View File

@ -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';

View File

@ -4,4 +4,3 @@
* @description
* Annotations which control how the dependencies are resolved by the {@link Injector}.
*/

View File

@ -4,4 +4,3 @@
* @description
* Errors thrown by the {@link Injector}.
*/

View File

@ -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<Type> =
CONST_EXPR([NgFor, NgIf, NgNonBindable, NgSwitch, NgSwitchWhen, NgSwitchDefault]);

View File

@ -2,18 +2,16 @@
* This file contains declarations of global symbols we reference in our code
*/
/// <reference path="typings/hammerjs/hammerjs"/>
/// <reference path="typings/zone/zone.d.ts"/>
declare var assert: any;
declare var global: Window;
declare type int = number;
interface List<T> extends Array<T> {}
interface StringMap<K, V> 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;
}

View File

@ -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;

View File

@ -1,6 +1,5 @@
import {Injectable} from 'angular2/src/di/decorators';
import {
int,
isBlank,
isPresent,
BaseException,

View File

@ -7,7 +7,6 @@ import {
} from 'angular2/src/facade/collection';
import {
int,
isBlank,
isPresent,
stringify,

View File

@ -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';

View File

@ -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 {

View File

@ -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';

View File

@ -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.
*

View File

@ -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);

View File

@ -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);

View File

@ -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:
*
* ```
* <div *ng-if="errorCount > 0" class="error">
* <!-- Error message displayed when the errorCount property on the current context is greater than 0. -->
* <!-- Error message displayed when the errorCount property on the current context is greater
* than 0. -->
* {{errorCount}} errors detected
* </div>
* ```
@ -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;

View File

@ -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 {
}

View File

@ -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<any, List<SwitchView>>;
_activeViews: List<SwitchView>;
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<SwitchView>):void {
_activateViews(views: List<SwitchView>): 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));
}
}

View File

@ -1,7 +1,7 @@
/// <reference path="../../typings/es6-promise/es6-promise.d.ts" />
/// <reference path="../../typings/rx/rx.all.d.ts" />
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';

View File

@ -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;

View File

@ -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;

View File

@ -1,4 +1,4 @@
var _global = typeof window === 'undefined' ? global : window;
var _global: BrowserNodeGlobal = <any>(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<T>(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);

View File

@ -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();
}
}

View File

@ -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(); }
}

View File

@ -8,7 +8,7 @@ export class MockTemplateResolver extends TemplateResolver {
_templates: Map<Type, View>;
_inlineTemplates: Map<Type, string>;
_templateCache: Map<Type, View>;
_directiveOverrides: Map<Type, Type>;
_directiveOverrides: Map<Type, Map<Type, Type>>;
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`);
}
}
}

View File

@ -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<Promise>;
private _expectations: List<_Expectation>;
private _definitions: Map<string, string>;
private _requests: List<Promise<string>>;
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<string> {
return this.completer.promise;
}
getPromise(): Promise<string> { return this.completer.promise; }
}
class _Expectation {

View File

@ -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';

View File

@ -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';

View File

@ -1,3 +1,5 @@
/// <reference path="../../../../typings/hammerjs/hammerjs"/>
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`);
}

View File

@ -7,8 +7,7 @@ import {
RegExpMatcherWrapper,
isPresent,
isBlank,
BaseException,
int
BaseException
} from 'angular2/src/facade/lang';
/**

View File

@ -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';

View File

@ -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';

View File

@ -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<els.length; i++) {
for (var i = 0; i < els.length; i++) {
el = els[i];
var type = DOM.type(el);
if ((type != 'radio' && type != 'checkbox') || DOM.getChecked(el)) {
@ -29,11 +29,9 @@ export function getStringParameter(name:string) {
return value;
}
export function bindAction(selector:string, callback:Function) {
export function bindAction(selector: string, callback: Function) {
var el = DOM.querySelector(document, selector);
DOM.on(el, 'click', function(_) {
callback();
});
DOM.on(el, 'click', function(_) { callback(); });
}
export function microBenchmark(name, iterationCount, callback) {

View File

@ -0,0 +1,2 @@
library angular2.e2e_util;
// empty as this file is node.js specific and should not be transpiled to dart

View File

@ -1,17 +1,16 @@
var webdriver = require('selenium-webdriver');
/// <reference path="../../typings/node/node.d.ts" />
/// <reference path="../../typings/angular-protractor/angular-protractor.d.ts" />
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);
});
}

View File

@ -1,12 +1,19 @@
/// <reference path="../../typings/jasmine/jasmine"/>
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<Function> = [];
var _microtasks: List<Function> = [];
var _pendingPeriodicTimers: List<number> = [];
var _pendingTimers: List<number> = [];
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 = <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 (<any>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 (!(<FakeAsyncZone>global.zone)._inFakeAsyncZone) {
throw new Error('The code should be running in the fakeAsync zone to call this function');
}
}

View File

@ -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<any> = []) {
var instance = Object.create(type.prototype);
instance.constructor.apply(instance, params);
return instance;

View File

@ -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') {

View File

@ -0,0 +1,2 @@
library angular2.perf_util;
// empty as this file is node.js specific and should not be transpiled to dart

View File

@ -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<ViewProxy>}
*/
createView(component: Type,
{context = null, html = null}: {context:any, html: string} = {}): Promise<ViewProxy> {
{context = null,
html = null}: {context?: any, html?: string} = {}): Promise<ViewProxy> {
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</*node*/ any> { 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; }
}

View File

@ -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<Type | Binding | List<any>>): 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<any>, fn: Function): FunctionWithParamTokens {
return new FunctionWithParamTokens(tokens, fn);
}
export class FunctionWithParamTokens {
_tokens: List;
_tokens: List<any>;
_fn: Function;
constructor(tokens: List, fn: Function) {
constructor(tokens: List<any>, 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);
}
}

View File

@ -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;
}

View File

@ -0,0 +1,352 @@
/// <reference path="../../typings/jasmine/jasmine"/>
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 = <any>(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<FunctionWithParamTokens>;
_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 = <any>jasmine.createSpy(name);
newSpy.andCallFake = <any>newSpy.and.callFake;
newSpy.andReturn = <any>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 (<NgZoneZone>global.zone)._innerZone === true;
}

View File

@ -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<any>;
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</*node*/ any> {
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)));
}

View File

@ -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"
}
}
}