@@ -3,7 +3,7 @@ import {AnimationBuilder} from 'angular2/src/animate/animation_builder';
|
||||
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
|
||||
|
||||
export function main() {
|
||||
describe("AnimationBuilder", () => {
|
||||
describe('AnimationBuilder', () => {
|
||||
|
||||
it('should have data object', inject([AnimationBuilder], animate => {
|
||||
var animateCss = animate.css();
|
||||
|
||||
@@ -1,19 +1,4 @@
|
||||
import {
|
||||
ComponentFixture,
|
||||
AsyncTestCompleter,
|
||||
TestComponentBuilder,
|
||||
beforeEach,
|
||||
beforeEachProviders,
|
||||
ddescribe,
|
||||
xdescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
} from 'angular2/testing_internal';
|
||||
import {ComponentFixture, AsyncTestCompleter, TestComponentBuilder, beforeEach, beforeEachProviders, ddescribe, xdescribe, describe, el, expect, iit, inject, it, xit,} from 'angular2/testing_internal';
|
||||
import {ListWrapper, StringMapWrapper, SetWrapper} from 'angular2/src/facade/collection';
|
||||
import {Component, provide} from 'angular2/core';
|
||||
import {NgFor} from 'angular2/common';
|
||||
|
||||
@@ -1,17 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
TestComponentBuilder,
|
||||
beforeEach,
|
||||
beforeEachProviders,
|
||||
ddescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, TestComponentBuilder, beforeEach, beforeEachProviders, ddescribe, describe, el, expect, iit, inject, it, xit,} from 'angular2/testing_internal';
|
||||
|
||||
import {ListWrapper} from 'angular2/src/facade/collection';
|
||||
import {IS_DART} from 'angular2/src/facade/lang';
|
||||
@@ -162,18 +149,16 @@ export function main() {
|
||||
if (!IS_DART) {
|
||||
it('should throw on non-iterable ref and suggest using an array',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideTemplate(TestComponent, TEMPLATE)
|
||||
.createAsync(TestComponent)
|
||||
.then((fixture) => {
|
||||
fixture.debugElement.componentInstance.items = 'whaaa';
|
||||
try {
|
||||
fixture.detectChanges()
|
||||
} catch (e) {
|
||||
expect(e.message).toContain(
|
||||
`Cannot find a differ supporting object 'whaaa' of type 'string'. NgFor only supports binding to Iterables such as Arrays.`);
|
||||
async.done();
|
||||
}
|
||||
});
|
||||
tcb.overrideTemplate(TestComponent, TEMPLATE).createAsync(TestComponent).then((fixture) => {
|
||||
fixture.debugElement.componentInstance.items = 'whaaa';
|
||||
try {
|
||||
fixture.detectChanges()
|
||||
} catch (e) {
|
||||
expect(e.message).toContain(
|
||||
`Cannot find a differ supporting object 'whaaa' of type 'string'. NgFor only supports binding to Iterables such as Arrays.`);
|
||||
async.done();
|
||||
}
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -207,12 +192,12 @@ export function main() {
|
||||
it('should repeat over nested arrays',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
var template = '<div>' +
|
||||
'<div template="ngFor #item of items">' +
|
||||
'<div template="ngFor #subitem of item">' +
|
||||
'{{subitem}}-{{item.length}};' +
|
||||
'</div>|' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
'<div template="ngFor #item of items">' +
|
||||
'<div template="ngFor #subitem of item">' +
|
||||
'{{subitem}}-{{item.length}};' +
|
||||
'</div>|' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
|
||||
tcb.overrideTemplate(TestComponent, template)
|
||||
.createAsync(TestComponent)
|
||||
@@ -234,9 +219,9 @@ export function main() {
|
||||
it('should repeat over nested arrays with no intermediate element',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
var template = '<div><template ngFor #item [ngForOf]="items">' +
|
||||
'<div template="ngFor #subitem of item">' +
|
||||
'{{subitem}}-{{item.length}};' +
|
||||
'</div></template></div>';
|
||||
'<div template="ngFor #subitem of item">' +
|
||||
'{{subitem}}-{{item.length}};' +
|
||||
'</div></template></div>';
|
||||
|
||||
tcb.overrideTemplate(TestComponent, template)
|
||||
.createAsync(TestComponent)
|
||||
|
||||
@@ -1,16 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
TestComponentBuilder,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, TestComponentBuilder, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit,} from 'angular2/testing_internal';
|
||||
|
||||
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
|
||||
|
||||
@@ -25,15 +13,13 @@ export function main() {
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
var html = '<div><copy-me template="ngIf booleanCondition">hello</copy-me></div>';
|
||||
|
||||
tcb.overrideTemplate(TestComponent, html)
|
||||
.createAsync(TestComponent)
|
||||
.then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('hello');
|
||||
async.done();
|
||||
});
|
||||
tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('hello');
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should work in a template element',
|
||||
@@ -41,44 +27,40 @@ export function main() {
|
||||
var html =
|
||||
'<div><template [ngIf]="booleanCondition"><copy-me>hello2</copy-me></template></div>';
|
||||
|
||||
tcb.overrideTemplate(TestComponent, html)
|
||||
.createAsync(TestComponent)
|
||||
.then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('hello2');
|
||||
async.done();
|
||||
});
|
||||
tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('hello2');
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should toggle node when condition changes',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
var html = '<div><copy-me template="ngIf booleanCondition">hello</copy-me></div>';
|
||||
|
||||
tcb.overrideTemplate(TestComponent, html)
|
||||
.createAsync(TestComponent)
|
||||
.then((fixture) => {
|
||||
fixture.debugElement.componentInstance.booleanCondition = false;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(0);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('');
|
||||
tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then((fixture) => {
|
||||
fixture.debugElement.componentInstance.booleanCondition = false;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(0);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('');
|
||||
|
||||
fixture.debugElement.componentInstance.booleanCondition = true;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('hello');
|
||||
fixture.debugElement.componentInstance.booleanCondition = true;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('hello');
|
||||
|
||||
fixture.debugElement.componentInstance.booleanCondition = false;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(0);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('');
|
||||
fixture.debugElement.componentInstance.booleanCondition = false;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(0);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('');
|
||||
|
||||
async.done();
|
||||
});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should handle nested if correctly',
|
||||
@@ -86,75 +68,70 @@ export function main() {
|
||||
var html =
|
||||
'<div><template [ngIf]="booleanCondition"><copy-me *ngIf="nestedBooleanCondition">hello</copy-me></template></div>';
|
||||
|
||||
tcb.overrideTemplate(TestComponent, html)
|
||||
.createAsync(TestComponent)
|
||||
.then((fixture) => {
|
||||
fixture.debugElement.componentInstance.booleanCondition = false;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(0);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('');
|
||||
tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then((fixture) => {
|
||||
fixture.debugElement.componentInstance.booleanCondition = false;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(0);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('');
|
||||
|
||||
fixture.debugElement.componentInstance.booleanCondition = true;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('hello');
|
||||
fixture.debugElement.componentInstance.booleanCondition = true;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('hello');
|
||||
|
||||
fixture.debugElement.componentInstance.nestedBooleanCondition = false;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(0);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('');
|
||||
fixture.debugElement.componentInstance.nestedBooleanCondition = false;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(0);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('');
|
||||
|
||||
fixture.debugElement.componentInstance.nestedBooleanCondition = true;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('hello');
|
||||
fixture.debugElement.componentInstance.nestedBooleanCondition = true;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('hello');
|
||||
|
||||
fixture.debugElement.componentInstance.booleanCondition = false;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(0);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('');
|
||||
fixture.debugElement.componentInstance.booleanCondition = false;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(0);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('');
|
||||
|
||||
async.done();
|
||||
});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should update several nodes with if',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
var html =
|
||||
'<div>' +
|
||||
var html = '<div>' +
|
||||
'<copy-me template="ngIf numberCondition + 1 >= 2">helloNumber</copy-me>' +
|
||||
'<copy-me template="ngIf stringCondition == \'foo\'">helloString</copy-me>' +
|
||||
'<copy-me template="ngIf functionCondition(stringCondition, numberCondition)">helloFunction</copy-me>' +
|
||||
'</div>';
|
||||
|
||||
tcb.overrideTemplate(TestComponent, html)
|
||||
.createAsync(TestComponent)
|
||||
.then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(3);
|
||||
expect(DOM.getText(fixture.debugElement.nativeElement))
|
||||
.toEqual('helloNumberhelloStringhelloFunction');
|
||||
tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(3);
|
||||
expect(DOM.getText(fixture.debugElement.nativeElement))
|
||||
.toEqual('helloNumberhelloStringhelloFunction');
|
||||
|
||||
fixture.debugElement.componentInstance.numberCondition = 0;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('helloString');
|
||||
fixture.debugElement.componentInstance.numberCondition = 0;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('helloString');
|
||||
|
||||
fixture.debugElement.componentInstance.numberCondition = 1;
|
||||
fixture.debugElement.componentInstance.stringCondition = "bar";
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('helloNumber');
|
||||
async.done();
|
||||
});
|
||||
fixture.debugElement.componentInstance.numberCondition = 1;
|
||||
fixture.debugElement.componentInstance.stringCondition = 'bar';
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('helloNumber');
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
|
||||
@@ -163,44 +140,38 @@ export function main() {
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
var html = '<div><copy-me template="ngIf numberCondition">hello</copy-me></div>';
|
||||
|
||||
tcb.overrideTemplate(TestComponent, html)
|
||||
.createAsync(TestComponent)
|
||||
.then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('hello');
|
||||
tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('hello');
|
||||
|
||||
fixture.debugElement.componentInstance.numberCondition = 2;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('hello');
|
||||
fixture.debugElement.componentInstance.numberCondition = 2;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(1);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('hello');
|
||||
|
||||
async.done();
|
||||
});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should not recreate the element if the condition goes from true to true (JS)',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
var html = '<div><copy-me template="ngIf numberCondition">hello</copy-me></div>';
|
||||
|
||||
tcb.overrideTemplate(TestComponent, html)
|
||||
.createAsync(TestComponent)
|
||||
.then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
DOM.addClass(DOM.querySelector(fixture.debugElement.nativeElement, 'copy-me'),
|
||||
"foo");
|
||||
tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
DOM.addClass(DOM.querySelector(fixture.debugElement.nativeElement, 'copy-me'), 'foo');
|
||||
|
||||
fixture.debugElement.componentInstance.numberCondition = 2;
|
||||
fixture.detectChanges();
|
||||
expect(
|
||||
DOM.hasClass(DOM.querySelector(fixture.debugElement.nativeElement, 'copy-me'),
|
||||
"foo"))
|
||||
.toBe(true);
|
||||
fixture.debugElement.componentInstance.numberCondition = 2;
|
||||
fixture.detectChanges();
|
||||
expect(DOM.hasClass(
|
||||
DOM.querySelector(fixture.debugElement.nativeElement, 'copy-me'), 'foo'))
|
||||
.toBe(true);
|
||||
|
||||
async.done();
|
||||
});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -209,15 +180,13 @@ export function main() {
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
var html = '<div><copy-me template="ngIf numberCondition">hello</copy-me></div>';
|
||||
|
||||
tcb.overrideTemplate(TestComponent, html)
|
||||
.createAsync(TestComponent)
|
||||
.then((fixture) => {
|
||||
expect(() => fixture.detectChanges()).toThrowError();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(0);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('');
|
||||
async.done();
|
||||
});
|
||||
tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then((fixture) => {
|
||||
expect(() => fixture.detectChanges()).toThrowError();
|
||||
expect(DOM.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
|
||||
.toEqual(0);
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('');
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -235,7 +204,7 @@ class TestComponent {
|
||||
this.booleanCondition = true;
|
||||
this.nestedBooleanCondition = true;
|
||||
this.numberCondition = 1;
|
||||
this.stringCondition = "foo";
|
||||
this.functionCondition = function(s, n) { return s == "foo" && n == 1; };
|
||||
this.stringCondition = 'foo';
|
||||
this.functionCondition = function(s, n) { return s == 'foo' && n == 1; };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
TestComponentBuilder,
|
||||
beforeEachProviders,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, TestComponentBuilder, beforeEachProviders, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit,} from 'angular2/testing_internal';
|
||||
|
||||
import {Component, Injectable, provide} from 'angular2/core';
|
||||
import {NgPlural, NgPluralCase, NgLocalization} from 'angular2/common';
|
||||
@@ -23,10 +10,10 @@ export function main() {
|
||||
it('should display the template according to the exact value',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
var template = '<div>' +
|
||||
'<ul [ngPlural]="switchValue">' +
|
||||
'<template ngPluralCase="=0"><li>you have no messages.</li></template>' +
|
||||
'<template ngPluralCase="=1"><li>you have one message.</li></template>' +
|
||||
'</ul></div>';
|
||||
'<ul [ngPlural]="switchValue">' +
|
||||
'<template ngPluralCase="=0"><li>you have no messages.</li></template>' +
|
||||
'<template ngPluralCase="=1"><li>you have one message.</li></template>' +
|
||||
'</ul></div>';
|
||||
|
||||
tcb.overrideTemplate(TestComponent, template)
|
||||
.createAsync(TestComponent)
|
||||
@@ -45,8 +32,7 @@ export function main() {
|
||||
|
||||
it('should display the template according to the category',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
var template =
|
||||
'<div>' +
|
||||
var template = '<div>' +
|
||||
'<ul [ngPlural]="switchValue">' +
|
||||
'<template ngPluralCase="few"><li>you have a few messages.</li></template>' +
|
||||
'<template ngPluralCase="many"><li>you have many messages.</li></template>' +
|
||||
@@ -69,8 +55,7 @@ export function main() {
|
||||
|
||||
it('should default to other when no matches are found',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
var template =
|
||||
'<div>' +
|
||||
var template = '<div>' +
|
||||
'<ul [ngPlural]="switchValue">' +
|
||||
'<template ngPluralCase="few"><li>you have a few messages.</li></template>' +
|
||||
'<template ngPluralCase="other"><li>default message.</li></template>' +
|
||||
@@ -89,8 +74,7 @@ export function main() {
|
||||
|
||||
it('should prioritize value matches over category matches',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
var template =
|
||||
'<div>' +
|
||||
var template = '<div>' +
|
||||
'<ul [ngPlural]="switchValue">' +
|
||||
'<template ngPluralCase="few"><li>you have a few messages.</li></template>' +
|
||||
'<template ngPluralCase="=2">you have two messages.</template>' +
|
||||
|
||||
@@ -1,18 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
TestComponentBuilder,
|
||||
beforeEach,
|
||||
beforeEachProviders,
|
||||
ddescribe,
|
||||
xdescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, TestComponentBuilder, beforeEach, beforeEachProviders, ddescribe, xdescribe, describe, el, expect, iit, inject, it, xit,} from 'angular2/testing_internal';
|
||||
|
||||
import {StringMapWrapper} from 'angular2/src/facade/collection';
|
||||
|
||||
|
||||
@@ -1,16 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
TestComponentBuilder,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, TestComponentBuilder, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit,} from 'angular2/testing_internal';
|
||||
|
||||
import {Component} from 'angular2/core';
|
||||
|
||||
@@ -22,10 +10,10 @@ export function main() {
|
||||
it('should switch amongst when values',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
var template = '<div>' +
|
||||
'<ul [ngSwitch]="switchValue">' +
|
||||
'<template ngSwitchWhen="a"><li>when a</li></template>' +
|
||||
'<template ngSwitchWhen="b"><li>when b</li></template>' +
|
||||
'</ul></div>';
|
||||
'<ul [ngSwitch]="switchValue">' +
|
||||
'<template ngSwitchWhen="a"><li>when a</li></template>' +
|
||||
'<template ngSwitchWhen="b"><li>when b</li></template>' +
|
||||
'</ul></div>';
|
||||
|
||||
tcb.overrideTemplate(TestComponent, template)
|
||||
.createAsync(TestComponent)
|
||||
@@ -48,10 +36,10 @@ export function main() {
|
||||
it('should switch amongst when values with fallback to default',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
var template = '<div>' +
|
||||
'<ul [ngSwitch]="switchValue">' +
|
||||
'<li template="ngSwitchWhen \'a\'">when a</li>' +
|
||||
'<li template="ngSwitchDefault">when default</li>' +
|
||||
'</ul></div>';
|
||||
'<ul [ngSwitch]="switchValue">' +
|
||||
'<li template="ngSwitchWhen \'a\'">when a</li>' +
|
||||
'<li template="ngSwitchDefault">when default</li>' +
|
||||
'</ul></div>';
|
||||
|
||||
tcb.overrideTemplate(TestComponent, template)
|
||||
.createAsync(TestComponent)
|
||||
@@ -74,14 +62,14 @@ export function main() {
|
||||
it('should support multiple whens with the same value',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
var template = '<div>' +
|
||||
'<ul [ngSwitch]="switchValue">' +
|
||||
'<template ngSwitchWhen="a"><li>when a1;</li></template>' +
|
||||
'<template ngSwitchWhen="b"><li>when b1;</li></template>' +
|
||||
'<template ngSwitchWhen="a"><li>when a2;</li></template>' +
|
||||
'<template ngSwitchWhen="b"><li>when b2;</li></template>' +
|
||||
'<template ngSwitchDefault><li>when default1;</li></template>' +
|
||||
'<template ngSwitchDefault><li>when default2;</li></template>' +
|
||||
'</ul></div>';
|
||||
'<ul [ngSwitch]="switchValue">' +
|
||||
'<template ngSwitchWhen="a"><li>when a1;</li></template>' +
|
||||
'<template ngSwitchWhen="b"><li>when b1;</li></template>' +
|
||||
'<template ngSwitchWhen="a"><li>when a2;</li></template>' +
|
||||
'<template ngSwitchWhen="b"><li>when b2;</li></template>' +
|
||||
'<template ngSwitchDefault><li>when default1;</li></template>' +
|
||||
'<template ngSwitchDefault><li>when default2;</li></template>' +
|
||||
'</ul></div>';
|
||||
|
||||
tcb.overrideTemplate(TestComponent, template)
|
||||
.createAsync(TestComponent)
|
||||
@@ -107,11 +95,11 @@ export function main() {
|
||||
it('should switch amongst when values',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
var template = '<div>' +
|
||||
'<ul [ngSwitch]="switchValue">' +
|
||||
'<template [ngSwitchWhen]="when1"><li>when 1;</li></template>' +
|
||||
'<template [ngSwitchWhen]="when2"><li>when 2;</li></template>' +
|
||||
'<template ngSwitchDefault><li>when default;</li></template>' +
|
||||
'</ul></div>';
|
||||
'<ul [ngSwitch]="switchValue">' +
|
||||
'<template [ngSwitchWhen]="when1"><li>when 1;</li></template>' +
|
||||
'<template [ngSwitchWhen]="when2"><li>when 2;</li></template>' +
|
||||
'<template ngSwitchDefault><li>when default;</li></template>' +
|
||||
'</ul></div>';
|
||||
|
||||
tcb.overrideTemplate(TestComponent, template)
|
||||
.createAsync(TestComponent)
|
||||
|
||||
@@ -1,16 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
TestComponentBuilder,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, TestComponentBuilder, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit,} from 'angular2/testing_internal';
|
||||
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
|
||||
import {Component, Directive} from 'angular2/core';
|
||||
import {ElementRef} from 'angular2/src/core/linker/element_ref';
|
||||
|
||||
@@ -1,41 +1,10 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
fakeAsync,
|
||||
flushMicrotasks,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
el,
|
||||
AsyncTestCompleter,
|
||||
inject,
|
||||
tick
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, fakeAsync, flushMicrotasks, it, iit, xit, expect, beforeEach, afterEach, el, AsyncTestCompleter, inject, tick} from 'angular2/testing_internal';
|
||||
|
||||
import {SpyNgControl, SpyValueAccessor} from '../spies';
|
||||
|
||||
import {QueryList} from 'angular2/core';
|
||||
|
||||
import {
|
||||
ControlGroup,
|
||||
Control,
|
||||
NgControlName,
|
||||
NgControlGroup,
|
||||
NgFormModel,
|
||||
ControlValueAccessor,
|
||||
Validators,
|
||||
NgForm,
|
||||
NgModel,
|
||||
NgFormControl,
|
||||
NgControl,
|
||||
DefaultValueAccessor,
|
||||
CheckboxControlValueAccessor,
|
||||
SelectControlValueAccessor,
|
||||
Validator
|
||||
} from 'angular2/common';
|
||||
import {ControlGroup, Control, NgControlName, NgControlGroup, NgFormModel, ControlValueAccessor, Validators, NgForm, NgModel, NgFormControl, NgControl, DefaultValueAccessor, CheckboxControlValueAccessor, SelectControlValueAccessor, Validator} from 'angular2/common';
|
||||
|
||||
|
||||
import {selectValueAccessor, composeValidators} from 'angular2/src/common/forms/directives/shared';
|
||||
@@ -53,13 +22,13 @@ class DummyControlValueAccessor implements ControlValueAccessor {
|
||||
}
|
||||
|
||||
class CustomValidatorDirective implements Validator {
|
||||
validate(c: Control): {[key: string]: any} { return {"custom": true}; }
|
||||
validate(c: Control): {[key: string]: any} { return {'custom': true}; }
|
||||
}
|
||||
|
||||
function asyncValidator(expected, timeout = 0) {
|
||||
return (c) => {
|
||||
var completer = PromiseWrapper.completer();
|
||||
var res = c.value != expected ? {"async": true} : null;
|
||||
var res = c.value != expected ? {'async': true} : null;
|
||||
if (timeout == 0) {
|
||||
completer.resolve(res);
|
||||
} else {
|
||||
@@ -70,71 +39,74 @@ function asyncValidator(expected, timeout = 0) {
|
||||
}
|
||||
|
||||
export function main() {
|
||||
describe("Form Directives", () => {
|
||||
describe('Form Directives', () => {
|
||||
var defaultAccessor;
|
||||
|
||||
beforeEach(() => { defaultAccessor = new DefaultValueAccessor(null, null); });
|
||||
|
||||
describe("shared", () => {
|
||||
describe("selectValueAccessor", () => {
|
||||
describe('shared', () => {
|
||||
describe('selectValueAccessor', () => {
|
||||
var dir: NgControl;
|
||||
|
||||
beforeEach(() => { dir = <any>new SpyNgControl(); });
|
||||
|
||||
it("should throw when given an empty array",
|
||||
it('should throw when given an empty array',
|
||||
() => { expect(() => selectValueAccessor(dir, [])).toThrowError(); });
|
||||
|
||||
it("should return the default value accessor when no other provided",
|
||||
it('should return the default value accessor when no other provided',
|
||||
() => { expect(selectValueAccessor(dir, [defaultAccessor])).toEqual(defaultAccessor); });
|
||||
|
||||
it("should return checkbox accessor when provided", () => {
|
||||
it('should return checkbox accessor when provided', () => {
|
||||
var checkboxAccessor = new CheckboxControlValueAccessor(null, null);
|
||||
expect(selectValueAccessor(dir, [defaultAccessor, checkboxAccessor]))
|
||||
.toEqual(checkboxAccessor);
|
||||
expect(selectValueAccessor(dir, [
|
||||
defaultAccessor, checkboxAccessor
|
||||
])).toEqual(checkboxAccessor);
|
||||
});
|
||||
|
||||
it("should return select accessor when provided", () => {
|
||||
it('should return select accessor when provided', () => {
|
||||
var selectAccessor = new SelectControlValueAccessor(null, null);
|
||||
expect(selectValueAccessor(dir, [defaultAccessor, selectAccessor]))
|
||||
.toEqual(selectAccessor);
|
||||
expect(selectValueAccessor(dir, [
|
||||
defaultAccessor, selectAccessor
|
||||
])).toEqual(selectAccessor);
|
||||
});
|
||||
|
||||
it("should throw when more than one build-in accessor is provided", () => {
|
||||
it('should throw when more than one build-in accessor is provided', () => {
|
||||
var checkboxAccessor = new CheckboxControlValueAccessor(null, null);
|
||||
var selectAccessor = new SelectControlValueAccessor(null, null);
|
||||
expect(() => selectValueAccessor(dir, [checkboxAccessor, selectAccessor])).toThrowError();
|
||||
});
|
||||
|
||||
it("should return custom accessor when provided", () => {
|
||||
it('should return custom accessor when provided', () => {
|
||||
var customAccessor = new SpyValueAccessor();
|
||||
var checkboxAccessor = new CheckboxControlValueAccessor(null, null);
|
||||
expect(selectValueAccessor(dir, [defaultAccessor, customAccessor, checkboxAccessor]))
|
||||
.toEqual(customAccessor);
|
||||
expect(selectValueAccessor(dir, [
|
||||
defaultAccessor, customAccessor, checkboxAccessor
|
||||
])).toEqual(customAccessor);
|
||||
});
|
||||
|
||||
it("should throw when more than one custom accessor is provided", () => {
|
||||
it('should throw when more than one custom accessor is provided', () => {
|
||||
var customAccessor: ControlValueAccessor = <any>new SpyValueAccessor();
|
||||
expect(() => selectValueAccessor(dir, [customAccessor, customAccessor])).toThrowError();
|
||||
});
|
||||
});
|
||||
|
||||
describe("composeValidators", () => {
|
||||
it("should compose functions", () => {
|
||||
var dummy1 = (_) => ({"dummy1": true});
|
||||
var dummy2 = (_) => ({"dummy2": true});
|
||||
describe('composeValidators', () => {
|
||||
it('should compose functions', () => {
|
||||
var dummy1 = (_) => ({'dummy1': true});
|
||||
var dummy2 = (_) => ({'dummy2': true});
|
||||
var v = composeValidators([dummy1, dummy2]);
|
||||
expect(v(new Control(""))).toEqual({"dummy1": true, "dummy2": true});
|
||||
expect(v(new Control(''))).toEqual({'dummy1': true, 'dummy2': true});
|
||||
});
|
||||
|
||||
it("should compose validator directives", () => {
|
||||
var dummy1 = (_) => ({"dummy1": true});
|
||||
it('should compose validator directives', () => {
|
||||
var dummy1 = (_) => ({'dummy1': true});
|
||||
var v = composeValidators([dummy1, new CustomValidatorDirective()]);
|
||||
expect(v(new Control(""))).toEqual({"dummy1": true, "custom": true});
|
||||
expect(v(new Control(''))).toEqual({'dummy1': true, 'custom': true});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("NgFormModel", () => {
|
||||
describe('NgFormModel', () => {
|
||||
var form;
|
||||
var formModel: ControlGroup;
|
||||
var loginControlDir;
|
||||
@@ -142,19 +114,19 @@ export function main() {
|
||||
beforeEach(() => {
|
||||
form = new NgFormModel([], []);
|
||||
formModel = new ControlGroup({
|
||||
"login": new Control(),
|
||||
"passwords":
|
||||
new ControlGroup({"password": new Control(), "passwordConfirm": new Control()})
|
||||
'login': new Control(),
|
||||
'passwords':
|
||||
new ControlGroup({'password': new Control(), 'passwordConfirm': new Control()})
|
||||
});
|
||||
form.form = formModel;
|
||||
|
||||
loginControlDir = new NgControlName(form, [Validators.required],
|
||||
[asyncValidator("expected")], [defaultAccessor]);
|
||||
loginControlDir.name = "login";
|
||||
loginControlDir = new NgControlName(
|
||||
form, [Validators.required], [asyncValidator('expected')], [defaultAccessor]);
|
||||
loginControlDir.name = 'login';
|
||||
loginControlDir.valueAccessor = new DummyControlValueAccessor();
|
||||
});
|
||||
|
||||
it("should reexport control properties", () => {
|
||||
it('should reexport control properties', () => {
|
||||
expect(form.control).toBe(formModel);
|
||||
expect(form.value).toBe(formModel.value);
|
||||
expect(form.valid).toBe(formModel.valid);
|
||||
@@ -165,130 +137,132 @@ export function main() {
|
||||
expect(form.untouched).toBe(formModel.untouched);
|
||||
});
|
||||
|
||||
describe("addControl", () => {
|
||||
it("should throw when no control found", () => {
|
||||
describe('addControl', () => {
|
||||
it('should throw when no control found', () => {
|
||||
var dir = new NgControlName(form, null, null, [defaultAccessor]);
|
||||
dir.name = "invalidName";
|
||||
dir.name = 'invalidName';
|
||||
|
||||
expect(() => form.addControl(dir))
|
||||
.toThrowError(new RegExp("Cannot find control 'invalidName'"));
|
||||
.toThrowError(new RegExp('Cannot find control \'invalidName\''));
|
||||
});
|
||||
|
||||
it("should throw when no value accessor", () => {
|
||||
it('should throw when no value accessor', () => {
|
||||
var dir = new NgControlName(form, null, null, null);
|
||||
dir.name = "login";
|
||||
dir.name = 'login';
|
||||
|
||||
expect(() => form.addControl(dir))
|
||||
.toThrowError(new RegExp("No value accessor for 'login'"));
|
||||
.toThrowError(new RegExp('No value accessor for \'login\''));
|
||||
});
|
||||
|
||||
it("should set up validators", fakeAsync(() => {
|
||||
it('should set up validators', fakeAsync(() => {
|
||||
form.addControl(loginControlDir);
|
||||
|
||||
// sync validators are set
|
||||
expect(formModel.hasError("required", ["login"])).toBe(true);
|
||||
expect(formModel.hasError("async", ["login"])).toBe(false);
|
||||
expect(formModel.hasError('required', ['login'])).toBe(true);
|
||||
expect(formModel.hasError('async', ['login'])).toBe(false);
|
||||
|
||||
(<Control>formModel.find(["login"])).updateValue("invalid value");
|
||||
(<Control>formModel.find(['login'])).updateValue('invalid value');
|
||||
|
||||
// sync validator passes, running async validators
|
||||
expect(formModel.pending).toBe(true);
|
||||
|
||||
tick();
|
||||
|
||||
expect(formModel.hasError("required", ["login"])).toBe(false);
|
||||
expect(formModel.hasError("async", ["login"])).toBe(true);
|
||||
expect(formModel.hasError('required', ['login'])).toBe(false);
|
||||
expect(formModel.hasError('async', ['login'])).toBe(true);
|
||||
}));
|
||||
|
||||
it("should write value to the DOM", () => {
|
||||
(<Control>formModel.find(["login"])).updateValue("initValue");
|
||||
it('should write value to the DOM', () => {
|
||||
(<Control>formModel.find(['login'])).updateValue('initValue');
|
||||
|
||||
form.addControl(loginControlDir);
|
||||
|
||||
expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual("initValue");
|
||||
expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual('initValue');
|
||||
});
|
||||
|
||||
it("should add the directive to the list of directives included in the form", () => {
|
||||
it('should add the directive to the list of directives included in the form', () => {
|
||||
form.addControl(loginControlDir);
|
||||
expect(form.directives).toEqual([loginControlDir]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("addControlGroup", () => {
|
||||
describe('addControlGroup', () => {
|
||||
var matchingPasswordsValidator = (g) => {
|
||||
if (g.controls["password"].value != g.controls["passwordConfirm"].value) {
|
||||
return {"differentPasswords": true};
|
||||
if (g.controls['password'].value != g.controls['passwordConfirm'].value) {
|
||||
return {'differentPasswords': true};
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
it("should set up validator", fakeAsync(() => {
|
||||
var group = new NgControlGroup(form, [matchingPasswordsValidator],
|
||||
[asyncValidator('expected')]);
|
||||
group.name = "passwords";
|
||||
it('should set up validator', fakeAsync(() => {
|
||||
var group = new NgControlGroup(
|
||||
form, [matchingPasswordsValidator], [asyncValidator('expected')]);
|
||||
group.name = 'passwords';
|
||||
form.addControlGroup(group);
|
||||
|
||||
(<Control>formModel.find(["passwords", "password"])).updateValue("somePassword");
|
||||
(<Control>formModel.find(["passwords", "passwordConfirm"]))
|
||||
.updateValue("someOtherPassword");
|
||||
(<Control>formModel.find(['passwords', 'password'])).updateValue('somePassword');
|
||||
(<Control>formModel.find([
|
||||
'passwords', 'passwordConfirm'
|
||||
])).updateValue('someOtherPassword');
|
||||
|
||||
// sync validators are set
|
||||
expect(formModel.hasError("differentPasswords", ["passwords"])).toEqual(true);
|
||||
expect(formModel.hasError('differentPasswords', ['passwords'])).toEqual(true);
|
||||
|
||||
(<Control>formModel.find(["passwords", "passwordConfirm"]))
|
||||
.updateValue("somePassword");
|
||||
(<Control>formModel.find([
|
||||
'passwords', 'passwordConfirm'
|
||||
])).updateValue('somePassword');
|
||||
|
||||
// sync validators pass, running async validators
|
||||
expect(formModel.pending).toBe(true);
|
||||
|
||||
tick();
|
||||
|
||||
expect(formModel.hasError("async", ["passwords"])).toBe(true);
|
||||
expect(formModel.hasError('async', ['passwords'])).toBe(true);
|
||||
}));
|
||||
});
|
||||
|
||||
describe("removeControl", () => {
|
||||
it("should remove the directive to the list of directives included in the form", () => {
|
||||
describe('removeControl', () => {
|
||||
it('should remove the directive to the list of directives included in the form', () => {
|
||||
form.addControl(loginControlDir);
|
||||
form.removeControl(loginControlDir);
|
||||
expect(form.directives).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ngOnChanges", () => {
|
||||
it("should update dom values of all the directives", () => {
|
||||
describe('ngOnChanges', () => {
|
||||
it('should update dom values of all the directives', () => {
|
||||
form.addControl(loginControlDir);
|
||||
|
||||
(<Control>formModel.find(["login"])).updateValue("new value");
|
||||
(<Control>formModel.find(['login'])).updateValue('new value');
|
||||
|
||||
form.ngOnChanges({});
|
||||
|
||||
expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual("new value");
|
||||
expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual('new value');
|
||||
});
|
||||
|
||||
it("should set up a sync validator", () => {
|
||||
var formValidator = (c) => ({"custom": true});
|
||||
it('should set up a sync validator', () => {
|
||||
var formValidator = (c) => ({'custom': true});
|
||||
var f = new NgFormModel([formValidator], []);
|
||||
f.form = formModel;
|
||||
f.ngOnChanges({"form": new SimpleChange(null, null)});
|
||||
f.ngOnChanges({'form': new SimpleChange(null, null)});
|
||||
|
||||
expect(formModel.errors).toEqual({"custom": true});
|
||||
expect(formModel.errors).toEqual({'custom': true});
|
||||
});
|
||||
|
||||
it("should set up an async validator", fakeAsync(() => {
|
||||
var f = new NgFormModel([], [asyncValidator("expected")]);
|
||||
it('should set up an async validator', fakeAsync(() => {
|
||||
var f = new NgFormModel([], [asyncValidator('expected')]);
|
||||
f.form = formModel;
|
||||
f.ngOnChanges({"form": new SimpleChange(null, null)});
|
||||
f.ngOnChanges({'form': new SimpleChange(null, null)});
|
||||
|
||||
tick();
|
||||
|
||||
expect(formModel.errors).toEqual({"async": true});
|
||||
expect(formModel.errors).toEqual({'async': true});
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
describe("NgForm", () => {
|
||||
describe('NgForm', () => {
|
||||
var form;
|
||||
var formModel: ControlGroup;
|
||||
var loginControlDir;
|
||||
@@ -299,14 +273,14 @@ export function main() {
|
||||
formModel = form.form;
|
||||
|
||||
personControlGroupDir = new NgControlGroup(form, [], []);
|
||||
personControlGroupDir.name = "person";
|
||||
personControlGroupDir.name = 'person';
|
||||
|
||||
loginControlDir = new NgControlName(personControlGroupDir, null, null, [defaultAccessor]);
|
||||
loginControlDir.name = "login";
|
||||
loginControlDir.name = 'login';
|
||||
loginControlDir.valueAccessor = new DummyControlValueAccessor();
|
||||
});
|
||||
|
||||
it("should reexport control properties", () => {
|
||||
it('should reexport control properties', () => {
|
||||
expect(form.control).toBe(formModel);
|
||||
expect(form.value).toBe(formModel.value);
|
||||
expect(form.valid).toBe(formModel.valid);
|
||||
@@ -317,21 +291,21 @@ export function main() {
|
||||
expect(form.untouched).toBe(formModel.untouched);
|
||||
});
|
||||
|
||||
describe("addControl & addControlGroup", () => {
|
||||
it("should create a control with the given name", fakeAsync(() => {
|
||||
describe('addControl & addControlGroup', () => {
|
||||
it('should create a control with the given name', fakeAsync(() => {
|
||||
form.addControlGroup(personControlGroupDir);
|
||||
form.addControl(loginControlDir);
|
||||
|
||||
flushMicrotasks();
|
||||
|
||||
expect(formModel.find(["person", "login"])).not.toBeNull;
|
||||
expect(formModel.find(['person', 'login'])).not.toBeNull;
|
||||
}));
|
||||
|
||||
// should update the form's value and validity
|
||||
});
|
||||
|
||||
describe("removeControl & removeControlGroup", () => {
|
||||
it("should remove control", fakeAsync(() => {
|
||||
describe('removeControl & removeControlGroup', () => {
|
||||
it('should remove control', fakeAsync(() => {
|
||||
form.addControlGroup(personControlGroupDir);
|
||||
form.addControl(loginControlDir);
|
||||
|
||||
@@ -340,45 +314,45 @@ export function main() {
|
||||
|
||||
flushMicrotasks();
|
||||
|
||||
expect(formModel.find(["person"])).toBeNull();
|
||||
expect(formModel.find(["person", "login"])).toBeNull();
|
||||
expect(formModel.find(['person'])).toBeNull();
|
||||
expect(formModel.find(['person', 'login'])).toBeNull();
|
||||
}));
|
||||
|
||||
// should update the form's value and validity
|
||||
});
|
||||
|
||||
it("should set up sync validator", fakeAsync(() => {
|
||||
var formValidator = (c) => ({"custom": true});
|
||||
it('should set up sync validator', fakeAsync(() => {
|
||||
var formValidator = (c) => ({'custom': true});
|
||||
var f = new NgForm([formValidator], []);
|
||||
|
||||
tick();
|
||||
|
||||
expect(f.form.errors).toEqual({"custom": true});
|
||||
expect(f.form.errors).toEqual({'custom': true});
|
||||
}));
|
||||
|
||||
it("should set up async validator", fakeAsync(() => {
|
||||
var f = new NgForm([], [asyncValidator("expected")]);
|
||||
it('should set up async validator', fakeAsync(() => {
|
||||
var f = new NgForm([], [asyncValidator('expected')]);
|
||||
|
||||
tick();
|
||||
|
||||
expect(f.form.errors).toEqual({"async": true});
|
||||
expect(f.form.errors).toEqual({'async': true});
|
||||
}));
|
||||
});
|
||||
|
||||
describe("NgControlGroup", () => {
|
||||
describe('NgControlGroup', () => {
|
||||
var formModel;
|
||||
var controlGroupDir;
|
||||
|
||||
beforeEach(() => {
|
||||
formModel = new ControlGroup({"login": new Control(null)});
|
||||
formModel = new ControlGroup({'login': new Control(null)});
|
||||
|
||||
var parent = new NgFormModel([], []);
|
||||
parent.form = new ControlGroup({"group": formModel});
|
||||
parent.form = new ControlGroup({'group': formModel});
|
||||
controlGroupDir = new NgControlGroup(parent, [], []);
|
||||
controlGroupDir.name = "group";
|
||||
controlGroupDir.name = 'group';
|
||||
});
|
||||
|
||||
it("should reexport control properties", () => {
|
||||
it('should reexport control properties', () => {
|
||||
expect(controlGroupDir.control).toBe(formModel);
|
||||
expect(controlGroupDir.value).toBe(formModel.value);
|
||||
expect(controlGroupDir.valid).toBe(formModel.valid);
|
||||
@@ -390,7 +364,7 @@ export function main() {
|
||||
});
|
||||
});
|
||||
|
||||
describe("NgFormControl", () => {
|
||||
describe('NgFormControl', () => {
|
||||
var controlDir;
|
||||
var control;
|
||||
var checkProperties = function(control) {
|
||||
@@ -412,36 +386,36 @@ export function main() {
|
||||
controlDir.form = control;
|
||||
});
|
||||
|
||||
it("should reexport control properties", () => { checkProperties(control); });
|
||||
it('should reexport control properties', () => { checkProperties(control); });
|
||||
|
||||
it("should reexport new control properties", () => {
|
||||
it('should reexport new control properties', () => {
|
||||
var newControl = new Control(null);
|
||||
controlDir.form = newControl;
|
||||
controlDir.ngOnChanges({"form": new SimpleChange(control, newControl)});
|
||||
controlDir.ngOnChanges({'form': new SimpleChange(control, newControl)});
|
||||
|
||||
checkProperties(newControl);
|
||||
});
|
||||
|
||||
it("should set up validator", () => {
|
||||
it('should set up validator', () => {
|
||||
expect(control.valid).toBe(true);
|
||||
|
||||
// this will add the required validator and recalculate the validity
|
||||
controlDir.ngOnChanges({"form": new SimpleChange(null, control)});
|
||||
controlDir.ngOnChanges({'form': new SimpleChange(null, control)});
|
||||
|
||||
expect(control.valid).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("NgModel", () => {
|
||||
describe('NgModel', () => {
|
||||
var ngModel;
|
||||
|
||||
beforeEach(() => {
|
||||
ngModel =
|
||||
new NgModel([Validators.required], [asyncValidator("expected")], [defaultAccessor]);
|
||||
new NgModel([Validators.required], [asyncValidator('expected')], [defaultAccessor]);
|
||||
ngModel.valueAccessor = new DummyControlValueAccessor();
|
||||
});
|
||||
|
||||
it("should reexport control properties", () => {
|
||||
it('should reexport control properties', () => {
|
||||
var control = ngModel.control;
|
||||
expect(ngModel.control).toBe(control);
|
||||
expect(ngModel.value).toBe(control.value);
|
||||
@@ -453,34 +427,34 @@ export function main() {
|
||||
expect(ngModel.untouched).toBe(control.untouched);
|
||||
});
|
||||
|
||||
it("should set up validator", fakeAsync(() => {
|
||||
it('should set up validator', fakeAsync(() => {
|
||||
// this will add the required validator and recalculate the validity
|
||||
ngModel.ngOnChanges({});
|
||||
tick();
|
||||
|
||||
expect(ngModel.control.errors).toEqual({"required": true});
|
||||
expect(ngModel.control.errors).toEqual({'required': true});
|
||||
|
||||
ngModel.control.updateValue("someValue");
|
||||
ngModel.control.updateValue('someValue');
|
||||
tick();
|
||||
|
||||
expect(ngModel.control.errors).toEqual({"async": true});
|
||||
expect(ngModel.control.errors).toEqual({'async': true});
|
||||
}));
|
||||
});
|
||||
|
||||
describe("NgControlName", () => {
|
||||
describe('NgControlName', () => {
|
||||
var formModel;
|
||||
var controlNameDir;
|
||||
|
||||
beforeEach(() => {
|
||||
formModel = new Control("name");
|
||||
formModel = new Control('name');
|
||||
|
||||
var parent = new NgFormModel([], []);
|
||||
parent.form = new ControlGroup({"name": formModel});
|
||||
parent.form = new ControlGroup({'name': formModel});
|
||||
controlNameDir = new NgControlName(parent, [], [], [defaultAccessor]);
|
||||
controlNameDir.name = "name";
|
||||
controlNameDir.name = 'name';
|
||||
});
|
||||
|
||||
it("should reexport control properties", () => {
|
||||
it('should reexport control properties', () => {
|
||||
expect(controlNameDir.control).toBe(formModel);
|
||||
expect(controlNameDir.value).toBe(formModel.value);
|
||||
expect(controlNameDir.valid).toBe(formModel.valid);
|
||||
|
||||
@@ -1,14 +1,4 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
el
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, el} from 'angular2/testing_internal';
|
||||
import {Control, FormBuilder} from 'angular2/common';
|
||||
import {PromiseWrapper} from 'angular2/src/facade/promise';
|
||||
|
||||
@@ -16,53 +6,53 @@ export function main() {
|
||||
function syncValidator(_) { return null; }
|
||||
function asyncValidator(_) { return PromiseWrapper.resolve(null); }
|
||||
|
||||
describe("Form Builder", () => {
|
||||
describe('Form Builder', () => {
|
||||
var b;
|
||||
|
||||
beforeEach(() => { b = new FormBuilder(); });
|
||||
|
||||
it("should create controls from a value", () => {
|
||||
var g = b.group({"login": "some value"});
|
||||
it('should create controls from a value', () => {
|
||||
var g = b.group({'login': 'some value'});
|
||||
|
||||
expect(g.controls["login"].value).toEqual("some value");
|
||||
expect(g.controls['login'].value).toEqual('some value');
|
||||
});
|
||||
|
||||
it("should create controls from an array", () => {
|
||||
it('should create controls from an array', () => {
|
||||
var g = b.group(
|
||||
{"login": ["some value"], "password": ["some value", syncValidator, asyncValidator]});
|
||||
{'login': ['some value'], 'password': ['some value', syncValidator, asyncValidator]});
|
||||
|
||||
expect(g.controls["login"].value).toEqual("some value");
|
||||
expect(g.controls["password"].value).toEqual("some value");
|
||||
expect(g.controls["password"].validator).toEqual(syncValidator);
|
||||
expect(g.controls["password"].asyncValidator).toEqual(asyncValidator);
|
||||
expect(g.controls['login'].value).toEqual('some value');
|
||||
expect(g.controls['password'].value).toEqual('some value');
|
||||
expect(g.controls['password'].validator).toEqual(syncValidator);
|
||||
expect(g.controls['password'].asyncValidator).toEqual(asyncValidator);
|
||||
});
|
||||
|
||||
it("should use controls", () => {
|
||||
var g = b.group({"login": b.control("some value", syncValidator, asyncValidator)});
|
||||
it('should use controls', () => {
|
||||
var g = b.group({'login': b.control('some value', syncValidator, asyncValidator)});
|
||||
|
||||
expect(g.controls["login"].value).toEqual("some value");
|
||||
expect(g.controls["login"].validator).toBe(syncValidator);
|
||||
expect(g.controls["login"].asyncValidator).toBe(asyncValidator);
|
||||
expect(g.controls['login'].value).toEqual('some value');
|
||||
expect(g.controls['login'].validator).toBe(syncValidator);
|
||||
expect(g.controls['login'].asyncValidator).toBe(asyncValidator);
|
||||
});
|
||||
|
||||
it("should create groups with optional controls", () => {
|
||||
var g = b.group({"login": "some value"}, {"optionals": {"login": false}});
|
||||
it('should create groups with optional controls', () => {
|
||||
var g = b.group({'login': 'some value'}, {'optionals': {'login': false}});
|
||||
|
||||
expect(g.contains("login")).toEqual(false);
|
||||
expect(g.contains('login')).toEqual(false);
|
||||
});
|
||||
|
||||
it("should create groups with a custom validator", () => {
|
||||
var g = b.group({"login": "some value"},
|
||||
{"validator": syncValidator, "asyncValidator": asyncValidator});
|
||||
it('should create groups with a custom validator', () => {
|
||||
var g = b.group(
|
||||
{'login': 'some value'}, {'validator': syncValidator, 'asyncValidator': asyncValidator});
|
||||
|
||||
expect(g.validator).toBe(syncValidator);
|
||||
expect(g.asyncValidator).toBe(asyncValidator);
|
||||
});
|
||||
|
||||
it("should create control arrays", () => {
|
||||
var c = b.control("three");
|
||||
var a = b.array(["one", ["two", syncValidator], c, b.array(['four'])], syncValidator,
|
||||
asyncValidator);
|
||||
it('should create control arrays', () => {
|
||||
var c = b.control('three');
|
||||
var a = b.array(
|
||||
['one', ['two', syncValidator], c, b.array(['four'])], syncValidator, asyncValidator);
|
||||
|
||||
expect(a.value).toEqual(['one', 'two', 'three', ['four']]);
|
||||
expect(a.validator).toBe(syncValidator);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,16 +1,4 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
fakeAsync,
|
||||
tick,
|
||||
el
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, fakeAsync, tick, el} from 'angular2/testing_internal';
|
||||
import {ControlGroup, Control, Validators, AbstractControl, ControlArray} from 'angular2/common';
|
||||
import {PromiseWrapper} from 'angular2/src/facade/promise';
|
||||
import {EventEmitter, ObservableWrapper, TimerWrapper} from 'angular2/src/facade/async';
|
||||
@@ -25,95 +13,98 @@ export function main() {
|
||||
}
|
||||
}
|
||||
|
||||
describe("Validators", () => {
|
||||
describe("required", () => {
|
||||
it("should error on an empty string",
|
||||
() => { expect(Validators.required(new Control(""))).toEqual({"required": true}); });
|
||||
describe('Validators', () => {
|
||||
describe('required', () => {
|
||||
it('should error on an empty string',
|
||||
() => { expect(Validators.required(new Control(''))).toEqual({'required': true}); });
|
||||
|
||||
it("should error on null",
|
||||
() => { expect(Validators.required(new Control(null))).toEqual({"required": true}); });
|
||||
it('should error on null',
|
||||
() => { expect(Validators.required(new Control(null))).toEqual({'required': true}); });
|
||||
|
||||
it("should not error on a non-empty string",
|
||||
() => { expect(Validators.required(new Control("not empty"))).toEqual(null); });
|
||||
it('should not error on a non-empty string',
|
||||
() => { expect(Validators.required(new Control('not empty'))).toEqual(null); });
|
||||
|
||||
it("should accept zero as valid",
|
||||
it('should accept zero as valid',
|
||||
() => { expect(Validators.required(new Control(0))).toEqual(null); });
|
||||
});
|
||||
|
||||
describe("minLength", () => {
|
||||
it("should not error on an empty string",
|
||||
() => { expect(Validators.minLength(2)(new Control(""))).toEqual(null); });
|
||||
describe('minLength', () => {
|
||||
it('should not error on an empty string',
|
||||
() => { expect(Validators.minLength(2)(new Control(''))).toEqual(null); });
|
||||
|
||||
it("should not error on null",
|
||||
it('should not error on null',
|
||||
() => { expect(Validators.minLength(2)(new Control(null))).toEqual(null); });
|
||||
|
||||
it("should not error on valid strings",
|
||||
() => { expect(Validators.minLength(2)(new Control("aa"))).toEqual(null); });
|
||||
it('should not error on valid strings',
|
||||
() => { expect(Validators.minLength(2)(new Control('aa'))).toEqual(null); });
|
||||
|
||||
it("should error on short strings", () => {
|
||||
expect(Validators.minLength(2)(new Control("a")))
|
||||
.toEqual({"minlength": {"requiredLength": 2, "actualLength": 1}});
|
||||
it('should error on short strings', () => {
|
||||
expect(Validators.minLength(2)(new Control('a'))).toEqual({
|
||||
'minlength': {'requiredLength': 2, 'actualLength': 1}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("maxLength", () => {
|
||||
it("should not error on an empty string",
|
||||
() => { expect(Validators.maxLength(2)(new Control(""))).toEqual(null); });
|
||||
describe('maxLength', () => {
|
||||
it('should not error on an empty string',
|
||||
() => { expect(Validators.maxLength(2)(new Control(''))).toEqual(null); });
|
||||
|
||||
it("should not error on null",
|
||||
it('should not error on null',
|
||||
() => { expect(Validators.maxLength(2)(new Control(null))).toEqual(null); });
|
||||
|
||||
it("should not error on valid strings",
|
||||
() => { expect(Validators.maxLength(2)(new Control("aa"))).toEqual(null); });
|
||||
it('should not error on valid strings',
|
||||
() => { expect(Validators.maxLength(2)(new Control('aa'))).toEqual(null); });
|
||||
|
||||
it("should error on long strings", () => {
|
||||
expect(Validators.maxLength(2)(new Control("aaa")))
|
||||
.toEqual({"maxlength": {"requiredLength": 2, "actualLength": 3}});
|
||||
it('should error on long strings', () => {
|
||||
expect(Validators.maxLength(2)(new Control('aaa'))).toEqual({
|
||||
'maxlength': {'requiredLength': 2, 'actualLength': 3}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("pattern", () => {
|
||||
it("should not error on an empty string",
|
||||
() => { expect(Validators.pattern("[a-zA-Z ]*")(new Control(""))).toEqual(null); });
|
||||
describe('pattern', () => {
|
||||
it('should not error on an empty string',
|
||||
() => { expect(Validators.pattern('[a-zA-Z ]*')(new Control(''))).toEqual(null); });
|
||||
|
||||
it("should not error on null",
|
||||
() => { expect(Validators.pattern("[a-zA-Z ]*")(new Control(null))).toEqual(null); });
|
||||
it('should not error on null',
|
||||
() => { expect(Validators.pattern('[a-zA-Z ]*')(new Control(null))).toEqual(null); });
|
||||
|
||||
it("should not error on valid strings",
|
||||
() => { expect(Validators.pattern("[a-zA-Z ]*")(new Control("aaAA"))).toEqual(null); });
|
||||
it('should not error on valid strings',
|
||||
() => { expect(Validators.pattern('[a-zA-Z ]*')(new Control('aaAA'))).toEqual(null); });
|
||||
|
||||
it("should error on failure to match string", () => {
|
||||
expect(Validators.pattern("[a-zA-Z ]*")(new Control("aaa0")))
|
||||
.toEqual({"pattern": {"requiredPattern": "^[a-zA-Z ]*$", "actualValue": "aaa0"}});
|
||||
it('should error on failure to match string', () => {
|
||||
expect(Validators.pattern('[a-zA-Z ]*')(new Control('aaa0'))).toEqual({
|
||||
'pattern': {'requiredPattern': '^[a-zA-Z ]*$', 'actualValue': 'aaa0'}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("compose", () => {
|
||||
it("should return null when given null",
|
||||
describe('compose', () => {
|
||||
it('should return null when given null',
|
||||
() => { expect(Validators.compose(null)).toBe(null); });
|
||||
|
||||
it("should collect errors from all the validators", () => {
|
||||
var c = Validators.compose([validator("a", true), validator("b", true)]);
|
||||
expect(c(new Control(""))).toEqual({"a": true, "b": true});
|
||||
it('should collect errors from all the validators', () => {
|
||||
var c = Validators.compose([validator('a', true), validator('b', true)]);
|
||||
expect(c(new Control(''))).toEqual({'a': true, 'b': true});
|
||||
});
|
||||
|
||||
it("should run validators left to right", () => {
|
||||
var c = Validators.compose([validator("a", 1), validator("a", 2)]);
|
||||
expect(c(new Control(""))).toEqual({"a": 2});
|
||||
it('should run validators left to right', () => {
|
||||
var c = Validators.compose([validator('a', 1), validator('a', 2)]);
|
||||
expect(c(new Control(''))).toEqual({'a': 2});
|
||||
});
|
||||
|
||||
it("should return null when no errors", () => {
|
||||
it('should return null when no errors', () => {
|
||||
var c = Validators.compose([Validators.nullValidator, Validators.nullValidator]);
|
||||
expect(c(new Control(""))).toEqual(null);
|
||||
expect(c(new Control(''))).toEqual(null);
|
||||
});
|
||||
|
||||
it("should ignore nulls", () => {
|
||||
it('should ignore nulls', () => {
|
||||
var c = Validators.compose([null, Validators.required]);
|
||||
expect(c(new Control(""))).toEqual({"required": true});
|
||||
expect(c(new Control(''))).toEqual({'required': true});
|
||||
});
|
||||
});
|
||||
|
||||
describe("composeAsync", () => {
|
||||
describe('composeAsync', () => {
|
||||
function asyncValidator(expected, response) {
|
||||
return (c) => {
|
||||
var emitter = new EventEmitter();
|
||||
@@ -130,43 +121,42 @@ export function main() {
|
||||
};
|
||||
}
|
||||
|
||||
it("should return null when given null",
|
||||
it('should return null when given null',
|
||||
() => { expect(Validators.composeAsync(null)).toEqual(null); });
|
||||
|
||||
it("should collect errors from all the validators", fakeAsync(() => {
|
||||
it('should collect errors from all the validators', fakeAsync(() => {
|
||||
var c = Validators.composeAsync([
|
||||
asyncValidator("expected", {"one": true}),
|
||||
asyncValidator("expected", {"two": true})
|
||||
asyncValidator('expected', {'one': true}), asyncValidator('expected', {'two': true})
|
||||
]);
|
||||
|
||||
var value = null;
|
||||
(<Promise<any>>c(new Control("invalid"))).then(v => value = v);
|
||||
(<Promise<any>>c(new Control('invalid'))).then(v => value = v);
|
||||
|
||||
tick(1);
|
||||
|
||||
expect(value).toEqual({"one": true, "two": true});
|
||||
expect(value).toEqual({'one': true, 'two': true});
|
||||
}));
|
||||
|
||||
it("should return null when no errors", fakeAsync(() => {
|
||||
var c = Validators.composeAsync([asyncValidator("expected", {"one": true})]);
|
||||
it('should return null when no errors', fakeAsync(() => {
|
||||
var c = Validators.composeAsync([asyncValidator('expected', {'one': true})]);
|
||||
|
||||
var value = null;
|
||||
(<Promise<any>>c(new Control("expected"))).then(v => value = v);
|
||||
(<Promise<any>>c(new Control('expected'))).then(v => value = v);
|
||||
|
||||
tick(1);
|
||||
|
||||
expect(value).toEqual(null);
|
||||
}));
|
||||
|
||||
it("should ignore nulls", fakeAsync(() => {
|
||||
var c = Validators.composeAsync([asyncValidator("expected", {"one": true}), null]);
|
||||
it('should ignore nulls', fakeAsync(() => {
|
||||
var c = Validators.composeAsync([asyncValidator('expected', {'one': true}), null]);
|
||||
|
||||
var value = null;
|
||||
(<Promise<any>>c(new Control("invalid"))).then(v => value = v);
|
||||
(<Promise<any>>c(new Control('invalid'))).then(v => value = v);
|
||||
|
||||
tick(1);
|
||||
|
||||
expect(value).toEqual({"one": true});
|
||||
expect(value).toEqual({'one': true});
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,32 +1,15 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
AsyncTestCompleter,
|
||||
inject,
|
||||
browserDetection
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, browserDetection} from 'angular2/testing_internal';
|
||||
import {SpyChangeDetectorRef} from '../spies';
|
||||
|
||||
import {isBlank} from 'angular2/src/facade/lang';
|
||||
import {AsyncPipe} from 'angular2/common';
|
||||
import {WrappedValue} from 'angular2/core';
|
||||
import {
|
||||
EventEmitter,
|
||||
ObservableWrapper,
|
||||
PromiseWrapper,
|
||||
TimerWrapper
|
||||
} from 'angular2/src/facade/async';
|
||||
import {EventEmitter, ObservableWrapper, PromiseWrapper, TimerWrapper} from 'angular2/src/facade/async';
|
||||
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
|
||||
import {PromiseCompleter} from 'angular2/src/facade/promise';
|
||||
|
||||
export function main() {
|
||||
describe("AsyncPipe", () => {
|
||||
describe('AsyncPipe', () => {
|
||||
|
||||
describe('Observable', () => {
|
||||
var emitter;
|
||||
@@ -40,11 +23,11 @@ export function main() {
|
||||
pipe = new AsyncPipe(ref);
|
||||
});
|
||||
|
||||
describe("transform", () => {
|
||||
it("should return null when subscribing to an observable",
|
||||
describe('transform', () => {
|
||||
it('should return null when subscribing to an observable',
|
||||
() => { expect(pipe.transform(emitter)).toBe(null); });
|
||||
|
||||
it("should return the latest available value wrapped",
|
||||
it('should return the latest available value wrapped',
|
||||
inject([AsyncTestCompleter], (async) => {
|
||||
pipe.transform(emitter);
|
||||
|
||||
@@ -57,7 +40,7 @@ export function main() {
|
||||
}));
|
||||
|
||||
|
||||
it("should return same value when nothing has changed since the last call",
|
||||
it('should return same value when nothing has changed since the last call',
|
||||
inject([AsyncTestCompleter], (async) => {
|
||||
pipe.transform(emitter);
|
||||
ObservableWrapper.callEmit(emitter, message);
|
||||
@@ -69,7 +52,7 @@ export function main() {
|
||||
}, 0)
|
||||
}));
|
||||
|
||||
it("should dispose of the existing subscription when subscribing to a new observable",
|
||||
it('should dispose of the existing subscription when subscribing to a new observable',
|
||||
inject([AsyncTestCompleter], (async) => {
|
||||
pipe.transform(emitter);
|
||||
|
||||
@@ -85,7 +68,7 @@ export function main() {
|
||||
}, 0)
|
||||
}));
|
||||
|
||||
it("should request a change detection check upon receiving a new value",
|
||||
it('should request a change detection check upon receiving a new value',
|
||||
inject([AsyncTestCompleter], (async) => {
|
||||
pipe.transform(emitter);
|
||||
ObservableWrapper.callEmit(emitter, message);
|
||||
@@ -97,11 +80,11 @@ export function main() {
|
||||
}));
|
||||
});
|
||||
|
||||
describe("ngOnDestroy", () => {
|
||||
it("should do nothing when no subscription",
|
||||
describe('ngOnDestroy', () => {
|
||||
it('should do nothing when no subscription',
|
||||
() => { expect(() => pipe.ngOnDestroy()).not.toThrow(); });
|
||||
|
||||
it("should dispose of the existing subscription", inject([AsyncTestCompleter], (async) => {
|
||||
it('should dispose of the existing subscription', inject([AsyncTestCompleter], (async) => {
|
||||
pipe.transform(emitter);
|
||||
pipe.ngOnDestroy();
|
||||
|
||||
@@ -115,7 +98,7 @@ export function main() {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Promise", () => {
|
||||
describe('Promise', () => {
|
||||
var message = new Object();
|
||||
var pipe: AsyncPipe;
|
||||
var completer: PromiseCompleter<any>;
|
||||
@@ -129,11 +112,11 @@ export function main() {
|
||||
pipe = new AsyncPipe(<any>ref);
|
||||
});
|
||||
|
||||
describe("transform", () => {
|
||||
it("should return null when subscribing to a promise",
|
||||
describe('transform', () => {
|
||||
it('should return null when subscribing to a promise',
|
||||
() => { expect(pipe.transform(completer.promise)).toBe(null); });
|
||||
|
||||
it("should return the latest available value", inject([AsyncTestCompleter], (async) => {
|
||||
it('should return the latest available value', inject([AsyncTestCompleter], (async) => {
|
||||
pipe.transform(completer.promise);
|
||||
|
||||
completer.resolve(message);
|
||||
@@ -144,7 +127,7 @@ export function main() {
|
||||
}, timer)
|
||||
}));
|
||||
|
||||
it("should return unwrapped value when nothing has changed since the last call",
|
||||
it('should return unwrapped value when nothing has changed since the last call',
|
||||
inject([AsyncTestCompleter], (async) => {
|
||||
pipe.transform(completer.promise);
|
||||
completer.resolve(message);
|
||||
@@ -156,7 +139,7 @@ export function main() {
|
||||
}, timer)
|
||||
}));
|
||||
|
||||
it("should dispose of the existing subscription when subscribing to a new promise",
|
||||
it('should dispose of the existing subscription when subscribing to a new promise',
|
||||
inject([AsyncTestCompleter], (async) => {
|
||||
pipe.transform(completer.promise);
|
||||
|
||||
@@ -172,7 +155,7 @@ export function main() {
|
||||
}, timer)
|
||||
}));
|
||||
|
||||
it("should request a change detection check upon receiving a new value",
|
||||
it('should request a change detection check upon receiving a new value',
|
||||
inject([AsyncTestCompleter], (async) => {
|
||||
var markForCheck = ref.spy('markForCheck');
|
||||
pipe.transform(completer.promise);
|
||||
@@ -184,22 +167,22 @@ export function main() {
|
||||
}, timer)
|
||||
}));
|
||||
|
||||
describe("ngOnDestroy", () => {
|
||||
it("should do nothing when no source",
|
||||
describe('ngOnDestroy', () => {
|
||||
it('should do nothing when no source',
|
||||
() => { expect(() => pipe.ngOnDestroy()).not.toThrow(); });
|
||||
|
||||
it("should dispose of the existing source", inject([AsyncTestCompleter], (async) => {
|
||||
it('should dispose of the existing source', inject([AsyncTestCompleter], (async) => {
|
||||
pipe.transform(completer.promise);
|
||||
expect(pipe.transform(completer.promise)).toBe(null);
|
||||
completer.resolve(message)
|
||||
|
||||
|
||||
TimerWrapper.setTimeout(() => {
|
||||
expect(pipe.transform(completer.promise)).toEqual(new WrappedValue(message));
|
||||
pipe.ngOnDestroy();
|
||||
expect(pipe.transform(completer.promise)).toBe(null);
|
||||
async.done();
|
||||
}, timer);
|
||||
TimerWrapper.setTimeout(() => {
|
||||
expect(pipe.transform(completer.promise)).toEqual(new WrappedValue(message));
|
||||
pipe.ngOnDestroy();
|
||||
expect(pipe.transform(completer.promise)).toBe(null);
|
||||
async.done();
|
||||
}, timer);
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -215,7 +198,7 @@ export function main() {
|
||||
describe('other types', () => {
|
||||
it('should throw when given an invalid object', () => {
|
||||
var pipe = new AsyncPipe(null);
|
||||
expect(() => pipe.transform(<any>"some bogus object", [])).toThrowError();
|
||||
expect(() => pipe.transform(<any>'some bogus object', [])).toThrowError();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,21 +1,11 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
browserDetection
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, browserDetection} from 'angular2/testing_internal';
|
||||
|
||||
import {DatePipe} from 'angular2/common';
|
||||
import {DateWrapper} from 'angular2/src/facade/lang';
|
||||
import {PipeResolver} from 'angular2/src/core/linker/pipe_resolver';
|
||||
|
||||
export function main() {
|
||||
describe("DatePipe", () => {
|
||||
describe('DatePipe', () => {
|
||||
var date;
|
||||
var pipe;
|
||||
|
||||
@@ -27,11 +17,11 @@ export function main() {
|
||||
it('should be marked as pure',
|
||||
() => { expect(new PipeResolver().resolve(DatePipe).pure).toEqual(true); });
|
||||
|
||||
describe("supports", () => {
|
||||
it("should support date", () => { expect(pipe.supports(date)).toBe(true); });
|
||||
it("should support int", () => { expect(pipe.supports(123456789)).toBe(true); });
|
||||
describe('supports', () => {
|
||||
it('should support date', () => { expect(pipe.supports(date)).toBe(true); });
|
||||
it('should support int', () => { expect(pipe.supports(123456789)).toBe(true); });
|
||||
|
||||
it("should not support other objects", () => {
|
||||
it('should not support other objects', () => {
|
||||
expect(pipe.supports(new Object())).toBe(false);
|
||||
expect(pipe.supports(null)).toBe(false);
|
||||
});
|
||||
@@ -40,7 +30,7 @@ export function main() {
|
||||
// TODO(mlaval): enable tests when Intl API is no longer used, see
|
||||
// https://github.com/angular/angular/issues/3333
|
||||
if (browserDetection.supportsIntlApi) {
|
||||
describe("transform", () => {
|
||||
describe('transform', () => {
|
||||
it('should format each component correctly', () => {
|
||||
expect(pipe.transform(date, ['y'])).toEqual('2015');
|
||||
expect(pipe.transform(date, ['yy'])).toEqual('15');
|
||||
|
||||
@@ -1,57 +1,51 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
|
||||
import {I18nPluralPipe} from 'angular2/common';
|
||||
import {PipeResolver} from 'angular2/src/core/linker/pipe_resolver';
|
||||
|
||||
export function main() {
|
||||
describe("I18nPluralPipe", () => {
|
||||
describe('I18nPluralPipe', () => {
|
||||
var pipe;
|
||||
var mapping = {'=0': 'No messages.', '=1': 'One message.', 'other': 'There are some messages.'};
|
||||
var interpolatedMapping =
|
||||
{'=0': 'No messages.', '=1': 'One message.', 'other': 'There are # messages, that is #.'};
|
||||
var interpolatedMapping = {
|
||||
'=0': 'No messages.',
|
||||
'=1': 'One message.',
|
||||
'other': 'There are # messages, that is #.'
|
||||
};
|
||||
|
||||
beforeEach(() => { pipe = new I18nPluralPipe(); });
|
||||
|
||||
it('should be marked as pure',
|
||||
() => { expect(new PipeResolver().resolve(I18nPluralPipe).pure).toEqual(true); });
|
||||
|
||||
describe("transform", () => {
|
||||
it("should return 0 text if value is 0", () => {
|
||||
describe('transform', () => {
|
||||
it('should return 0 text if value is 0', () => {
|
||||
var val = pipe.transform(0, [mapping]);
|
||||
expect(val).toEqual('No messages.');
|
||||
});
|
||||
|
||||
it("should return 1 text if value is 1", () => {
|
||||
it('should return 1 text if value is 1', () => {
|
||||
var val = pipe.transform(1, [mapping]);
|
||||
expect(val).toEqual('One message.');
|
||||
});
|
||||
|
||||
it("should return other text if value is anything other than 0 or 1", () => {
|
||||
it('should return other text if value is anything other than 0 or 1', () => {
|
||||
var val = pipe.transform(6, [mapping]);
|
||||
expect(val).toEqual('There are some messages.');
|
||||
});
|
||||
|
||||
it("should interpolate the value into the text where indicated", () => {
|
||||
it('should interpolate the value into the text where indicated', () => {
|
||||
var val = pipe.transform(6, [interpolatedMapping]);
|
||||
expect(val).toEqual('There are 6 messages, that is 6.');
|
||||
});
|
||||
|
||||
it("should use 'other' if value is undefined", () => {
|
||||
it('should use \'other\' if value is undefined', () => {
|
||||
var messageLength;
|
||||
var val = pipe.transform(messageLength, [interpolatedMapping]);
|
||||
expect(val).toEqual('There are messages, that is .');
|
||||
});
|
||||
|
||||
it("should not support bad arguments",
|
||||
it('should not support bad arguments',
|
||||
() => { expect(() => pipe.transform(0, ['hey'])).toThrowError(); });
|
||||
});
|
||||
|
||||
|
||||
@@ -1,19 +1,10 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
|
||||
import {I18nSelectPipe} from 'angular2/common';
|
||||
import {PipeResolver} from 'angular2/src/core/linker/pipe_resolver';
|
||||
|
||||
export function main() {
|
||||
describe("I18nSelectPipe", () => {
|
||||
describe('I18nSelectPipe', () => {
|
||||
var pipe;
|
||||
var mapping = {'male': 'Invite him.', 'female': 'Invite her.', 'other': 'Invite them.'};
|
||||
|
||||
@@ -22,29 +13,29 @@ export function main() {
|
||||
it('should be marked as pure',
|
||||
() => { expect(new PipeResolver().resolve(I18nSelectPipe).pure).toEqual(true); });
|
||||
|
||||
describe("transform", () => {
|
||||
it("should return male text if value is male", () => {
|
||||
describe('transform', () => {
|
||||
it('should return male text if value is male', () => {
|
||||
var val = pipe.transform('male', [mapping]);
|
||||
expect(val).toEqual('Invite him.');
|
||||
});
|
||||
|
||||
it("should return female text if value is female", () => {
|
||||
it('should return female text if value is female', () => {
|
||||
var val = pipe.transform('female', [mapping]);
|
||||
expect(val).toEqual('Invite her.');
|
||||
});
|
||||
|
||||
it("should return other text if value is anything other than male or female", () => {
|
||||
it('should return other text if value is anything other than male or female', () => {
|
||||
var val = pipe.transform('Anything else', [mapping]);
|
||||
expect(val).toEqual('Invite them.');
|
||||
});
|
||||
|
||||
it("should use 'other' if value is undefined", () => {
|
||||
it('should use \'other\' if value is undefined', () => {
|
||||
var gender;
|
||||
var val = pipe.transform(gender, [mapping]);
|
||||
expect(val).toEqual('Invite them.');
|
||||
});
|
||||
|
||||
it("should not support bad arguments",
|
||||
it('should not support bad arguments',
|
||||
() => { expect(() => pipe.transform('male', ['hey'])).toThrowError(); });
|
||||
});
|
||||
|
||||
|
||||
@@ -1,24 +1,11 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
AsyncTestCompleter,
|
||||
inject,
|
||||
proxy,
|
||||
TestComponentBuilder
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, proxy, TestComponentBuilder} from 'angular2/testing_internal';
|
||||
import {Json, RegExp, NumberWrapper, StringWrapper} from 'angular2/src/facade/lang';
|
||||
|
||||
import {Component} from 'angular2/core';
|
||||
import {JsonPipe} from 'angular2/common';
|
||||
|
||||
export function main() {
|
||||
describe("JsonPipe", () => {
|
||||
describe('JsonPipe', () => {
|
||||
var regNewLine = '\n';
|
||||
var inceptionObj;
|
||||
var inceptionObjString;
|
||||
@@ -28,24 +15,29 @@ export function main() {
|
||||
|
||||
beforeEach(() => {
|
||||
inceptionObj = {dream: {dream: {dream: 'Limbo'}}};
|
||||
inceptionObjString = "{\n" + " \"dream\": {\n" + " \"dream\": {\n" +
|
||||
" \"dream\": \"Limbo\"\n" + " }\n" + " }\n" + "}";
|
||||
inceptionObjString = '{\n' +
|
||||
' "dream": {\n' +
|
||||
' "dream": {\n' +
|
||||
' "dream": "Limbo"\n' +
|
||||
' }\n' +
|
||||
' }\n' +
|
||||
'}';
|
||||
|
||||
|
||||
pipe = new JsonPipe();
|
||||
});
|
||||
|
||||
describe("transform", () => {
|
||||
it("should return JSON-formatted string",
|
||||
describe('transform', () => {
|
||||
it('should return JSON-formatted string',
|
||||
() => { expect(pipe.transform(inceptionObj)).toEqual(inceptionObjString); });
|
||||
|
||||
it("should return JSON-formatted string even when normalized", () => {
|
||||
it('should return JSON-formatted string even when normalized', () => {
|
||||
var dream1 = normalize(pipe.transform(inceptionObj));
|
||||
var dream2 = normalize(inceptionObjString);
|
||||
expect(dream1).toEqual(dream2);
|
||||
});
|
||||
|
||||
it("should return JSON-formatted string similar to Json.stringify", () => {
|
||||
it('should return JSON-formatted string similar to Json.stringify', () => {
|
||||
var dream1 = normalize(pipe.transform(inceptionObj));
|
||||
var dream2 = normalize(Json.stringify(inceptionObj));
|
||||
expect(dream1).toEqual(dream2);
|
||||
@@ -59,11 +51,11 @@ export function main() {
|
||||
let mutable: number[] = [1];
|
||||
fixture.debugElement.componentInstance.data = mutable;
|
||||
fixture.detectChanges();
|
||||
expect(fixture.debugElement.nativeElement).toHaveText("[\n 1\n]");
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('[\n 1\n]');
|
||||
|
||||
mutable.push(2);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.debugElement.nativeElement).toHaveText("[\n 1,\n 2\n]");
|
||||
expect(fixture.debugElement.nativeElement).toHaveText('[\n 1,\n 2\n]');
|
||||
|
||||
async.done();
|
||||
});
|
||||
|
||||
@@ -1,18 +1,9 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
|
||||
import {LowerCasePipe} from 'angular2/common';
|
||||
|
||||
export function main() {
|
||||
describe("LowerCasePipe", () => {
|
||||
describe('LowerCasePipe', () => {
|
||||
var upper;
|
||||
var lower;
|
||||
var pipe;
|
||||
@@ -23,20 +14,20 @@ export function main() {
|
||||
pipe = new LowerCasePipe();
|
||||
});
|
||||
|
||||
describe("transform", () => {
|
||||
it("should return lowercase", () => {
|
||||
describe('transform', () => {
|
||||
it('should return lowercase', () => {
|
||||
var val = pipe.transform(upper);
|
||||
expect(val).toEqual(lower);
|
||||
});
|
||||
|
||||
it("should lowercase when there is a new value", () => {
|
||||
it('should lowercase when there is a new value', () => {
|
||||
var val = pipe.transform(upper);
|
||||
expect(val).toEqual(lower);
|
||||
var val2 = pipe.transform('WAT');
|
||||
expect(val2).toEqual('wat');
|
||||
});
|
||||
|
||||
it("should not support other objects",
|
||||
it('should not support other objects',
|
||||
() => { expect(() => pipe.transform(new Object())).toThrowError(); });
|
||||
});
|
||||
|
||||
|
||||
@@ -1,14 +1,4 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
browserDetection
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, browserDetection} from 'angular2/testing_internal';
|
||||
|
||||
import {DecimalPipe, PercentPipe, CurrencyPipe} from 'angular2/common';
|
||||
|
||||
@@ -17,12 +7,12 @@ export function main() {
|
||||
// TODO(mlaval): enable tests when Intl API is no longer used, see
|
||||
// https://github.com/angular/angular/issues/3333
|
||||
if (browserDetection.supportsIntlApi) {
|
||||
describe("DecimalPipe", () => {
|
||||
describe('DecimalPipe', () => {
|
||||
var pipe;
|
||||
|
||||
beforeEach(() => { pipe = new DecimalPipe(); });
|
||||
|
||||
describe("transform", () => {
|
||||
describe('transform', () => {
|
||||
it('should return correct value for numbers', () => {
|
||||
expect(pipe.transform(12345, [])).toEqual('12,345');
|
||||
expect(pipe.transform(123, ['.2'])).toEqual('123.00');
|
||||
@@ -33,39 +23,39 @@ export function main() {
|
||||
expect(pipe.transform(1.1234, [])).toEqual('1.123');
|
||||
});
|
||||
|
||||
it("should not support other objects",
|
||||
it('should not support other objects',
|
||||
() => { expect(() => pipe.transform(new Object(), [])).toThrowError(); });
|
||||
});
|
||||
});
|
||||
|
||||
describe("PercentPipe", () => {
|
||||
describe('PercentPipe', () => {
|
||||
var pipe;
|
||||
|
||||
beforeEach(() => { pipe = new PercentPipe(); });
|
||||
|
||||
describe("transform", () => {
|
||||
describe('transform', () => {
|
||||
it('should return correct value for numbers', () => {
|
||||
expect(pipe.transform(1.23, [])).toEqual('123%');
|
||||
expect(pipe.transform(1.2, ['.2'])).toEqual('120.00%');
|
||||
});
|
||||
|
||||
it("should not support other objects",
|
||||
it('should not support other objects',
|
||||
() => { expect(() => pipe.transform(new Object(), [])).toThrowError(); });
|
||||
});
|
||||
});
|
||||
|
||||
describe("CurrencyPipe", () => {
|
||||
describe('CurrencyPipe', () => {
|
||||
var pipe;
|
||||
|
||||
beforeEach(() => { pipe = new CurrencyPipe(); });
|
||||
|
||||
describe("transform", () => {
|
||||
describe('transform', () => {
|
||||
it('should return correct value for numbers', () => {
|
||||
expect(pipe.transform(123, [])).toEqual('USD123');
|
||||
expect(pipe.transform(12, ['EUR', false, '.2'])).toEqual('EUR12.00');
|
||||
});
|
||||
|
||||
it("should not support other objects",
|
||||
it('should not support other objects',
|
||||
() => { expect(() => pipe.transform(new Object(), [])).toThrowError(); });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,14 +1,4 @@
|
||||
import {
|
||||
ddescribe,
|
||||
xdescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, xdescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
|
||||
import {PipeProvider} from 'angular2/src/core/pipes/pipe_provider';
|
||||
import {Pipe} from 'angular2/src/core/metadata';
|
||||
@@ -16,7 +6,7 @@ import {Pipe} from 'angular2/src/core/metadata';
|
||||
class MyPipe {}
|
||||
|
||||
export function main() {
|
||||
describe("PipeProvider", () => {
|
||||
describe('PipeProvider', () => {
|
||||
it('should create a provider out of a type', () => {
|
||||
var provider = PipeProvider.createFromType(MyPipe, new Pipe({name: 'my-pipe'}));
|
||||
expect(provider.name).toEqual('my-pipe');
|
||||
|
||||
@@ -1,14 +1,4 @@
|
||||
import {
|
||||
ddescribe,
|
||||
xdescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, xdescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
|
||||
import {Injector, Inject, provide, Pipe, PipeTransform, OnDestroy} from 'angular2/core';
|
||||
import {ProtoPipes, Pipes} from 'angular2/src/core/pipes/pipes';
|
||||
@@ -21,13 +11,13 @@ class PipeA implements PipeTransform, OnDestroy {
|
||||
|
||||
class PipeB implements PipeTransform, OnDestroy {
|
||||
dep;
|
||||
constructor(@Inject("dep") dep: any) { this.dep = dep; }
|
||||
constructor(@Inject('dep') dep: any) { this.dep = dep; }
|
||||
transform(a, b) {}
|
||||
ngOnDestroy() {}
|
||||
}
|
||||
|
||||
export function main() {
|
||||
describe("Pipes", () => {
|
||||
describe('Pipes', () => {
|
||||
var injector;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -39,20 +29,20 @@ export function main() {
|
||||
ProtoPipes.fromProviders([PipeProvider.createFromType(PipeA, new Pipe({name: 'a'}))]);
|
||||
var pipes = new Pipes(proto, injector);
|
||||
|
||||
expect(pipes.get("a").pipe).toBeAnInstanceOf(PipeA);
|
||||
expect(pipes.get('a').pipe).toBeAnInstanceOf(PipeA);
|
||||
});
|
||||
|
||||
it('should throw when no pipe found', () => {
|
||||
var proto = ProtoPipes.fromProviders([]);
|
||||
var pipes = new Pipes(proto, injector);
|
||||
expect(() => pipes.get("invalid")).toThrowErrorWith("Cannot find pipe 'invalid'");
|
||||
expect(() => pipes.get('invalid')).toThrowErrorWith('Cannot find pipe \'invalid\'');
|
||||
});
|
||||
|
||||
it('should inject dependencies from the provided injector', () => {
|
||||
var proto =
|
||||
ProtoPipes.fromProviders([PipeProvider.createFromType(PipeB, new Pipe({name: 'b'}))]);
|
||||
var pipes = new Pipes(proto, injector);
|
||||
expect((<any>pipes.get("b").pipe).dep).toEqual("dependency");
|
||||
expect((<any>pipes.get('b').pipe).dep).toEqual('dependency');
|
||||
});
|
||||
|
||||
it('should cache pure pipes', () => {
|
||||
@@ -60,8 +50,8 @@ export function main() {
|
||||
[PipeProvider.createFromType(PipeA, new Pipe({name: 'a', pure: true}))]);
|
||||
var pipes = new Pipes(proto, injector);
|
||||
|
||||
expect(pipes.get("a").pure).toEqual(true);
|
||||
expect(pipes.get("a")).toBe(pipes.get("a"));
|
||||
expect(pipes.get('a').pure).toEqual(true);
|
||||
expect(pipes.get('a')).toBe(pipes.get('a'));
|
||||
});
|
||||
|
||||
it('should NOT cache impure pipes', () => {
|
||||
@@ -69,8 +59,8 @@ export function main() {
|
||||
[PipeProvider.createFromType(PipeA, new Pipe({name: 'a', pure: false}))]);
|
||||
var pipes = new Pipes(proto, injector);
|
||||
|
||||
expect(pipes.get("a").pure).toEqual(false);
|
||||
expect(pipes.get("a")).not.toBe(pipes.get("a"));
|
||||
expect(pipes.get('a').pure).toEqual(false);
|
||||
expect(pipes.get('a')).not.toBe(pipes.get('a'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,23 +1,10 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
browserDetection,
|
||||
inject,
|
||||
TestComponentBuilder,
|
||||
AsyncTestCompleter
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, browserDetection, inject, TestComponentBuilder, AsyncTestCompleter} from 'angular2/testing_internal';
|
||||
|
||||
import {ReplacePipe} from 'angular2/common';
|
||||
import {RegExpWrapper, StringJoiner} from 'angular2/src/facade/lang';
|
||||
|
||||
export function main() {
|
||||
describe("ReplacePipe", () => {
|
||||
describe('ReplacePipe', () => {
|
||||
var someNumber: number;
|
||||
var str;
|
||||
var pipe;
|
||||
@@ -28,43 +15,43 @@ export function main() {
|
||||
pipe = new ReplacePipe();
|
||||
});
|
||||
|
||||
describe("transform", () => {
|
||||
describe('transform', () => {
|
||||
|
||||
it("should not support input other than strings and numbers", () => {
|
||||
expect(() => pipe.transform({}, ["Douglas", "Hugh"])).toThrow();
|
||||
expect(() => pipe.transform([1, 2, 3], ["Douglas", "Hugh"])).toThrow();
|
||||
it('should not support input other than strings and numbers', () => {
|
||||
expect(() => pipe.transform({}, ['Douglas', 'Hugh'])).toThrow();
|
||||
expect(() => pipe.transform([1, 2, 3], ['Douglas', 'Hugh'])).toThrow();
|
||||
});
|
||||
|
||||
it("should not support patterns other than strings and regular expressions", () => {
|
||||
expect(() => pipe.transform(str, [{}, "Hugh"])).toThrow();
|
||||
expect(() => pipe.transform(str, [null, "Hugh"])).toThrow();
|
||||
expect(() => pipe.transform(str, [123, "Hugh"])).toThrow();
|
||||
it('should not support patterns other than strings and regular expressions', () => {
|
||||
expect(() => pipe.transform(str, [{}, 'Hugh'])).toThrow();
|
||||
expect(() => pipe.transform(str, [null, 'Hugh'])).toThrow();
|
||||
expect(() => pipe.transform(str, [123, 'Hugh'])).toThrow();
|
||||
});
|
||||
|
||||
it("should not support replacements other than strings and functions", () => {
|
||||
expect(() => pipe.transform(str, ["Douglas", {}])).toThrow();
|
||||
expect(() => pipe.transform(str, ["Douglas", null])).toThrow();
|
||||
expect(() => pipe.transform(str, ["Douglas", 123])).toThrow();
|
||||
it('should not support replacements other than strings and functions', () => {
|
||||
expect(() => pipe.transform(str, ['Douglas', {}])).toThrow();
|
||||
expect(() => pipe.transform(str, ['Douglas', null])).toThrow();
|
||||
expect(() => pipe.transform(str, ['Douglas', 123])).toThrow();
|
||||
});
|
||||
|
||||
it("should return a new string with the pattern replaced", () => {
|
||||
var result1 = pipe.transform(str, ["Douglas", "Hugh"]);
|
||||
it('should return a new string with the pattern replaced', () => {
|
||||
var result1 = pipe.transform(str, ['Douglas', 'Hugh']);
|
||||
|
||||
var result2 = pipe.transform(str, [RegExpWrapper.create("a"), "_"]);
|
||||
var result2 = pipe.transform(str, [RegExpWrapper.create('a'), '_']);
|
||||
|
||||
var result3 = pipe.transform(str, [RegExpWrapper.create("a", "i"), "_"]);
|
||||
var result3 = pipe.transform(str, [RegExpWrapper.create('a', 'i'), '_']);
|
||||
|
||||
var f = (x => { return "Adams!"; });
|
||||
var f = (x => { return 'Adams!'; });
|
||||
|
||||
var result4 = pipe.transform(str, ["Adams", f]);
|
||||
var result4 = pipe.transform(str, ['Adams', f]);
|
||||
|
||||
var result5 = pipe.transform(someNumber, ["2", "4"]);
|
||||
var result5 = pipe.transform(someNumber, ['2', '4']);
|
||||
|
||||
expect(result1).toEqual("Hugh Adams");
|
||||
expect(result2).toEqual("Dougl_s Ad_ms");
|
||||
expect(result3).toEqual("Dougl_s _d_ms");
|
||||
expect(result4).toEqual("Douglas Adams!");
|
||||
expect(result5).toEqual("44");
|
||||
expect(result1).toEqual('Hugh Adams');
|
||||
expect(result2).toEqual('Dougl_s Ad_ms');
|
||||
expect(result3).toEqual('Dougl_s _d_ms');
|
||||
expect(result4).toEqual('Douglas Adams!');
|
||||
expect(result5).toEqual('44');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -1,23 +1,10 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
browserDetection,
|
||||
inject,
|
||||
TestComponentBuilder,
|
||||
AsyncTestCompleter
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, browserDetection, inject, TestComponentBuilder, AsyncTestCompleter} from 'angular2/testing_internal';
|
||||
|
||||
import {Component} from 'angular2/core';
|
||||
import {SlicePipe} from 'angular2/common';
|
||||
|
||||
export function main() {
|
||||
describe("SlicePipe", () => {
|
||||
describe('SlicePipe', () => {
|
||||
var list: number[];
|
||||
var str;
|
||||
var pipe;
|
||||
@@ -28,17 +15,17 @@ export function main() {
|
||||
pipe = new SlicePipe();
|
||||
});
|
||||
|
||||
describe("supports", () => {
|
||||
it("should support strings", () => { expect(pipe.supports(str)).toBe(true); });
|
||||
it("should support lists", () => { expect(pipe.supports(list)).toBe(true); });
|
||||
describe('supports', () => {
|
||||
it('should support strings', () => { expect(pipe.supports(str)).toBe(true); });
|
||||
it('should support lists', () => { expect(pipe.supports(list)).toBe(true); });
|
||||
|
||||
it("should not support other objects", () => {
|
||||
it('should not support other objects', () => {
|
||||
expect(pipe.supports(new Object())).toBe(false);
|
||||
expect(pipe.supports(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("transform", () => {
|
||||
describe('transform', () => {
|
||||
|
||||
it('should return all items after START index when START is positive and END is omitted',
|
||||
() => {
|
||||
|
||||
@@ -1,18 +1,9 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
|
||||
import {UpperCasePipe} from 'angular2/common';
|
||||
|
||||
export function main() {
|
||||
describe("UpperCasePipe", () => {
|
||||
describe('UpperCasePipe', () => {
|
||||
var upper;
|
||||
var lower;
|
||||
var pipe;
|
||||
@@ -23,21 +14,21 @@ export function main() {
|
||||
pipe = new UpperCasePipe();
|
||||
});
|
||||
|
||||
describe("transform", () => {
|
||||
describe('transform', () => {
|
||||
|
||||
it("should return uppercase", () => {
|
||||
it('should return uppercase', () => {
|
||||
var val = pipe.transform(lower);
|
||||
expect(val).toEqual(upper);
|
||||
});
|
||||
|
||||
it("should uppercase when there is a new value", () => {
|
||||
it('should uppercase when there is a new value', () => {
|
||||
var val = pipe.transform(lower);
|
||||
expect(val).toEqual(upper);
|
||||
var val2 = pipe.transform('wat');
|
||||
expect(val2).toEqual('WAT');
|
||||
});
|
||||
|
||||
it("should not support other objects",
|
||||
it('should not support other objects',
|
||||
() => { expect(() => pipe.transform(new Object())).toThrowError(); });
|
||||
});
|
||||
|
||||
|
||||
@@ -1,36 +1,8 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
TestComponentBuilder,
|
||||
beforeEachProviders
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit, TestComponentBuilder, beforeEachProviders} from 'angular2/testing_internal';
|
||||
import {MapWrapper} from 'angular2/src/facade/collection';
|
||||
import {
|
||||
CompileDirectiveMetadata,
|
||||
CompileTypeMetadata
|
||||
} from 'angular2/src/compiler/directive_metadata';
|
||||
import {CompileDirectiveMetadata, CompileTypeMetadata} from 'angular2/src/compiler/directive_metadata';
|
||||
import {TemplateParser} from 'angular2/src/compiler/template_parser';
|
||||
import {
|
||||
Parser,
|
||||
Lexer,
|
||||
ChangeDetectorDefinition,
|
||||
ChangeDetectorGenConfig,
|
||||
DynamicProtoChangeDetector,
|
||||
ChangeDetectionStrategy,
|
||||
ChangeDispatcher,
|
||||
DirectiveIndex,
|
||||
Locals,
|
||||
BindingTarget,
|
||||
ChangeDetector
|
||||
} from 'angular2/src/core/change_detection/change_detection';
|
||||
import {Parser, Lexer, ChangeDetectorDefinition, ChangeDetectorGenConfig, DynamicProtoChangeDetector, ChangeDetectionStrategy, ChangeDispatcher, DirectiveIndex, Locals, BindingTarget, ChangeDetector} from 'angular2/src/core/change_detection/change_detection';
|
||||
import {Pipes} from 'angular2/src/core/change_detection/pipes';
|
||||
import {createChangeDetectorDefinitions} from 'angular2/src/compiler/change_definition_factory';
|
||||
import {TestDirective, TestDispatcher, TestPipes} from './change_detector_mocks';
|
||||
@@ -57,13 +29,14 @@ export function main() {
|
||||
pipes = new TestPipes();
|
||||
}));
|
||||
|
||||
function createChangeDetector(template: string, directives: CompileDirectiveMetadata[],
|
||||
protoViewIndex: number = 0): ChangeDetector {
|
||||
function createChangeDetector(
|
||||
template: string, directives: CompileDirectiveMetadata[],
|
||||
protoViewIndex: number = 0): ChangeDetector {
|
||||
var protoChangeDetectors =
|
||||
createChangeDetectorDefinitions(new CompileTypeMetadata({name: 'SomeComp'}),
|
||||
ChangeDetectionStrategy.Default,
|
||||
new ChangeDetectorGenConfig(true, false, false),
|
||||
parser.parse(template, directives, [], 'TestComp'))
|
||||
createChangeDetectorDefinitions(
|
||||
new CompileTypeMetadata({name: 'SomeComp'}), ChangeDetectionStrategy.Default,
|
||||
new ChangeDetectorGenConfig(true, false, false),
|
||||
parser.parse(template, directives, [], 'TestComp'))
|
||||
.map(definition => new DynamicProtoChangeDetector(definition));
|
||||
var changeDetector = protoChangeDetectors[protoViewIndex].instantiate();
|
||||
changeDetector.hydrate(context, locals, dispatcher, pipes);
|
||||
|
||||
@@ -1,17 +1,4 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
xdescribe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
AsyncTestCompleter,
|
||||
inject,
|
||||
beforeEachProviders
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal';
|
||||
import {provide} from 'angular2/src/core/di';
|
||||
|
||||
import {CONST_EXPR, stringify, IS_DART} from 'angular2/src/facade/lang';
|
||||
@@ -19,28 +6,12 @@ import {MapWrapper} from 'angular2/src/facade/collection';
|
||||
|
||||
import {ChangeDetectionCompiler} from 'angular2/src/compiler/change_detector_compiler';
|
||||
|
||||
import {
|
||||
CompileDirectiveMetadata,
|
||||
CompileTypeMetadata
|
||||
} from 'angular2/src/compiler/directive_metadata';
|
||||
import {
|
||||
SourceModule,
|
||||
SourceExpression,
|
||||
SourceExpressions,
|
||||
moduleRef
|
||||
} from 'angular2/src/compiler/source_module';
|
||||
import {CompileDirectiveMetadata, CompileTypeMetadata} from 'angular2/src/compiler/directive_metadata';
|
||||
import {SourceModule, SourceExpression, SourceExpressions, moduleRef} from 'angular2/src/compiler/source_module';
|
||||
|
||||
import {TemplateParser} from 'angular2/src/compiler/template_parser';
|
||||
|
||||
import {
|
||||
ChangeDetectorGenConfig,
|
||||
ChangeDetectionStrategy,
|
||||
ChangeDispatcher,
|
||||
DirectiveIndex,
|
||||
Locals,
|
||||
BindingTarget,
|
||||
ChangeDetector
|
||||
} from 'angular2/src/core/change_detection/change_detection';
|
||||
import {ChangeDetectorGenConfig, ChangeDetectionStrategy, ChangeDispatcher, DirectiveIndex, Locals, BindingTarget, ChangeDetector} from 'angular2/src/core/change_detection/change_detection';
|
||||
|
||||
import {evalModule} from './eval_module';
|
||||
|
||||
@@ -60,18 +31,15 @@ export function main() {
|
||||
return;
|
||||
}
|
||||
describe('ChangeDetectorCompiler', () => {
|
||||
beforeEachProviders(() => [
|
||||
TEST_PROVIDERS,
|
||||
provide(ChangeDetectorGenConfig,
|
||||
{useValue: new ChangeDetectorGenConfig(true, false, false)})
|
||||
]);
|
||||
beforeEachProviders(() => [TEST_PROVIDERS, provide(ChangeDetectorGenConfig, {
|
||||
useValue: new ChangeDetectorGenConfig(true, false, false)
|
||||
})]);
|
||||
|
||||
var parser: TemplateParser;
|
||||
var compiler: ChangeDetectionCompiler;
|
||||
beforeEachProviders(() => [
|
||||
provide(ChangeDetectorGenConfig,
|
||||
{useValue: new ChangeDetectorGenConfig(true, false, false)})
|
||||
]);
|
||||
beforeEachProviders(
|
||||
() => [provide(
|
||||
ChangeDetectorGenConfig, {useValue: new ChangeDetectorGenConfig(true, false, false)})]);
|
||||
|
||||
beforeEach(inject([TemplateParser, ChangeDetectionCompiler], (_parser, _compiler) => {
|
||||
parser = _parser;
|
||||
@@ -79,8 +47,9 @@ export function main() {
|
||||
}));
|
||||
|
||||
describe('compileComponentRuntime', () => {
|
||||
function detectChanges(compiler: ChangeDetectionCompiler, template: string,
|
||||
directives: CompileDirectiveMetadata[] = CONST_EXPR([])): string[] {
|
||||
function detectChanges(
|
||||
compiler: ChangeDetectionCompiler, template: string,
|
||||
directives: CompileDirectiveMetadata[] = CONST_EXPR([])): string[] {
|
||||
var type =
|
||||
new CompileTypeMetadata({name: stringify(SomeComponent), moduleUrl: THIS_MODULE_URL});
|
||||
var parsedTemplate = parser.parse(template, directives, [], 'TestComp');
|
||||
@@ -90,8 +59,9 @@ export function main() {
|
||||
}
|
||||
|
||||
it('should watch element properties', () => {
|
||||
expect(detectChanges(compiler, '<div [elProp]="someProp">'))
|
||||
.toEqual(['elementProperty(elProp)=someValue']);
|
||||
expect(detectChanges(compiler, '<div [elProp]="someProp">')).toEqual([
|
||||
'elementProperty(elProp)=someValue'
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -109,11 +79,10 @@ export function main() {
|
||||
}
|
||||
|
||||
it('should watch element properties', inject([AsyncTestCompleter], (async) => {
|
||||
detectChanges(compiler, '<div [elProp]="someProp">')
|
||||
.then((value) => {
|
||||
expect(value).toEqual(['elementProperty(elProp)=someValue']);
|
||||
async.done();
|
||||
});
|
||||
detectChanges(compiler, '<div [elProp]="someProp">').then((value) => {
|
||||
expect(value).toEqual(['elementProperty(elProp)=someValue']);
|
||||
async.done();
|
||||
});
|
||||
|
||||
}));
|
||||
});
|
||||
@@ -121,8 +90,8 @@ export function main() {
|
||||
});
|
||||
}
|
||||
|
||||
function createTestableModule(source: SourceExpressions,
|
||||
changeDetectorIndex: number): SourceModule {
|
||||
function createTestableModule(
|
||||
source: SourceExpressions, changeDetectorIndex: number): SourceModule {
|
||||
var resultExpression =
|
||||
`${THIS_MODULE_REF}testChangeDetector(([${source.expressions.join(',')}])[${changeDetectorIndex}])`;
|
||||
var testableSource = `${source.declarations.join('\n')}
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
import {isBlank} from 'angular2/src/facade/lang';
|
||||
import {Pipes} from 'angular2/src/core/change_detection/pipes';
|
||||
import {EventEmitter} from 'angular2/src/facade/async';
|
||||
import {
|
||||
ChangeDetector,
|
||||
ChangeDispatcher,
|
||||
DirectiveIndex,
|
||||
BindingTarget
|
||||
} from 'angular2/src/core/change_detection/change_detection';
|
||||
import {ChangeDetector, ChangeDispatcher, DirectiveIndex, BindingTarget} from 'angular2/src/core/change_detection/change_detection';
|
||||
|
||||
export class TestDirective {
|
||||
eventLog: string[] = [];
|
||||
|
||||
@@ -1,27 +1,12 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
|
||||
import {isPresent} from "angular2/src/facade/lang";
|
||||
import {isPresent} from 'angular2/src/facade/lang';
|
||||
|
||||
import {
|
||||
CssToken,
|
||||
CssScannerError,
|
||||
CssLexer,
|
||||
CssLexerMode,
|
||||
CssTokenType
|
||||
} from 'angular2/src/compiler/css/lexer';
|
||||
import {CssToken, CssScannerError, CssLexer, CssLexerMode, CssTokenType} from 'angular2/src/compiler/css/lexer';
|
||||
|
||||
export function main() {
|
||||
function tokenize(code, trackComments: boolean = false,
|
||||
mode: CssLexerMode = CssLexerMode.ALL): CssToken[] {
|
||||
function tokenize(
|
||||
code, trackComments: boolean = false, mode: CssLexerMode = CssLexerMode.ALL): CssToken[] {
|
||||
var scanner = new CssLexer().scan(code, trackComments);
|
||||
scanner.setMode(mode);
|
||||
|
||||
@@ -41,7 +26,7 @@ export function main() {
|
||||
|
||||
describe('CssLexer', () => {
|
||||
it('should lex newline characters as whitespace when whitespace mode is on', () => {
|
||||
var newlines = ["\n", "\r\n", "\r", "\f"];
|
||||
var newlines = ['\n', '\r\n', '\r', '\f'];
|
||||
newlines.forEach((line) => {
|
||||
var token = tokenize(line, false, CssLexerMode.ALL_TRACK_WS)[0];
|
||||
expect(token.type).toEqual(CssTokenType.Whitespace);
|
||||
@@ -49,7 +34,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should combined newline characters as one newline token when whitespace mode is on', () => {
|
||||
var newlines = ["\n", "\r\n", "\r", "\f"].join("");
|
||||
var newlines = ['\n', '\r\n', '\r', '\f'].join('');
|
||||
var tokens = tokenize(newlines, false, CssLexerMode.ALL_TRACK_WS);
|
||||
expect(tokens.length).toEqual(1);
|
||||
expect(tokens[0].type).toEqual(CssTokenType.Whitespace);
|
||||
@@ -57,13 +42,14 @@ export function main() {
|
||||
|
||||
it('should not consider whitespace or newline values at all when whitespace mode is off',
|
||||
() => {
|
||||
var newlines = ["\n", "\r\n", "\r", "\f"].join("");
|
||||
var newlines = ['\n', '\r\n', '\r', '\f'].join('');
|
||||
var tokens = tokenize(newlines);
|
||||
expect(tokens.length).toEqual(0);
|
||||
});
|
||||
|
||||
it('should lex simple selectors and their inner properties', () => {
|
||||
var cssCode = "\n" + " .selector { my-prop: my-value; }\n";
|
||||
var cssCode = '\n' +
|
||||
' .selector { my-prop: my-value; }\n';
|
||||
var tokens = tokenize(cssCode);
|
||||
|
||||
expect(tokens[0].type).toEqual(CssTokenType.Character);
|
||||
@@ -92,7 +78,9 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should capture the column and line values for each token', () => {
|
||||
var cssCode = "#id {\n" + " prop:value;\n" + "}";
|
||||
var cssCode = '#id {\n' +
|
||||
' prop:value;\n' +
|
||||
'}';
|
||||
|
||||
var tokens = tokenize(cssCode);
|
||||
|
||||
@@ -138,13 +126,13 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should lex quoted strings and escape accordingly', () => {
|
||||
var cssCode = "prop: 'some { value } \\' that is quoted'";
|
||||
var cssCode = 'prop: \'some { value } \\\' that is quoted\'';
|
||||
var tokens = tokenize(cssCode);
|
||||
|
||||
expect(tokens[0].type).toEqual(CssTokenType.Identifier);
|
||||
expect(tokens[1].type).toEqual(CssTokenType.Character);
|
||||
expect(tokens[2].type).toEqual(CssTokenType.String);
|
||||
expect(tokens[2].strValue).toEqual("'some { value } \\' that is quoted'");
|
||||
expect(tokens[2].strValue).toEqual('\'some { value } \\\' that is quoted\'');
|
||||
});
|
||||
|
||||
it('should treat attribute operators as regular characters', () => {
|
||||
@@ -152,27 +140,27 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should lex numbers properly and set them as numbers', () => {
|
||||
var cssCode = "0 1 -2 3.0 -4.001";
|
||||
var cssCode = '0 1 -2 3.0 -4.001';
|
||||
var tokens = tokenize(cssCode);
|
||||
|
||||
expect(tokens[0].type).toEqual(CssTokenType.Number);
|
||||
expect(tokens[0].strValue).toEqual("0");
|
||||
expect(tokens[0].strValue).toEqual('0');
|
||||
|
||||
expect(tokens[1].type).toEqual(CssTokenType.Number);
|
||||
expect(tokens[1].strValue).toEqual("1");
|
||||
expect(tokens[1].strValue).toEqual('1');
|
||||
|
||||
expect(tokens[2].type).toEqual(CssTokenType.Number);
|
||||
expect(tokens[2].strValue).toEqual("-2");
|
||||
expect(tokens[2].strValue).toEqual('-2');
|
||||
|
||||
expect(tokens[3].type).toEqual(CssTokenType.Number);
|
||||
expect(tokens[3].strValue).toEqual("3.0");
|
||||
expect(tokens[3].strValue).toEqual('3.0');
|
||||
|
||||
expect(tokens[4].type).toEqual(CssTokenType.Number);
|
||||
expect(tokens[4].strValue).toEqual("-4.001");
|
||||
expect(tokens[4].strValue).toEqual('-4.001');
|
||||
});
|
||||
|
||||
it('should lex @keywords', () => {
|
||||
var cssCode = "@import()@something";
|
||||
var cssCode = '@import()@something';
|
||||
var tokens = tokenize(cssCode);
|
||||
|
||||
expect(tokens[0].type).toEqual(CssTokenType.AtKeyword);
|
||||
@@ -189,7 +177,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should still lex a number even if it has a dimension suffix', () => {
|
||||
var cssCode = "40% is 40 percent";
|
||||
var cssCode = '40% is 40 percent';
|
||||
var tokens = tokenize(cssCode);
|
||||
|
||||
expect(tokens[0].type).toEqual(CssTokenType.Number);
|
||||
@@ -206,7 +194,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should allow escaped character and unicode character-strings in CSS selectors', () => {
|
||||
var cssCode = "\\123456 .some\\thing \{\}";
|
||||
var cssCode = '\\123456 .some\\thing \{\}';
|
||||
var tokens = tokenize(cssCode);
|
||||
|
||||
expect(tokens[0].type).toEqual(CssTokenType.Identifier);
|
||||
@@ -218,67 +206,67 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should distinguish identifiers and numbers from special characters', () => {
|
||||
var cssCode = "one*two=-4+three-4-equals_value$";
|
||||
var cssCode = 'one*two=-4+three-4-equals_value$';
|
||||
var tokens = tokenize(cssCode);
|
||||
|
||||
expect(tokens[0].type).toEqual(CssTokenType.Identifier);
|
||||
expect(tokens[0].strValue).toEqual("one");
|
||||
expect(tokens[0].strValue).toEqual('one');
|
||||
|
||||
expect(tokens[1].type).toEqual(CssTokenType.Character);
|
||||
expect(tokens[1].strValue).toEqual("*");
|
||||
expect(tokens[1].strValue).toEqual('*');
|
||||
|
||||
expect(tokens[2].type).toEqual(CssTokenType.Identifier);
|
||||
expect(tokens[2].strValue).toEqual("two");
|
||||
expect(tokens[2].strValue).toEqual('two');
|
||||
|
||||
expect(tokens[3].type).toEqual(CssTokenType.Character);
|
||||
expect(tokens[3].strValue).toEqual("=");
|
||||
expect(tokens[3].strValue).toEqual('=');
|
||||
|
||||
expect(tokens[4].type).toEqual(CssTokenType.Number);
|
||||
expect(tokens[4].strValue).toEqual("-4");
|
||||
expect(tokens[4].strValue).toEqual('-4');
|
||||
|
||||
expect(tokens[5].type).toEqual(CssTokenType.Character);
|
||||
expect(tokens[5].strValue).toEqual("+");
|
||||
expect(tokens[5].strValue).toEqual('+');
|
||||
|
||||
expect(tokens[6].type).toEqual(CssTokenType.Identifier);
|
||||
expect(tokens[6].strValue).toEqual("three-4-equals_value");
|
||||
expect(tokens[6].strValue).toEqual('three-4-equals_value');
|
||||
|
||||
expect(tokens[7].type).toEqual(CssTokenType.Character);
|
||||
expect(tokens[7].strValue).toEqual("$");
|
||||
expect(tokens[7].strValue).toEqual('$');
|
||||
});
|
||||
|
||||
it('should filter out comments and whitespace by default', () => {
|
||||
var cssCode = ".selector /* comment */ { /* value */ }";
|
||||
var cssCode = '.selector /* comment */ { /* value */ }';
|
||||
var tokens = tokenize(cssCode);
|
||||
|
||||
expect(tokens[0].strValue).toEqual(".");
|
||||
expect(tokens[1].strValue).toEqual("selector");
|
||||
expect(tokens[2].strValue).toEqual("{");
|
||||
expect(tokens[3].strValue).toEqual("}");
|
||||
expect(tokens[0].strValue).toEqual('.');
|
||||
expect(tokens[1].strValue).toEqual('selector');
|
||||
expect(tokens[2].strValue).toEqual('{');
|
||||
expect(tokens[3].strValue).toEqual('}');
|
||||
});
|
||||
|
||||
it('should track comments when the flag is set to true', () => {
|
||||
var cssCode = ".selector /* comment */ { /* value */ }";
|
||||
var cssCode = '.selector /* comment */ { /* value */ }';
|
||||
var trackComments = true;
|
||||
var tokens = tokenize(cssCode, trackComments, CssLexerMode.ALL_TRACK_WS);
|
||||
|
||||
expect(tokens[0].strValue).toEqual(".");
|
||||
expect(tokens[1].strValue).toEqual("selector");
|
||||
expect(tokens[2].strValue).toEqual(" ");
|
||||
expect(tokens[0].strValue).toEqual('.');
|
||||
expect(tokens[1].strValue).toEqual('selector');
|
||||
expect(tokens[2].strValue).toEqual(' ');
|
||||
|
||||
expect(tokens[3].type).toEqual(CssTokenType.Comment);
|
||||
expect(tokens[3].strValue).toEqual("/* comment */");
|
||||
expect(tokens[3].strValue).toEqual('/* comment */');
|
||||
|
||||
expect(tokens[4].strValue).toEqual(" ");
|
||||
expect(tokens[5].strValue).toEqual("{");
|
||||
expect(tokens[6].strValue).toEqual(" ");
|
||||
expect(tokens[4].strValue).toEqual(' ');
|
||||
expect(tokens[5].strValue).toEqual('{');
|
||||
expect(tokens[6].strValue).toEqual(' ');
|
||||
|
||||
expect(tokens[7].type).toEqual(CssTokenType.Comment);
|
||||
expect(tokens[7].strValue).toEqual("/* value */");
|
||||
expect(tokens[7].strValue).toEqual('/* value */');
|
||||
});
|
||||
|
||||
describe('Selector Mode', () => {
|
||||
it('should throw an error if a selector is being parsed while in the wrong mode', () => {
|
||||
var cssCode = ".class > tag";
|
||||
var cssCode = '.class > tag';
|
||||
|
||||
var capturedMessage;
|
||||
try {
|
||||
@@ -305,18 +293,18 @@ export function main() {
|
||||
it('should consider attribute selectors as valid input and throw when an invalid modifier is used',
|
||||
() => {
|
||||
function tokenizeAttr(modifier) {
|
||||
var cssCode = "value" + modifier + "='something'";
|
||||
var cssCode = 'value' + modifier + '=\'something\'';
|
||||
return tokenize(cssCode, false, CssLexerMode.ATTRIBUTE_SELECTOR);
|
||||
}
|
||||
|
||||
expect(tokenizeAttr("*").length).toEqual(4);
|
||||
expect(tokenizeAttr("|").length).toEqual(4);
|
||||
expect(tokenizeAttr("^").length).toEqual(4);
|
||||
expect(tokenizeAttr("$").length).toEqual(4);
|
||||
expect(tokenizeAttr("~").length).toEqual(4);
|
||||
expect(tokenizeAttr("").length).toEqual(3);
|
||||
expect(tokenizeAttr('*').length).toEqual(4);
|
||||
expect(tokenizeAttr('|').length).toEqual(4);
|
||||
expect(tokenizeAttr('^').length).toEqual(4);
|
||||
expect(tokenizeAttr('$').length).toEqual(4);
|
||||
expect(tokenizeAttr('~').length).toEqual(4);
|
||||
expect(tokenizeAttr('').length).toEqual(3);
|
||||
|
||||
expect(() => { tokenizeAttr("+"); }).toThrow();
|
||||
expect(() => { tokenizeAttr('+'); }).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -326,15 +314,15 @@ export function main() {
|
||||
|
||||
// the reason why the numbers are so high is because MediaQueries keep
|
||||
// track of the whitespace values
|
||||
expect(tokenizeQuery("(prop: value)").length).toEqual(5);
|
||||
expect(tokenizeQuery("(prop: value) and (prop2: value2)").length).toEqual(11);
|
||||
expect(tokenizeQuery("tv and (prop: value)").length).toEqual(7);
|
||||
expect(tokenizeQuery("print and ((prop: value) or (prop2: value2))").length).toEqual(15);
|
||||
expect(tokenizeQuery("(content: 'something $ crazy inside &')").length).toEqual(5);
|
||||
expect(tokenizeQuery('(prop: value)').length).toEqual(5);
|
||||
expect(tokenizeQuery('(prop: value) and (prop2: value2)').length).toEqual(11);
|
||||
expect(tokenizeQuery('tv and (prop: value)').length).toEqual(7);
|
||||
expect(tokenizeQuery('print and ((prop: value) or (prop2: value2))').length).toEqual(15);
|
||||
expect(tokenizeQuery('(content: \'something $ crazy inside &\')').length).toEqual(5);
|
||||
|
||||
expect(() => { tokenizeQuery("(max-height: 10 + 20)"); }).toThrow();
|
||||
expect(() => { tokenizeQuery('(max-height: 10 + 20)'); }).toThrow();
|
||||
|
||||
expect(() => { tokenizeQuery("(max-height: fifty < 100)"); }).toThrow();
|
||||
expect(() => { tokenizeQuery('(max-height: fifty < 100)'); }).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -345,13 +333,13 @@ export function main() {
|
||||
return tokenize(code, false, CssLexerMode.PSEUDO_SELECTOR);
|
||||
}
|
||||
|
||||
expect(tokenizePseudo("lang(en-us)").length).toEqual(4);
|
||||
expect(tokenizePseudo("hover").length).toEqual(1);
|
||||
expect(tokenizePseudo("focus").length).toEqual(1);
|
||||
expect(tokenizePseudo('lang(en-us)').length).toEqual(4);
|
||||
expect(tokenizePseudo('hover').length).toEqual(1);
|
||||
expect(tokenizePseudo('focus').length).toEqual(1);
|
||||
|
||||
expect(() => { tokenizePseudo("lang(something:broken)"); }).toThrow();
|
||||
expect(() => { tokenizePseudo('lang(something:broken)'); }).toThrow();
|
||||
|
||||
expect(() => { tokenizePseudo("not(.selector)"); }).toThrow();
|
||||
expect(() => { tokenizePseudo('not(.selector)'); }).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -362,32 +350,35 @@ export function main() {
|
||||
return tokenize(code, false, CssLexerMode.PSEUDO_SELECTOR);
|
||||
}
|
||||
|
||||
expect(tokenizePseudo("lang(en-us)").length).toEqual(4);
|
||||
expect(tokenizePseudo("hover").length).toEqual(1);
|
||||
expect(tokenizePseudo("focus").length).toEqual(1);
|
||||
expect(tokenizePseudo('lang(en-us)').length).toEqual(4);
|
||||
expect(tokenizePseudo('hover').length).toEqual(1);
|
||||
expect(tokenizePseudo('focus').length).toEqual(1);
|
||||
|
||||
expect(() => { tokenizePseudo("lang(something:broken)"); }).toThrow();
|
||||
expect(() => { tokenizePseudo('lang(something:broken)'); }).toThrow();
|
||||
|
||||
expect(() => { tokenizePseudo("not(.selector)"); }).toThrow();
|
||||
expect(() => { tokenizePseudo('not(.selector)'); }).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Style Block Mode', () => {
|
||||
it('should style blocks with a reduced subset of valid characters', () => {
|
||||
function tokenizeStyles(code) { return tokenize(code, false, CssLexerMode.STYLE_BLOCK); }
|
||||
describe(
|
||||
'Style Block Mode', () => {
|
||||
it('should style blocks with a reduced subset of valid characters',
|
||||
() => {
|
||||
function tokenizeStyles(code) {
|
||||
return tokenize(code, false, CssLexerMode.STYLE_BLOCK);
|
||||
}
|
||||
|
||||
expect(tokenizeStyles(`
|
||||
expect(tokenizeStyles(`
|
||||
key: value;
|
||||
prop: 100;
|
||||
style: value3!important;
|
||||
`).length)
|
||||
.toEqual(14);
|
||||
`).length).toEqual(14);
|
||||
|
||||
expect(() => tokenizeStyles(` key$: value; `)).toThrow();
|
||||
expect(() => tokenizeStyles(` key: value$; `)).toThrow();
|
||||
expect(() => tokenizeStyles(` key: value + 10; `)).toThrow();
|
||||
expect(() => tokenizeStyles(` key: &value; `)).toThrow();
|
||||
});
|
||||
});
|
||||
expect(() => tokenizeStyles(` key$: value; `)).toThrow();
|
||||
expect(() => tokenizeStyles(` key: value$; `)).toThrow();
|
||||
expect(() => tokenizeStyles(` key: value + 10; `)).toThrow();
|
||||
expect(() => tokenizeStyles(` key: &value; `)).toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,35 +1,8 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
|
||||
import {BaseException} from 'angular2/src/facade/exceptions';
|
||||
|
||||
import {
|
||||
ParsedCssResult,
|
||||
CssParser,
|
||||
BlockType,
|
||||
CssSelectorRuleAST,
|
||||
CssKeyframeRuleAST,
|
||||
CssKeyframeDefinitionAST,
|
||||
CssBlockDefinitionRuleAST,
|
||||
CssMediaQueryRuleAST,
|
||||
CssBlockRuleAST,
|
||||
CssInlineRuleAST,
|
||||
CssStyleValueAST,
|
||||
CssSelectorAST,
|
||||
CssDefinitionAST,
|
||||
CssStyleSheetAST,
|
||||
CssRuleAST,
|
||||
CssBlockAST,
|
||||
CssParseError
|
||||
} from 'angular2/src/compiler/css/parser';
|
||||
import {ParsedCssResult, CssParser, BlockType, CssSelectorRuleAST, CssKeyframeRuleAST, CssKeyframeDefinitionAST, CssBlockDefinitionRuleAST, CssMediaQueryRuleAST, CssBlockRuleAST, CssInlineRuleAST, CssStyleValueAST, CssSelectorAST, CssDefinitionAST, CssStyleSheetAST, CssRuleAST, CssBlockAST, CssParseError} from 'angular2/src/compiler/css/parser';
|
||||
|
||||
import {CssLexer} from 'angular2/src/compiler/css/lexer';
|
||||
|
||||
@@ -94,17 +67,17 @@ export function main() {
|
||||
var rule = <CssSelectorRuleAST>ast.rules[0];
|
||||
expect(rule.selectors.length).toBe(7);
|
||||
|
||||
assertTokens(rule.selectors[0].tokens, [".", "class"]);
|
||||
assertTokens(rule.selectors[1].tokens, ["#", "id"]);
|
||||
assertTokens(rule.selectors[2].tokens, ["tag"]);
|
||||
assertTokens(rule.selectors[3].tokens, ["[", "attr", "]"]);
|
||||
assertTokens(rule.selectors[4].tokens, ["key", " ", "+", " ", "value"]);
|
||||
assertTokens(rule.selectors[5].tokens, ["*", " ", "value"]);
|
||||
assertTokens(rule.selectors[6].tokens, [":", "-moz-any-link"]);
|
||||
assertTokens(rule.selectors[0].tokens, ['.', 'class']);
|
||||
assertTokens(rule.selectors[1].tokens, ['#', 'id']);
|
||||
assertTokens(rule.selectors[2].tokens, ['tag']);
|
||||
assertTokens(rule.selectors[3].tokens, ['[', 'attr', ']']);
|
||||
assertTokens(rule.selectors[4].tokens, ['key', ' ', '+', ' ', 'value']);
|
||||
assertTokens(rule.selectors[5].tokens, ['*', ' ', 'value']);
|
||||
assertTokens(rule.selectors[6].tokens, [':', '-moz-any-link']);
|
||||
|
||||
var style1 = <CssDefinitionAST>rule.block.entries[0];
|
||||
expect(style1.property.strValue).toEqual("prop");
|
||||
assertTokens(style1.value.tokens, ["value123"]);
|
||||
expect(style1.property.strValue).toEqual('prop');
|
||||
assertTokens(style1.value.tokens, ['value123']);
|
||||
});
|
||||
|
||||
it('should parse keyframe rules', () => {
|
||||
@@ -187,16 +160,16 @@ export function main() {
|
||||
|
||||
var importRule = <CssInlineRuleAST>ast.rules[0];
|
||||
expect(importRule.type).toEqual(BlockType.Import);
|
||||
assertTokens(importRule.value.tokens, ["url", "(", "remote", ".", "css", ")"]);
|
||||
assertTokens(importRule.value.tokens, ['url', '(', 'remote', '.', 'css', ')']);
|
||||
|
||||
var charsetRule = <CssInlineRuleAST>ast.rules[1];
|
||||
expect(charsetRule.type).toEqual(BlockType.Charset);
|
||||
assertTokens(charsetRule.value.tokens, ["UTF-8"]);
|
||||
assertTokens(charsetRule.value.tokens, ['UTF-8']);
|
||||
|
||||
var namespaceRule = <CssInlineRuleAST>ast.rules[2];
|
||||
expect(namespaceRule.type).toEqual(BlockType.Namespace);
|
||||
assertTokens(namespaceRule.value.tokens,
|
||||
["ng", "url", "(", "http://angular.io/namespace/ng", ")"]);
|
||||
assertTokens(
|
||||
namespaceRule.value.tokens, ['ng', 'url', '(', 'http://angular.io/namespace/ng', ')']);
|
||||
});
|
||||
|
||||
it('should parse CSS values that contain functions and leave the inner function data untokenized',
|
||||
@@ -216,8 +189,9 @@ export function main() {
|
||||
expect(defs.length).toEqual(3);
|
||||
|
||||
assertTokens((<CssDefinitionAST>defs[0]).value.tokens, ['url', '(', 'matias.css', ')']);
|
||||
assertTokens((<CssDefinitionAST>defs[1]).value.tokens,
|
||||
['cubic-bezier', '(', '0.755, 0.050, 0.855, 0.060', ')']);
|
||||
assertTokens(
|
||||
(<CssDefinitionAST>defs[1]).value.tokens,
|
||||
['cubic-bezier', '(', '0.755, 0.050, 0.855, 0.060', ')']);
|
||||
assertTokens((<CssDefinitionAST>defs[2]).value.tokens, ['calc', '(', '100% - 50px', ')']);
|
||||
});
|
||||
|
||||
@@ -265,7 +239,7 @@ export function main() {
|
||||
|
||||
var importRule = <CssInlineRuleAST>ast.rules[0];
|
||||
expect(importRule.type).toEqual(BlockType.Import);
|
||||
assertTokens(importRule.value.tokens, ["url", "(", "something something", ")"]);
|
||||
assertTokens(importRule.value.tokens, ['url', '(', 'something something', ')']);
|
||||
|
||||
var fontFaceRule = <CssBlockRuleAST>ast.rules[1];
|
||||
expect(fontFaceRule.type).toEqual(BlockType.FontFace);
|
||||
@@ -330,7 +304,7 @@ export function main() {
|
||||
expect(documentRule.type).toEqual(BlockType.Document);
|
||||
|
||||
var rule = <CssSelectorRuleAST>documentRule.block.entries[0];
|
||||
expect(rule.strValue).toEqual("body");
|
||||
expect(rule.strValue).toEqual('body');
|
||||
});
|
||||
|
||||
it('should parse the @page rule', () => {
|
||||
@@ -348,11 +322,11 @@ export function main() {
|
||||
var rules = ast.rules;
|
||||
|
||||
var pageRule1 = <CssBlockDefinitionRuleAST>rules[0];
|
||||
expect(pageRule1.strValue).toEqual("one");
|
||||
expect(pageRule1.strValue).toEqual('one');
|
||||
expect(pageRule1.type).toEqual(BlockType.Page);
|
||||
|
||||
var pageRule2 = <CssBlockDefinitionRuleAST>rules[1];
|
||||
expect(pageRule2.strValue).toEqual("two");
|
||||
expect(pageRule2.strValue).toEqual('two');
|
||||
expect(pageRule2.type).toEqual(BlockType.Page);
|
||||
|
||||
var selectorOne = <CssSelectorRuleAST>pageRule1.block.entries[0];
|
||||
@@ -408,15 +382,15 @@ export function main() {
|
||||
expect(ast.rules.length).toEqual(3);
|
||||
|
||||
var rule1 = <CssSelectorRuleAST>ast.rules[0];
|
||||
expect(rule1.selectors[0].strValue).toEqual("tag&");
|
||||
expect(rule1.selectors[0].strValue).toEqual('tag&');
|
||||
expect(rule1.block.entries.length).toEqual(1);
|
||||
|
||||
var rule2 = <CssSelectorRuleAST>ast.rules[1];
|
||||
expect(rule2.selectors[0].strValue).toEqual(".%tag");
|
||||
expect(rule2.selectors[0].strValue).toEqual('.%tag');
|
||||
expect(rule2.block.entries.length).toEqual(1);
|
||||
|
||||
var rule3 = <CssSelectorRuleAST>ast.rules[2];
|
||||
expect(rule3.selectors[0].strValue).toEqual("#tag$");
|
||||
expect(rule3.selectors[0].strValue).toEqual('#tag$');
|
||||
expect(rule3.block.entries.length).toEqual(1);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,39 +1,9 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
|
||||
import {NumberWrapper, StringWrapper, isPresent} from "angular2/src/facade/lang";
|
||||
import {NumberWrapper, StringWrapper, isPresent} from 'angular2/src/facade/lang';
|
||||
import {BaseException} from 'angular2/src/facade/exceptions';
|
||||
|
||||
import {
|
||||
CssToken,
|
||||
CssParser,
|
||||
CssParseError,
|
||||
BlockType,
|
||||
CssAST,
|
||||
CssSelectorRuleAST,
|
||||
CssKeyframeRuleAST,
|
||||
CssKeyframeDefinitionAST,
|
||||
CssBlockDefinitionRuleAST,
|
||||
CssMediaQueryRuleAST,
|
||||
CssBlockRuleAST,
|
||||
CssInlineRuleAST,
|
||||
CssStyleValueAST,
|
||||
CssSelectorAST,
|
||||
CssDefinitionAST,
|
||||
CssStyleSheetAST,
|
||||
CssRuleAST,
|
||||
CssBlockAST,
|
||||
CssASTVisitor,
|
||||
CssUnknownTokenListAST
|
||||
} from 'angular2/src/compiler/css/parser';
|
||||
import {CssToken, CssParser, CssParseError, BlockType, CssAST, CssSelectorRuleAST, CssKeyframeRuleAST, CssKeyframeDefinitionAST, CssBlockDefinitionRuleAST, CssMediaQueryRuleAST, CssBlockRuleAST, CssInlineRuleAST, CssStyleValueAST, CssSelectorAST, CssDefinitionAST, CssStyleSheetAST, CssRuleAST, CssBlockAST, CssASTVisitor, CssUnknownTokenListAST} from 'angular2/src/compiler/css/parser';
|
||||
|
||||
import {CssLexer} from 'angular2/src/compiler/css/lexer';
|
||||
|
||||
@@ -53,49 +23,49 @@ class MyVisitor implements CssASTVisitor {
|
||||
|
||||
constructor(ast: CssStyleSheetAST, context?: any) { ast.visit(this, context); }
|
||||
|
||||
visitCssValue(ast, context?: any): void { this._capture("visitCssValue", ast, context); }
|
||||
visitCssValue(ast, context?: any): void { this._capture('visitCssValue', ast, context); }
|
||||
|
||||
visitInlineCssRule(ast, context?: any): void {
|
||||
this._capture("visitInlineCssRule", ast, context);
|
||||
this._capture('visitInlineCssRule', ast, context);
|
||||
}
|
||||
|
||||
visitCssKeyframeRule(ast: CssKeyframeRuleAST, context?: any): void {
|
||||
this._capture("visitCssKeyframeRule", ast, context);
|
||||
this._capture('visitCssKeyframeRule', ast, context);
|
||||
ast.block.visit(this, context);
|
||||
}
|
||||
|
||||
visitCssKeyframeDefinition(ast: CssKeyframeDefinitionAST, context?: any): void {
|
||||
this._capture("visitCssKeyframeDefinition", ast, context);
|
||||
this._capture('visitCssKeyframeDefinition', ast, context);
|
||||
ast.block.visit(this, context);
|
||||
}
|
||||
|
||||
visitCssMediaQueryRule(ast: CssMediaQueryRuleAST, context?: any): void {
|
||||
this._capture("visitCssMediaQueryRule", ast, context);
|
||||
this._capture('visitCssMediaQueryRule', ast, context);
|
||||
ast.block.visit(this, context);
|
||||
}
|
||||
|
||||
visitCssSelectorRule(ast: CssSelectorRuleAST, context?: any): void {
|
||||
this._capture("visitCssSelectorRule", ast, context);
|
||||
this._capture('visitCssSelectorRule', ast, context);
|
||||
ast.selectors.forEach((selAST: CssSelectorAST) => { selAST.visit(this, context); });
|
||||
ast.block.visit(this, context);
|
||||
}
|
||||
|
||||
visitCssSelector(ast: CssSelectorAST, context?: any): void {
|
||||
this._capture("visitCssSelector", ast, context);
|
||||
this._capture('visitCssSelector', ast, context);
|
||||
}
|
||||
|
||||
visitCssDefinition(ast: CssDefinitionAST, context?: any): void {
|
||||
this._capture("visitCssDefinition", ast, context);
|
||||
this._capture('visitCssDefinition', ast, context);
|
||||
ast.value.visit(this, context);
|
||||
}
|
||||
|
||||
visitCssBlock(ast: CssBlockAST, context?: any): void {
|
||||
this._capture("visitCssBlock", ast, context);
|
||||
this._capture('visitCssBlock', ast, context);
|
||||
ast.entries.forEach((entryAST: CssAST) => { entryAST.visit(this, context); });
|
||||
}
|
||||
|
||||
visitCssStyleSheet(ast: CssStyleSheetAST, context?: any): void {
|
||||
this._capture("visitCssStyleSheet", ast, context);
|
||||
this._capture('visitCssStyleSheet', ast, context);
|
||||
ast.rules.forEach((ruleAST: CssRuleAST) => { ruleAST.visit(this, context); });
|
||||
}
|
||||
|
||||
@@ -208,7 +178,7 @@ export function main() {
|
||||
expect(captures.length).toEqual(1);
|
||||
|
||||
var query1 = <CssMediaQueryRuleAST>captures[0][0];
|
||||
_assertTokens(query1.query, ["all", "and", "(", "max-width", "100", "px", ")"]);
|
||||
_assertTokens(query1.query, ['all', 'and', '(', 'max-width', '100', 'px', ')']);
|
||||
expect(query1.block.entries.length).toEqual(1);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,27 +1,6 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
TestComponentBuilder
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit, TestComponentBuilder} from 'angular2/testing_internal';
|
||||
|
||||
import {
|
||||
CompileDirectiveMetadata,
|
||||
CompileTypeMetadata,
|
||||
CompileTemplateMetadata,
|
||||
CompileProviderMetadata,
|
||||
CompileDiDependencyMetadata,
|
||||
CompileQueryMetadata,
|
||||
CompileIdentifierMetadata,
|
||||
CompileFactoryMetadata
|
||||
} from 'angular2/src/compiler/directive_metadata';
|
||||
import {CompileDirectiveMetadata, CompileTypeMetadata, CompileTemplateMetadata, CompileProviderMetadata, CompileDiDependencyMetadata, CompileQueryMetadata, CompileIdentifierMetadata, CompileFactoryMetadata} from 'angular2/src/compiler/directive_metadata';
|
||||
import {ViewEncapsulation} from 'angular2/src/core/metadata/view';
|
||||
import {ChangeDetectionStrategy} from 'angular2/src/core/change_detection';
|
||||
import {LifecycleHooks} from 'angular2/src/core/linker/interfaces';
|
||||
@@ -67,32 +46,24 @@ export function main() {
|
||||
outputs: ['someEvent'],
|
||||
host: {'(event1)': 'handler1', '[prop1]': 'expr1', 'attr1': 'attrValue2'},
|
||||
lifecycleHooks: [LifecycleHooks.OnChanges],
|
||||
providers: [
|
||||
new CompileProviderMetadata({
|
||||
token: 'token',
|
||||
useClass: fullTypeMeta,
|
||||
useExisting: new CompileIdentifierMetadata({name: 'someName'}),
|
||||
useFactory: new CompileFactoryMetadata({name: 'someName', diDeps: [diDep]}),
|
||||
useValue: 'someValue',
|
||||
})
|
||||
],
|
||||
viewProviders: [
|
||||
new CompileProviderMetadata({
|
||||
token: 'token',
|
||||
useClass: fullTypeMeta,
|
||||
useExisting: new CompileIdentifierMetadata({name: 'someName'}),
|
||||
useFactory: new CompileFactoryMetadata({name: 'someName', diDeps: [diDep]}),
|
||||
useValue: 'someValue',
|
||||
})
|
||||
],
|
||||
queries: [
|
||||
new CompileQueryMetadata(
|
||||
{selectors: ['selector'], descendants: true, first: false, propertyName: 'prop'})
|
||||
],
|
||||
viewQueries: [
|
||||
new CompileQueryMetadata(
|
||||
{selectors: ['selector'], descendants: true, first: false, propertyName: 'prop'})
|
||||
]
|
||||
providers: [new CompileProviderMetadata({
|
||||
token: 'token',
|
||||
useClass: fullTypeMeta,
|
||||
useExisting: new CompileIdentifierMetadata({name: 'someName'}),
|
||||
useFactory: new CompileFactoryMetadata({name: 'someName', diDeps: [diDep]}),
|
||||
useValue: 'someValue',
|
||||
})],
|
||||
viewProviders: [new CompileProviderMetadata({
|
||||
token: 'token',
|
||||
useClass: fullTypeMeta,
|
||||
useExisting: new CompileIdentifierMetadata({name: 'someName'}),
|
||||
useFactory: new CompileFactoryMetadata({name: 'someName', diDeps: [diDep]}),
|
||||
useValue: 'someValue',
|
||||
})],
|
||||
queries: [new CompileQueryMetadata(
|
||||
{selectors: ['selector'], descendants: true, first: false, propertyName: 'prop'})],
|
||||
viewQueries: [new CompileQueryMetadata(
|
||||
{selectors: ['selector'], descendants: true, first: false, propertyName: 'prop'})]
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -1,16 +1,4 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
xdescribe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
AsyncTestCompleter,
|
||||
inject
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject} from 'angular2/testing_internal';
|
||||
import {IS_DART} from 'angular2/src/facade/lang';
|
||||
|
||||
import {evalModule} from './eval_module';
|
||||
@@ -31,11 +19,10 @@ export function main() {
|
||||
it('should call the "run" function and allow to use imports',
|
||||
inject([AsyncTestCompleter], (async) => {
|
||||
var moduleSource = IS_DART ? testDartModule : testJsModule;
|
||||
evalModule(moduleSource, [[THIS_MODULE_URL, 'tst']], [1])
|
||||
.then((value) => {
|
||||
expect(value).toEqual([1, 23]);
|
||||
async.done();
|
||||
});
|
||||
evalModule(moduleSource, [[THIS_MODULE_URL, 'tst']], [1]).then((value) => {
|
||||
expect(value).toEqual([1, 23]);
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
import {HtmlParser, HtmlParseTreeResult, HtmlTreeError} from 'angular2/src/compiler/html_parser';
|
||||
import {
|
||||
HtmlAst,
|
||||
HtmlAstVisitor,
|
||||
HtmlElementAst,
|
||||
HtmlAttrAst,
|
||||
HtmlTextAst,
|
||||
HtmlCommentAst,
|
||||
htmlVisitAll
|
||||
} from 'angular2/src/compiler/html_ast';
|
||||
import {HtmlAst, HtmlAstVisitor, HtmlElementAst, HtmlAttrAst, HtmlTextAst, HtmlCommentAst, htmlVisitAll} from 'angular2/src/compiler/html_ast';
|
||||
import {ParseError, ParseLocation} from 'angular2/src/compiler/parse_util';
|
||||
import {BaseException} from 'angular2/src/facade/exceptions';
|
||||
|
||||
|
||||
@@ -1,584 +1,479 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
import {BaseException} from 'angular2/src/facade/exceptions';
|
||||
|
||||
import {
|
||||
tokenizeHtml,
|
||||
HtmlToken,
|
||||
HtmlTokenType,
|
||||
HtmlTokenError
|
||||
} from 'angular2/src/compiler/html_lexer';
|
||||
import {tokenizeHtml, HtmlToken, HtmlTokenType, HtmlTokenError} from 'angular2/src/compiler/html_lexer';
|
||||
import {ParseSourceSpan, ParseLocation, ParseSourceFile} from 'angular2/src/compiler/parse_util';
|
||||
|
||||
export function main() {
|
||||
describe('HtmlLexer', () => {
|
||||
describe('line/column numbers', () => {
|
||||
it('should work without newlines', () => {
|
||||
expect(tokenizeAndHumanizeLineColumn('<t>a</t>'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '0:0'],
|
||||
[HtmlTokenType.TAG_OPEN_END, '0:2'],
|
||||
[HtmlTokenType.TEXT, '0:3'],
|
||||
[HtmlTokenType.TAG_CLOSE, '0:4'],
|
||||
[HtmlTokenType.EOF, '0:8']
|
||||
]);
|
||||
expect(tokenizeAndHumanizeLineColumn('<t>a</t>')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '0:0'], [HtmlTokenType.TAG_OPEN_END, '0:2'],
|
||||
[HtmlTokenType.TEXT, '0:3'], [HtmlTokenType.TAG_CLOSE, '0:4'],
|
||||
[HtmlTokenType.EOF, '0:8']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should work with one newline', () => {
|
||||
expect(tokenizeAndHumanizeLineColumn('<t>\na</t>'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '0:0'],
|
||||
[HtmlTokenType.TAG_OPEN_END, '0:2'],
|
||||
[HtmlTokenType.TEXT, '0:3'],
|
||||
[HtmlTokenType.TAG_CLOSE, '1:1'],
|
||||
[HtmlTokenType.EOF, '1:5']
|
||||
]);
|
||||
expect(tokenizeAndHumanizeLineColumn('<t>\na</t>')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '0:0'], [HtmlTokenType.TAG_OPEN_END, '0:2'],
|
||||
[HtmlTokenType.TEXT, '0:3'], [HtmlTokenType.TAG_CLOSE, '1:1'],
|
||||
[HtmlTokenType.EOF, '1:5']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should work with multiple newlines', () => {
|
||||
expect(tokenizeAndHumanizeLineColumn('<t\n>\na</t>'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '0:0'],
|
||||
[HtmlTokenType.TAG_OPEN_END, '1:0'],
|
||||
[HtmlTokenType.TEXT, '1:1'],
|
||||
[HtmlTokenType.TAG_CLOSE, '2:1'],
|
||||
[HtmlTokenType.EOF, '2:5']
|
||||
]);
|
||||
expect(tokenizeAndHumanizeLineColumn('<t\n>\na</t>')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '0:0'], [HtmlTokenType.TAG_OPEN_END, '1:0'],
|
||||
[HtmlTokenType.TEXT, '1:1'], [HtmlTokenType.TAG_CLOSE, '2:1'],
|
||||
[HtmlTokenType.EOF, '2:5']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should work with CR and LF', () => {
|
||||
expect(tokenizeAndHumanizeLineColumn('<t\n>\r\na\r</t>'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '0:0'],
|
||||
[HtmlTokenType.TAG_OPEN_END, '1:0'],
|
||||
[HtmlTokenType.TEXT, '1:1'],
|
||||
[HtmlTokenType.TAG_CLOSE, '2:1'],
|
||||
[HtmlTokenType.EOF, '2:5']
|
||||
]);
|
||||
expect(tokenizeAndHumanizeLineColumn('<t\n>\r\na\r</t>')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '0:0'], [HtmlTokenType.TAG_OPEN_END, '1:0'],
|
||||
[HtmlTokenType.TEXT, '1:1'], [HtmlTokenType.TAG_CLOSE, '2:1'],
|
||||
[HtmlTokenType.EOF, '2:5']
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('comments', () => {
|
||||
it('should parse comments', () => {
|
||||
expect(tokenizeAndHumanizeParts('<!--t\ne\rs\r\nt-->'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.COMMENT_START],
|
||||
[HtmlTokenType.RAW_TEXT, 't\ne\ns\nt'],
|
||||
[HtmlTokenType.COMMENT_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<!--t\ne\rs\r\nt-->')).toEqual([
|
||||
[HtmlTokenType.COMMENT_START], [HtmlTokenType.RAW_TEXT, 't\ne\ns\nt'],
|
||||
[HtmlTokenType.COMMENT_END], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should store the locations',
|
||||
() => {expect(tokenizeAndHumanizeSourceSpans('<!--t\ne\rs\r\nt-->'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.COMMENT_START, '<!--'],
|
||||
[HtmlTokenType.RAW_TEXT, 't\ne\rs\r\nt'],
|
||||
[HtmlTokenType.COMMENT_END, '-->'],
|
||||
[HtmlTokenType.EOF, '']
|
||||
])});
|
||||
() => {expect(tokenizeAndHumanizeSourceSpans('<!--t\ne\rs\r\nt-->')).toEqual([
|
||||
[HtmlTokenType.COMMENT_START, '<!--'], [HtmlTokenType.RAW_TEXT, 't\ne\rs\r\nt'],
|
||||
[HtmlTokenType.COMMENT_END, '-->'], [HtmlTokenType.EOF, '']
|
||||
])});
|
||||
|
||||
it('should report <!- without -', () => {
|
||||
expect(tokenizeAndHumanizeErrors('<!-a'))
|
||||
.toEqual([[HtmlTokenType.COMMENT_START, 'Unexpected character "a"', '0:3']]);
|
||||
expect(tokenizeAndHumanizeErrors('<!-a')).toEqual([
|
||||
[HtmlTokenType.COMMENT_START, 'Unexpected character "a"', '0:3']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should report missing end comment', () => {
|
||||
expect(tokenizeAndHumanizeErrors('<!--'))
|
||||
.toEqual([[HtmlTokenType.RAW_TEXT, 'Unexpected character "EOF"', '0:4']]);
|
||||
expect(tokenizeAndHumanizeErrors('<!--')).toEqual([
|
||||
[HtmlTokenType.RAW_TEXT, 'Unexpected character "EOF"', '0:4']
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('doctype', () => {
|
||||
it('should parse doctypes', () => {
|
||||
expect(tokenizeAndHumanizeParts('<!doctype html>'))
|
||||
.toEqual([[HtmlTokenType.DOC_TYPE, 'doctype html'], [HtmlTokenType.EOF]]);
|
||||
expect(tokenizeAndHumanizeParts('<!doctype html>')).toEqual([
|
||||
[HtmlTokenType.DOC_TYPE, 'doctype html'], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should store the locations', () => {
|
||||
expect(tokenizeAndHumanizeSourceSpans('<!doctype html>'))
|
||||
.toEqual([[HtmlTokenType.DOC_TYPE, '<!doctype html>'], [HtmlTokenType.EOF, '']]);
|
||||
expect(tokenizeAndHumanizeSourceSpans('<!doctype html>')).toEqual([
|
||||
[HtmlTokenType.DOC_TYPE, '<!doctype html>'], [HtmlTokenType.EOF, '']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should report missing end doctype', () => {
|
||||
expect(tokenizeAndHumanizeErrors('<!'))
|
||||
.toEqual([[HtmlTokenType.DOC_TYPE, 'Unexpected character "EOF"', '0:2']]);
|
||||
expect(tokenizeAndHumanizeErrors('<!')).toEqual([
|
||||
[HtmlTokenType.DOC_TYPE, 'Unexpected character "EOF"', '0:2']
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('CDATA', () => {
|
||||
it('should parse CDATA', () => {
|
||||
expect(tokenizeAndHumanizeParts('<![CDATA[t\ne\rs\r\nt]]>'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.CDATA_START],
|
||||
[HtmlTokenType.RAW_TEXT, 't\ne\ns\nt'],
|
||||
[HtmlTokenType.CDATA_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<![CDATA[t\ne\rs\r\nt]]>')).toEqual([
|
||||
[HtmlTokenType.CDATA_START], [HtmlTokenType.RAW_TEXT, 't\ne\ns\nt'],
|
||||
[HtmlTokenType.CDATA_END], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should store the locations', () => {
|
||||
expect(tokenizeAndHumanizeSourceSpans('<![CDATA[t\ne\rs\r\nt]]>'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.CDATA_START, '<![CDATA['],
|
||||
[HtmlTokenType.RAW_TEXT, 't\ne\rs\r\nt'],
|
||||
[HtmlTokenType.CDATA_END, ']]>'],
|
||||
[HtmlTokenType.EOF, '']
|
||||
]);
|
||||
expect(tokenizeAndHumanizeSourceSpans('<![CDATA[t\ne\rs\r\nt]]>')).toEqual([
|
||||
[HtmlTokenType.CDATA_START, '<![CDATA['], [HtmlTokenType.RAW_TEXT, 't\ne\rs\r\nt'],
|
||||
[HtmlTokenType.CDATA_END, ']]>'], [HtmlTokenType.EOF, '']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should report <![ without CDATA[', () => {
|
||||
expect(tokenizeAndHumanizeErrors('<![a'))
|
||||
.toEqual([[HtmlTokenType.CDATA_START, 'Unexpected character "a"', '0:3']]);
|
||||
expect(tokenizeAndHumanizeErrors('<![a')).toEqual([
|
||||
[HtmlTokenType.CDATA_START, 'Unexpected character "a"', '0:3']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should report missing end cdata', () => {
|
||||
expect(tokenizeAndHumanizeErrors('<![CDATA['))
|
||||
.toEqual([[HtmlTokenType.RAW_TEXT, 'Unexpected character "EOF"', '0:9']]);
|
||||
expect(tokenizeAndHumanizeErrors('<![CDATA[')).toEqual([
|
||||
[HtmlTokenType.RAW_TEXT, 'Unexpected character "EOF"', '0:9']
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('open tags', () => {
|
||||
it('should parse open tags without prefix', () => {
|
||||
expect(tokenizeAndHumanizeParts('<test>'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'test'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<test>')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'test'], [HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse namespace prefix', () => {
|
||||
expect(tokenizeAndHumanizeParts('<ns1:test>'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, 'ns1', 'test'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<ns1:test>')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, 'ns1', 'test'], [HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse void tags', () => {
|
||||
expect(tokenizeAndHumanizeParts('<test/>'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'test'],
|
||||
[HtmlTokenType.TAG_OPEN_END_VOID],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<test/>')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'test'], [HtmlTokenType.TAG_OPEN_END_VOID],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should allow whitespace after the tag name', () => {
|
||||
expect(tokenizeAndHumanizeParts('<test >'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'test'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<test >')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'test'], [HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should store the locations', () => {
|
||||
expect(tokenizeAndHumanizeSourceSpans('<test>'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '<test'],
|
||||
[HtmlTokenType.TAG_OPEN_END, '>'],
|
||||
[HtmlTokenType.EOF, '']
|
||||
]);
|
||||
expect(tokenizeAndHumanizeSourceSpans('<test>')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '<test'], [HtmlTokenType.TAG_OPEN_END, '>'],
|
||||
[HtmlTokenType.EOF, '']
|
||||
]);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('attributes', () => {
|
||||
it('should parse attributes without prefix', () => {
|
||||
expect(tokenizeAndHumanizeParts('<t a>'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||
[HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<t a>')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse attributes with prefix', () => {
|
||||
expect(tokenizeAndHumanizeParts('<t ns1:a>'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||
[HtmlTokenType.ATTR_NAME, 'ns1', 'a'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<t ns1:a>')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, 'ns1', 'a'],
|
||||
[HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse attributes whose prefix is not valid', () => {
|
||||
expect(tokenizeAndHumanizeParts('<t (ns1:a)>'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||
[HtmlTokenType.ATTR_NAME, null, '(ns1:a)'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<t (ns1:a)>')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, '(ns1:a)'],
|
||||
[HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse attributes with single quote value', () => {
|
||||
expect(tokenizeAndHumanizeParts("<t a='b'>"))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||
[HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, 'b'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<t a=\'b\'>')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, 'b'], [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse attributes with double quote value', () => {
|
||||
expect(tokenizeAndHumanizeParts('<t a="b">'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||
[HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, 'b'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<t a="b">')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, 'b'], [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse attributes with unquoted value', () => {
|
||||
expect(tokenizeAndHumanizeParts('<t a=b>'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||
[HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, 'b'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<t a=b>')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, 'b'], [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should allow whitespace', () => {
|
||||
expect(tokenizeAndHumanizeParts('<t a = b >'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||
[HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, 'b'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<t a = b >')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, 'b'], [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse attributes with entities in values', () => {
|
||||
expect(tokenizeAndHumanizeParts('<t a="AA">'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||
[HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, 'AA'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<t a="AA">')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, 'AA'], [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should not decode entities without trailing ";"', () => {
|
||||
expect(tokenizeAndHumanizeParts('<t a="&" b="c&&d">'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||
[HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, '&'],
|
||||
[HtmlTokenType.ATTR_NAME, null, 'b'],
|
||||
[HtmlTokenType.ATTR_VALUE, 'c&&d'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<t a="&" b="c&&d">')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, '&'], [HtmlTokenType.ATTR_NAME, null, 'b'],
|
||||
[HtmlTokenType.ATTR_VALUE, 'c&&d'], [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse attributes with "&" in values', () => {
|
||||
expect(tokenizeAndHumanizeParts('<t a="b && c &">'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||
[HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, 'b && c &'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<t a="b && c &">')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, 'b && c &'], [HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse values with CR and LF', () => {
|
||||
expect(tokenizeAndHumanizeParts("<t a='t\ne\rs\r\nt'>"))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||
[HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, 't\ne\ns\nt'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('<t a=\'t\ne\rs\r\nt\'>')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 't'], [HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, 't\ne\ns\nt'], [HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should store the locations', () => {
|
||||
expect(tokenizeAndHumanizeSourceSpans('<t a=b>'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '<t'],
|
||||
[HtmlTokenType.ATTR_NAME, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, 'b'],
|
||||
[HtmlTokenType.TAG_OPEN_END, '>'],
|
||||
[HtmlTokenType.EOF, '']
|
||||
]);
|
||||
expect(tokenizeAndHumanizeSourceSpans('<t a=b>')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '<t'], [HtmlTokenType.ATTR_NAME, 'a'],
|
||||
[HtmlTokenType.ATTR_VALUE, 'b'], [HtmlTokenType.TAG_OPEN_END, '>'],
|
||||
[HtmlTokenType.EOF, '']
|
||||
]);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('closing tags', () => {
|
||||
it('should parse closing tags without prefix', () => {
|
||||
expect(tokenizeAndHumanizeParts('</test>'))
|
||||
.toEqual([[HtmlTokenType.TAG_CLOSE, null, 'test'], [HtmlTokenType.EOF]]);
|
||||
expect(tokenizeAndHumanizeParts('</test>')).toEqual([
|
||||
[HtmlTokenType.TAG_CLOSE, null, 'test'], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse closing tags with prefix', () => {
|
||||
expect(tokenizeAndHumanizeParts('</ns1:test>'))
|
||||
.toEqual([[HtmlTokenType.TAG_CLOSE, 'ns1', 'test'], [HtmlTokenType.EOF]]);
|
||||
expect(tokenizeAndHumanizeParts('</ns1:test>')).toEqual([
|
||||
[HtmlTokenType.TAG_CLOSE, 'ns1', 'test'], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should allow whitespace', () => {
|
||||
expect(tokenizeAndHumanizeParts('</ test >'))
|
||||
.toEqual([[HtmlTokenType.TAG_CLOSE, null, 'test'], [HtmlTokenType.EOF]]);
|
||||
expect(tokenizeAndHumanizeParts('</ test >')).toEqual([
|
||||
[HtmlTokenType.TAG_CLOSE, null, 'test'], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should store the locations', () => {
|
||||
expect(tokenizeAndHumanizeSourceSpans('</test>'))
|
||||
.toEqual([[HtmlTokenType.TAG_CLOSE, '</test>'], [HtmlTokenType.EOF, '']]);
|
||||
expect(tokenizeAndHumanizeSourceSpans('</test>')).toEqual([
|
||||
[HtmlTokenType.TAG_CLOSE, '</test>'], [HtmlTokenType.EOF, '']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should report missing name after </', () => {
|
||||
expect(tokenizeAndHumanizeErrors('</'))
|
||||
.toEqual([[HtmlTokenType.TAG_CLOSE, 'Unexpected character "EOF"', '0:2']]);
|
||||
expect(tokenizeAndHumanizeErrors('</')).toEqual([
|
||||
[HtmlTokenType.TAG_CLOSE, 'Unexpected character "EOF"', '0:2']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should report missing >', () => {
|
||||
expect(tokenizeAndHumanizeErrors('</test'))
|
||||
.toEqual([[HtmlTokenType.TAG_CLOSE, 'Unexpected character "EOF"', '0:6']]);
|
||||
expect(tokenizeAndHumanizeErrors('</test')).toEqual([
|
||||
[HtmlTokenType.TAG_CLOSE, 'Unexpected character "EOF"', '0:6']
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('entities', () => {
|
||||
it('should parse named entities', () => {
|
||||
expect(tokenizeAndHumanizeParts('a&b'))
|
||||
.toEqual([[HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF]]);
|
||||
expect(tokenizeAndHumanizeParts('a&b')).toEqual([
|
||||
[HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse hexadecimal entities', () => {
|
||||
expect(tokenizeAndHumanizeParts('AA'))
|
||||
.toEqual([[HtmlTokenType.TEXT, 'AA'], [HtmlTokenType.EOF]]);
|
||||
expect(tokenizeAndHumanizeParts('AA')).toEqual([
|
||||
[HtmlTokenType.TEXT, 'AA'], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse decimal entities', () => {
|
||||
expect(tokenizeAndHumanizeParts('A'))
|
||||
.toEqual([[HtmlTokenType.TEXT, 'A'], [HtmlTokenType.EOF]]);
|
||||
expect(tokenizeAndHumanizeParts('A')).toEqual([
|
||||
[HtmlTokenType.TEXT, 'A'], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should store the locations', () => {
|
||||
expect(tokenizeAndHumanizeSourceSpans('a&b'))
|
||||
.toEqual([[HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF, '']]);
|
||||
expect(tokenizeAndHumanizeSourceSpans('a&b')).toEqual([
|
||||
[HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF, '']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should report malformed/unknown entities', () => {
|
||||
expect(tokenizeAndHumanizeErrors('&tbo;'))
|
||||
.toEqual([
|
||||
[
|
||||
HtmlTokenType.TEXT,
|
||||
'Unknown entity "tbo" - use the "&#<decimal>;" or "&#x<hex>;" syntax',
|
||||
'0:0'
|
||||
]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeErrors('&#asdf;'))
|
||||
.toEqual([[HtmlTokenType.TEXT, 'Unexpected character "s"', '0:3']]);
|
||||
expect(tokenizeAndHumanizeErrors('
sdf;'))
|
||||
.toEqual([[HtmlTokenType.TEXT, 'Unexpected character "s"', '0:4']]);
|
||||
expect(tokenizeAndHumanizeErrors('&tbo;')).toEqual([[
|
||||
HtmlTokenType.TEXT,
|
||||
'Unknown entity "tbo" - use the "&#<decimal>;" or "&#x<hex>;" syntax', '0:0'
|
||||
]]);
|
||||
expect(tokenizeAndHumanizeErrors('&#asdf;')).toEqual([
|
||||
[HtmlTokenType.TEXT, 'Unexpected character "s"', '0:3']
|
||||
]);
|
||||
expect(tokenizeAndHumanizeErrors('
sdf;')).toEqual([
|
||||
[HtmlTokenType.TEXT, 'Unexpected character "s"', '0:4']
|
||||
]);
|
||||
|
||||
expect(tokenizeAndHumanizeErrors('઼'))
|
||||
.toEqual([[HtmlTokenType.TEXT, 'Unexpected character "EOF"', '0:6']]);
|
||||
expect(tokenizeAndHumanizeErrors('઼')).toEqual([
|
||||
[HtmlTokenType.TEXT, 'Unexpected character "EOF"', '0:6']
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('regular text', () => {
|
||||
it('should parse text', () => {
|
||||
expect(tokenizeAndHumanizeParts('a'))
|
||||
.toEqual([[HtmlTokenType.TEXT, 'a'], [HtmlTokenType.EOF]]);
|
||||
expect(tokenizeAndHumanizeParts('a')).toEqual([
|
||||
[HtmlTokenType.TEXT, 'a'], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should handle CR & LF', () => {
|
||||
expect(tokenizeAndHumanizeParts('t\ne\rs\r\nt'))
|
||||
.toEqual([[HtmlTokenType.TEXT, 't\ne\ns\nt'], [HtmlTokenType.EOF]]);
|
||||
expect(tokenizeAndHumanizeParts('t\ne\rs\r\nt')).toEqual([
|
||||
[HtmlTokenType.TEXT, 't\ne\ns\nt'], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse entities', () => {
|
||||
expect(tokenizeAndHumanizeParts('a&b'))
|
||||
.toEqual([[HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF]]);
|
||||
expect(tokenizeAndHumanizeParts('a&b')).toEqual([
|
||||
[HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse text starting with "&"', () => {
|
||||
expect(tokenizeAndHumanizeParts('a && b &'))
|
||||
.toEqual([[HtmlTokenType.TEXT, 'a && b &'], [HtmlTokenType.EOF]]);
|
||||
expect(tokenizeAndHumanizeParts('a && b &')).toEqual([
|
||||
[HtmlTokenType.TEXT, 'a && b &'], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should store the locations', () => {
|
||||
expect(tokenizeAndHumanizeSourceSpans('a'))
|
||||
.toEqual([[HtmlTokenType.TEXT, 'a'], [HtmlTokenType.EOF, '']]);
|
||||
expect(tokenizeAndHumanizeSourceSpans('a')).toEqual([
|
||||
[HtmlTokenType.TEXT, 'a'], [HtmlTokenType.EOF, '']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should allow "<" in text nodes', () => {
|
||||
expect(tokenizeAndHumanizeParts('{{ a < b ? c : d }}'))
|
||||
.toEqual([[HtmlTokenType.TEXT, '{{ a < b ? c : d }}'], [HtmlTokenType.EOF]]);
|
||||
expect(tokenizeAndHumanizeParts('{{ a < b ? c : d }}')).toEqual([
|
||||
[HtmlTokenType.TEXT, '{{ a < b ? c : d }}'], [HtmlTokenType.EOF]
|
||||
]);
|
||||
|
||||
expect(tokenizeAndHumanizeSourceSpans('<p>a<b</p>'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '<p'],
|
||||
[HtmlTokenType.TAG_OPEN_END, '>'],
|
||||
[HtmlTokenType.TEXT, 'a<b'],
|
||||
[HtmlTokenType.TAG_CLOSE, '</p>'],
|
||||
[HtmlTokenType.EOF, ''],
|
||||
]);
|
||||
expect(tokenizeAndHumanizeSourceSpans('<p>a<b</p>')).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '<p'],
|
||||
[HtmlTokenType.TAG_OPEN_END, '>'],
|
||||
[HtmlTokenType.TEXT, 'a<b'],
|
||||
[HtmlTokenType.TAG_CLOSE, '</p>'],
|
||||
[HtmlTokenType.EOF, ''],
|
||||
]);
|
||||
|
||||
expect(tokenizeAndHumanizeParts('< a>'))
|
||||
.toEqual([[HtmlTokenType.TEXT, '< a>'], [HtmlTokenType.EOF]]);
|
||||
expect(tokenizeAndHumanizeParts('< a>')).toEqual([
|
||||
[HtmlTokenType.TEXT, '< a>'], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
// TODO(vicb): make the lexer aware of Angular expressions
|
||||
// see https://github.com/angular/angular/issues/5679
|
||||
it('should parse valid start tag in interpolation', () => {
|
||||
expect(tokenizeAndHumanizeParts('{{ a <b && c > d }}'))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TEXT, '{{ a '],
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'b'],
|
||||
[HtmlTokenType.ATTR_NAME, null, '&&'],
|
||||
[HtmlTokenType.ATTR_NAME, null, 'c'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.TEXT, ' d }}'],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts('{{ a <b && c > d }}')).toEqual([
|
||||
[HtmlTokenType.TEXT, '{{ a '], [HtmlTokenType.TAG_OPEN_START, null, 'b'],
|
||||
[HtmlTokenType.ATTR_NAME, null, '&&'], [HtmlTokenType.ATTR_NAME, null, 'c'],
|
||||
[HtmlTokenType.TAG_OPEN_END], [HtmlTokenType.TEXT, ' d }}'], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('raw text', () => {
|
||||
it('should parse text', () => {
|
||||
expect(tokenizeAndHumanizeParts(`<script>t\ne\rs\r\nt</script>`))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'script'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.RAW_TEXT, 't\ne\ns\nt'],
|
||||
[HtmlTokenType.TAG_CLOSE, null, 'script'],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts(`<script>t\ne\rs\r\nt</script>`)).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'script'], [HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.RAW_TEXT, 't\ne\ns\nt'], [HtmlTokenType.TAG_CLOSE, null, 'script'],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should not detect entities', () => {
|
||||
expect(tokenizeAndHumanizeParts(`<script>&</SCRIPT>`))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'script'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.RAW_TEXT, '&'],
|
||||
[HtmlTokenType.TAG_CLOSE, null, 'script'],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts(`<script>&</SCRIPT>`)).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'script'], [HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.RAW_TEXT, '&'], [HtmlTokenType.TAG_CLOSE, null, 'script'],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should ignore other opening tags', () => {
|
||||
expect(tokenizeAndHumanizeParts(`<script>a<div></script>`))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'script'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.RAW_TEXT, 'a<div>'],
|
||||
[HtmlTokenType.TAG_CLOSE, null, 'script'],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts(`<script>a<div></script>`)).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'script'], [HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.RAW_TEXT, 'a<div>'], [HtmlTokenType.TAG_CLOSE, null, 'script'],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should ignore other closing tags', () => {
|
||||
expect(tokenizeAndHumanizeParts(`<script>a</test></script>`))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'script'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.RAW_TEXT, 'a</test>'],
|
||||
[HtmlTokenType.TAG_CLOSE, null, 'script'],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts(`<script>a</test></script>`)).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'script'], [HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.RAW_TEXT, 'a</test>'], [HtmlTokenType.TAG_CLOSE, null, 'script'],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should store the locations', () => {
|
||||
expect(tokenizeAndHumanizeSourceSpans(`<script>a</script>`))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '<script'],
|
||||
[HtmlTokenType.TAG_OPEN_END, '>'],
|
||||
[HtmlTokenType.RAW_TEXT, 'a'],
|
||||
[HtmlTokenType.TAG_CLOSE, '</script>'],
|
||||
[HtmlTokenType.EOF, '']
|
||||
]);
|
||||
expect(tokenizeAndHumanizeSourceSpans(`<script>a</script>`)).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '<script'], [HtmlTokenType.TAG_OPEN_END, '>'],
|
||||
[HtmlTokenType.RAW_TEXT, 'a'], [HtmlTokenType.TAG_CLOSE, '</script>'],
|
||||
[HtmlTokenType.EOF, '']
|
||||
]);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('escapable raw text', () => {
|
||||
it('should parse text', () => {
|
||||
expect(tokenizeAndHumanizeParts(`<title>t\ne\rs\r\nt</title>`))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'title'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.ESCAPABLE_RAW_TEXT, 't\ne\ns\nt'],
|
||||
[HtmlTokenType.TAG_CLOSE, null, 'title'],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts(`<title>t\ne\rs\r\nt</title>`)).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'title'], [HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.ESCAPABLE_RAW_TEXT, 't\ne\ns\nt'],
|
||||
[HtmlTokenType.TAG_CLOSE, null, 'title'], [HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should detect entities', () => {
|
||||
expect(tokenizeAndHumanizeParts(`<title>&</title>`))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'title'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.ESCAPABLE_RAW_TEXT, '&'],
|
||||
[HtmlTokenType.TAG_CLOSE, null, 'title'],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts(`<title>&</title>`)).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'title'], [HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.ESCAPABLE_RAW_TEXT, '&'], [HtmlTokenType.TAG_CLOSE, null, 'title'],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should ignore other opening tags', () => {
|
||||
expect(tokenizeAndHumanizeParts(`<title>a<div></title>`))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'title'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a<div>'],
|
||||
[HtmlTokenType.TAG_CLOSE, null, 'title'],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts(`<title>a<div></title>`)).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'title'], [HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a<div>'], [HtmlTokenType.TAG_CLOSE, null, 'title'],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should ignore other closing tags', () => {
|
||||
expect(tokenizeAndHumanizeParts(`<title>a</test></title>`))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'title'],
|
||||
[HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a</test>'],
|
||||
[HtmlTokenType.TAG_CLOSE, null, 'title'],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
expect(tokenizeAndHumanizeParts(`<title>a</test></title>`)).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, null, 'title'], [HtmlTokenType.TAG_OPEN_END],
|
||||
[HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a</test>'], [HtmlTokenType.TAG_CLOSE, null, 'title'],
|
||||
[HtmlTokenType.EOF]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should store the locations', () => {
|
||||
expect(tokenizeAndHumanizeSourceSpans(`<title>a</title>`))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '<title'],
|
||||
[HtmlTokenType.TAG_OPEN_END, '>'],
|
||||
[HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a'],
|
||||
[HtmlTokenType.TAG_CLOSE, '</title>'],
|
||||
[HtmlTokenType.EOF, '']
|
||||
]);
|
||||
expect(tokenizeAndHumanizeSourceSpans(`<title>a</title>`)).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '<title'], [HtmlTokenType.TAG_OPEN_END, '>'],
|
||||
[HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a'], [HtmlTokenType.TAG_CLOSE, '</title>'],
|
||||
[HtmlTokenType.EOF, '']
|
||||
]);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('errors', () => {
|
||||
it('should include 2 lines of context in message', () => {
|
||||
let src = "111\n222\n333\nE\n444\n555\n666\n";
|
||||
let src = '111\n222\n333\nE\n444\n555\n666\n';
|
||||
let file = new ParseSourceFile(src, 'file://');
|
||||
let location = new ParseLocation(file, 12, 123, 456);
|
||||
let span = new ParseSourceSpan(location, location);
|
||||
@@ -590,14 +485,10 @@ export function main() {
|
||||
|
||||
describe('unicode characters', () => {
|
||||
it('should support unicode characters', () => {
|
||||
expect(tokenizeAndHumanizeSourceSpans(`<p>İ</p>`))
|
||||
.toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '<p'],
|
||||
[HtmlTokenType.TAG_OPEN_END, '>'],
|
||||
[HtmlTokenType.TEXT, 'İ'],
|
||||
[HtmlTokenType.TAG_CLOSE, '</p>'],
|
||||
[HtmlTokenType.EOF, '']
|
||||
]);
|
||||
expect(tokenizeAndHumanizeSourceSpans(`<p>İ</p>`)).toEqual([
|
||||
[HtmlTokenType.TAG_OPEN_START, '<p'], [HtmlTokenType.TAG_OPEN_END, '>'],
|
||||
[HtmlTokenType.TEXT, 'İ'], [HtmlTokenType.TAG_CLOSE, '</p>'], [HtmlTokenType.EOF, '']
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -626,15 +517,14 @@ function humanizeLineColumn(location: ParseLocation): string {
|
||||
}
|
||||
|
||||
function tokenizeAndHumanizeLineColumn(input: string): any[] {
|
||||
return tokenizeWithoutErrors(input)
|
||||
.map(token => [<any>token.type, humanizeLineColumn(token.sourceSpan.start)]);
|
||||
return tokenizeWithoutErrors(input).map(
|
||||
token => [<any>token.type, humanizeLineColumn(token.sourceSpan.start)]);
|
||||
}
|
||||
|
||||
function tokenizeAndHumanizeErrors(input: string): any[] {
|
||||
return tokenizeHtml(input, 'someUrl')
|
||||
.errors.map(tokenError => [
|
||||
<any>tokenError.tokenType,
|
||||
tokenError.msg,
|
||||
humanizeLineColumn(tokenError.span.start)
|
||||
]);
|
||||
.errors.map(
|
||||
tokenError =>
|
||||
[<any>tokenError.tokenType, tokenError.msg,
|
||||
humanizeLineColumn(tokenError.span.start)]);
|
||||
}
|
||||
|
||||
@@ -1,25 +1,8 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
|
||||
import {HtmlTokenType} from 'angular2/src/compiler/html_lexer';
|
||||
import {HtmlParser, HtmlParseTreeResult, HtmlTreeError} from 'angular2/src/compiler/html_parser';
|
||||
import {
|
||||
HtmlAst,
|
||||
HtmlAstVisitor,
|
||||
HtmlElementAst,
|
||||
HtmlAttrAst,
|
||||
HtmlTextAst,
|
||||
HtmlCommentAst,
|
||||
htmlVisitAll
|
||||
} from 'angular2/src/compiler/html_ast';
|
||||
import {HtmlAst, HtmlAstVisitor, HtmlElementAst, HtmlAttrAst, HtmlTextAst, HtmlCommentAst, htmlVisitAll} from 'angular2/src/compiler/html_ast';
|
||||
import {ParseError, ParseLocation} from 'angular2/src/compiler/parse_util';
|
||||
import {humanizeDom, humanizeDomSourceSpans, humanizeLineColumn} from './html_ast_spec_utils';
|
||||
|
||||
@@ -35,31 +18,36 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should parse text nodes inside regular elements', () => {
|
||||
expect(humanizeDom(parser.parse('<div>a</div>', 'TestComp')))
|
||||
.toEqual([[HtmlElementAst, 'div', 0], [HtmlTextAst, 'a', 1]]);
|
||||
expect(humanizeDom(parser.parse('<div>a</div>', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, 'div', 0], [HtmlTextAst, 'a', 1]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse text nodes inside template elements', () => {
|
||||
expect(humanizeDom(parser.parse('<template>a</template>', 'TestComp')))
|
||||
.toEqual([[HtmlElementAst, 'template', 0], [HtmlTextAst, 'a', 1]]);
|
||||
expect(humanizeDom(parser.parse('<template>a</template>', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, 'template', 0], [HtmlTextAst, 'a', 1]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse CDATA', () => {
|
||||
expect(humanizeDom(parser.parse('<![CDATA[text]]>', 'TestComp')))
|
||||
.toEqual([[HtmlTextAst, 'text', 0]]);
|
||||
expect(humanizeDom(parser.parse('<![CDATA[text]]>', 'TestComp'))).toEqual([
|
||||
[HtmlTextAst, 'text', 0]
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('elements', () => {
|
||||
it('should parse root level elements', () => {
|
||||
expect(humanizeDom(parser.parse('<div></div>', 'TestComp')))
|
||||
.toEqual([[HtmlElementAst, 'div', 0]]);
|
||||
expect(humanizeDom(parser.parse('<div></div>', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, 'div', 0]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse elements inside of regular elements', () => {
|
||||
expect(humanizeDom(parser.parse('<div><span></span></div>', 'TestComp')))
|
||||
.toEqual([[HtmlElementAst, 'div', 0], [HtmlElementAst, 'span', 1]]);
|
||||
expect(humanizeDom(parser.parse('<div><span></span></div>', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, 'div', 0], [HtmlElementAst, 'span', 1]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse elements inside of template elements', () => {
|
||||
@@ -90,24 +78,22 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should close void elements on text nodes', () => {
|
||||
expect(humanizeDom(parser.parse('<p>before<br>after</p>', 'TestComp')))
|
||||
.toEqual([
|
||||
[HtmlElementAst, 'p', 0],
|
||||
[HtmlTextAst, 'before', 1],
|
||||
[HtmlElementAst, 'br', 1],
|
||||
[HtmlTextAst, 'after', 1],
|
||||
]);
|
||||
expect(humanizeDom(parser.parse('<p>before<br>after</p>', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, 'p', 0],
|
||||
[HtmlTextAst, 'before', 1],
|
||||
[HtmlElementAst, 'br', 1],
|
||||
[HtmlTextAst, 'after', 1],
|
||||
]);
|
||||
});
|
||||
|
||||
it('should support optional end tags', () => {
|
||||
expect(humanizeDom(parser.parse('<div><p>1<p>2</div>', 'TestComp')))
|
||||
.toEqual([
|
||||
[HtmlElementAst, 'div', 0],
|
||||
[HtmlElementAst, 'p', 1],
|
||||
[HtmlTextAst, '1', 2],
|
||||
[HtmlElementAst, 'p', 1],
|
||||
[HtmlTextAst, '2', 2],
|
||||
]);
|
||||
expect(humanizeDom(parser.parse('<div><p>1<p>2</div>', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, 'div', 0],
|
||||
[HtmlElementAst, 'p', 1],
|
||||
[HtmlTextAst, '1', 2],
|
||||
[HtmlElementAst, 'p', 1],
|
||||
[HtmlTextAst, '2', 2],
|
||||
]);
|
||||
});
|
||||
|
||||
it('should support nested elements', () => {
|
||||
@@ -126,63 +112,59 @@ export function main() {
|
||||
'<table><thead><tr head></tr></thead><tr noparent></tr><tbody><tr body></tr></tbody><tfoot><tr foot></tr></tfoot></table>',
|
||||
'TestComp')))
|
||||
.toEqual([
|
||||
[HtmlElementAst, 'table', 0],
|
||||
[HtmlElementAst, 'thead', 1],
|
||||
[HtmlElementAst, 'tr', 2],
|
||||
[HtmlAttrAst, 'head', ''],
|
||||
[HtmlElementAst, 'tbody', 1],
|
||||
[HtmlElementAst, 'tr', 2],
|
||||
[HtmlAttrAst, 'noparent', ''],
|
||||
[HtmlElementAst, 'tbody', 1],
|
||||
[HtmlElementAst, 'tr', 2],
|
||||
[HtmlAttrAst, 'body', ''],
|
||||
[HtmlElementAst, 'tfoot', 1],
|
||||
[HtmlElementAst, 'tr', 2],
|
||||
[HtmlElementAst, 'table', 0], [HtmlElementAst, 'thead', 1],
|
||||
[HtmlElementAst, 'tr', 2], [HtmlAttrAst, 'head', ''], [HtmlElementAst, 'tbody', 1],
|
||||
[HtmlElementAst, 'tr', 2], [HtmlAttrAst, 'noparent', ''],
|
||||
[HtmlElementAst, 'tbody', 1], [HtmlElementAst, 'tr', 2], [HtmlAttrAst, 'body', ''],
|
||||
[HtmlElementAst, 'tfoot', 1], [HtmlElementAst, 'tr', 2],
|
||||
[HtmlAttrAst, 'foot', '']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should not add the requiredParent when the parent is a template', () => {
|
||||
expect(humanizeDom(parser.parse('<template><tr></tr></template>', 'TestComp')))
|
||||
.toEqual([
|
||||
[HtmlElementAst, 'template', 0],
|
||||
[HtmlElementAst, 'tr', 1],
|
||||
]);
|
||||
expect(humanizeDom(parser.parse('<template><tr></tr></template>', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, 'template', 0],
|
||||
[HtmlElementAst, 'tr', 1],
|
||||
]);
|
||||
});
|
||||
|
||||
it('should support explicit mamespace', () => {
|
||||
expect(humanizeDom(parser.parse('<myns:div></myns:div>', 'TestComp')))
|
||||
.toEqual([[HtmlElementAst, '@myns:div', 0]]);
|
||||
expect(humanizeDom(parser.parse('<myns:div></myns:div>', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, '@myns:div', 0]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should support implicit mamespace', () => {
|
||||
expect(humanizeDom(parser.parse('<svg></svg>', 'TestComp')))
|
||||
.toEqual([[HtmlElementAst, '@svg:svg', 0]]);
|
||||
expect(humanizeDom(parser.parse('<svg></svg>', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, '@svg:svg', 0]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should propagate the namespace', () => {
|
||||
expect(humanizeDom(parser.parse('<myns:div><p></p></myns:div>', 'TestComp')))
|
||||
.toEqual([[HtmlElementAst, '@myns:div', 0], [HtmlElementAst, '@myns:p', 1]]);
|
||||
expect(humanizeDom(parser.parse('<myns:div><p></p></myns:div>', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, '@myns:div', 0], [HtmlElementAst, '@myns:p', 1]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should match closing tags case sensitive', () => {
|
||||
let errors = parser.parse('<DiV><P></p></dIv>', 'TestComp').errors;
|
||||
expect(errors.length).toEqual(2);
|
||||
expect(humanizeErrors(errors))
|
||||
.toEqual([
|
||||
['p', 'Unexpected closing tag "p"', '0:8'],
|
||||
['dIv', 'Unexpected closing tag "dIv"', '0:12'],
|
||||
]);
|
||||
expect(humanizeErrors(errors)).toEqual([
|
||||
['p', 'Unexpected closing tag "p"', '0:8'],
|
||||
['dIv', 'Unexpected closing tag "dIv"', '0:12'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('should support self closing void elements', () => {
|
||||
expect(humanizeDom(parser.parse('<input />', 'TestComp')))
|
||||
.toEqual([[HtmlElementAst, 'input', 0]]);
|
||||
expect(humanizeDom(parser.parse('<input />', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, 'input', 0]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should support self closing foreign elements', () => {
|
||||
expect(humanizeDom(parser.parse('<math />', 'TestComp')))
|
||||
.toEqual([[HtmlElementAst, '@math:math', 0]]);
|
||||
expect(humanizeDom(parser.parse('<math />', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, '@math:math', 0]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should ignore LF immediately after textarea, pre and listing', () => {
|
||||
@@ -204,39 +186,43 @@ export function main() {
|
||||
|
||||
describe('attributes', () => {
|
||||
it('should parse attributes on regular elements case sensitive', () => {
|
||||
expect(humanizeDom(parser.parse('<div kEy="v" key2=v2></div>', 'TestComp')))
|
||||
.toEqual([
|
||||
[HtmlElementAst, 'div', 0],
|
||||
[HtmlAttrAst, 'kEy', 'v'],
|
||||
[HtmlAttrAst, 'key2', 'v2'],
|
||||
]);
|
||||
expect(humanizeDom(parser.parse('<div kEy="v" key2=v2></div>', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, 'div', 0],
|
||||
[HtmlAttrAst, 'kEy', 'v'],
|
||||
[HtmlAttrAst, 'key2', 'v2'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse attributes without values', () => {
|
||||
expect(humanizeDom(parser.parse('<div k></div>', 'TestComp')))
|
||||
.toEqual([[HtmlElementAst, 'div', 0], [HtmlAttrAst, 'k', '']]);
|
||||
expect(humanizeDom(parser.parse('<div k></div>', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, 'div', 0], [HtmlAttrAst, 'k', '']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse attributes on svg elements case sensitive', () => {
|
||||
expect(humanizeDom(parser.parse('<svg viewBox="0"></svg>', 'TestComp')))
|
||||
.toEqual([[HtmlElementAst, '@svg:svg', 0], [HtmlAttrAst, 'viewBox', '0']]);
|
||||
expect(humanizeDom(parser.parse('<svg viewBox="0"></svg>', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, '@svg:svg', 0], [HtmlAttrAst, 'viewBox', '0']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse attributes on template elements', () => {
|
||||
expect(humanizeDom(parser.parse('<template k="v"></template>', 'TestComp')))
|
||||
.toEqual([[HtmlElementAst, 'template', 0], [HtmlAttrAst, 'k', 'v']]);
|
||||
expect(humanizeDom(parser.parse('<template k="v"></template>', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, 'template', 0], [HtmlAttrAst, 'k', 'v']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should support mamespace', () => {
|
||||
expect(humanizeDom(parser.parse('<svg:use xlink:href="Port" />', 'TestComp')))
|
||||
.toEqual([[HtmlElementAst, '@svg:use', 0], [HtmlAttrAst, '@xlink:href', 'Port']]);
|
||||
expect(humanizeDom(parser.parse('<svg:use xlink:href="Port" />', 'TestComp'))).toEqual([
|
||||
[HtmlElementAst, '@svg:use', 0], [HtmlAttrAst, '@xlink:href', 'Port']
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('comments', () => {
|
||||
it('should preserve comments', () => {
|
||||
expect(humanizeDom(parser.parse('<!-- comment --><div></div>', 'TestComp')))
|
||||
.toEqual([[HtmlCommentAst, 'comment', 0], [HtmlElementAst, 'div', 0]]);
|
||||
expect(humanizeDom(parser.parse('<!-- comment --><div></div>', 'TestComp'))).toEqual([
|
||||
[HtmlCommentAst, 'comment', 0], [HtmlElementAst, 'div', 0]
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -275,34 +261,34 @@ export function main() {
|
||||
it('should report closing tag for void elements', () => {
|
||||
let errors = parser.parse('<input></input>', 'TestComp').errors;
|
||||
expect(errors.length).toEqual(1);
|
||||
expect(humanizeErrors(errors))
|
||||
.toEqual([['input', 'Void elements do not have end tags "input"', '0:7']]);
|
||||
expect(humanizeErrors(errors)).toEqual([
|
||||
['input', 'Void elements do not have end tags "input"', '0:7']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should report self closing html element', () => {
|
||||
let errors = parser.parse('<p />', 'TestComp').errors;
|
||||
expect(errors.length).toEqual(1);
|
||||
expect(humanizeErrors(errors))
|
||||
.toEqual([['p', 'Only void and foreign elements can be self closed "p"', '0:0']]);
|
||||
expect(humanizeErrors(errors)).toEqual([
|
||||
['p', 'Only void and foreign elements can be self closed "p"', '0:0']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should report self closing custom element', () => {
|
||||
let errors = parser.parse('<my-cmp />', 'TestComp').errors;
|
||||
expect(errors.length).toEqual(1);
|
||||
expect(humanizeErrors(errors))
|
||||
.toEqual([
|
||||
['my-cmp', 'Only void and foreign elements can be self closed "my-cmp"', '0:0']
|
||||
]);
|
||||
expect(humanizeErrors(errors)).toEqual([
|
||||
['my-cmp', 'Only void and foreign elements can be self closed "my-cmp"', '0:0']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should also report lexer errors', () => {
|
||||
let errors = parser.parse('<!-err--><div></p></div>', 'TestComp').errors;
|
||||
expect(errors.length).toEqual(2);
|
||||
expect(humanizeErrors(errors))
|
||||
.toEqual([
|
||||
[HtmlTokenType.COMMENT_START, 'Unexpected character "e"', '0:3'],
|
||||
['p', 'Unexpected closing tag "p"', '0:14']
|
||||
]);
|
||||
expect(humanizeErrors(errors)).toEqual([
|
||||
[HtmlTokenType.COMMENT_START, 'Unexpected character "e"', '0:3'],
|
||||
['p', 'Unexpected closing tag "p"', '0:14']
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,26 +1,6 @@
|
||||
import {
|
||||
TestComponentBuilder,
|
||||
AsyncTestCompleter,
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
beforeEachProviders,
|
||||
inject
|
||||
} from 'angular2/testing_internal';
|
||||
import {TestComponentBuilder, AsyncTestCompleter, ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, beforeEachProviders, inject} from 'angular2/testing_internal';
|
||||
|
||||
import {
|
||||
HtmlAst,
|
||||
HtmlAstVisitor,
|
||||
HtmlElementAst,
|
||||
HtmlAttrAst,
|
||||
HtmlTextAst,
|
||||
htmlVisitAll
|
||||
} from 'angular2/src/compiler/html_ast';
|
||||
import {HtmlAst, HtmlAstVisitor, HtmlElementAst, HtmlAttrAst, HtmlTextAst, htmlVisitAll} from 'angular2/src/compiler/html_ast';
|
||||
|
||||
import {LegacyHtmlAstTransformer} from 'angular2/src/compiler/legacy_template';
|
||||
|
||||
|
||||
@@ -1,17 +1,4 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
xdescribe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
AsyncTestCompleter,
|
||||
inject,
|
||||
beforeEachProviders
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal';
|
||||
|
||||
import {Component, provide} from 'angular2/core';
|
||||
import {PromiseWrapper} from 'angular2/src/facade/async';
|
||||
@@ -38,11 +25,10 @@ export function main() {
|
||||
|
||||
it('compileInHost should compile the template via TemplateCompiler',
|
||||
inject([AsyncTestCompleter], (async) => {
|
||||
compiler.compileInHost(SomeComponent)
|
||||
.then((hostViewFactoryRef) => {
|
||||
expect(hostViewFactoryRef.internalHostViewFactory).toBe(someHostViewFactory);
|
||||
async.done();
|
||||
});
|
||||
compiler.compileInHost(SomeComponent).then((hostViewFactoryRef) => {
|
||||
expect(hostViewFactoryRef.internalHostViewFactory).toBe(someHostViewFactory);
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should clear the cache', () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {Component} from 'angular2/core';
|
||||
|
||||
@Component({styles:<any>('foo'), template: ''})
|
||||
@Component({styles: <any>('foo'), template: ''})
|
||||
export class MalformedStylesComponent {
|
||||
}
|
||||
|
||||
@@ -1,37 +1,9 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
xdescribe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
AsyncTestCompleter,
|
||||
inject,
|
||||
beforeEachProviders
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal';
|
||||
|
||||
import {stringify} from 'angular2/src/facade/lang';
|
||||
import {RuntimeMetadataResolver} from 'angular2/src/compiler/runtime_metadata';
|
||||
import {LifecycleHooks, LIFECYCLE_HOOKS_VALUES} from 'angular2/src/core/linker/interfaces';
|
||||
import {
|
||||
Component,
|
||||
Directive,
|
||||
ViewEncapsulation,
|
||||
ChangeDetectionStrategy,
|
||||
OnChanges,
|
||||
OnInit,
|
||||
DoCheck,
|
||||
OnDestroy,
|
||||
AfterContentInit,
|
||||
AfterContentChecked,
|
||||
AfterViewInit,
|
||||
AfterViewChecked,
|
||||
SimpleChange,
|
||||
provide
|
||||
} from 'angular2/core';
|
||||
import {Component, Directive, ViewEncapsulation, ChangeDetectionStrategy, OnChanges, OnInit, DoCheck, OnDestroy, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, SimpleChange, provide} from 'angular2/core';
|
||||
|
||||
import {TEST_PROVIDERS} from './test_bindings';
|
||||
import {MODULE_SUFFIX} from 'angular2/src/compiler/util';
|
||||
@@ -93,7 +65,7 @@ export function main() {
|
||||
.toContain(resolver.getDirectiveMetadata(SomeDirective));
|
||||
}));
|
||||
|
||||
describe("platform directives", () => {
|
||||
describe('platform directives', () => {
|
||||
beforeEachProviders(
|
||||
() => [provide(PLATFORM_DIRECTIVES, {useValue: [ADirective], multi: true})]);
|
||||
|
||||
|
||||
@@ -1,14 +1,4 @@
|
||||
import {
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
xdescribe,
|
||||
describe,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit
|
||||
} from 'angular2/testing_internal';
|
||||
import {beforeEach, ddescribe, xdescribe, describe, expect, iit, inject, it, xit} from 'angular2/testing_internal';
|
||||
import {IS_DART} from 'angular2/src/facade/lang';
|
||||
|
||||
import {DomElementSchemaRegistry} from 'angular2/src/compiler/schema/dom_element_schema_registry';
|
||||
|
||||
@@ -2,8 +2,9 @@ import {ElementSchemaRegistry} from 'angular2/src/compiler/schema/element_schema
|
||||
import {isPresent} from 'angular2/src/facade/lang';
|
||||
|
||||
export class MockSchemaRegistry implements ElementSchemaRegistry {
|
||||
constructor(public existingProperties: {[key: string]: boolean},
|
||||
public attrPropMapping: {[key: string]: string}) {}
|
||||
constructor(
|
||||
public existingProperties: {[key: string]: boolean},
|
||||
public attrPropMapping: {[key: string]: string}) {}
|
||||
hasProperty(tagName: string, property: string): boolean {
|
||||
var result = this.existingProperties[property];
|
||||
return isPresent(result) ? result : true;
|
||||
|
||||
@@ -72,20 +72,20 @@ export function main() {
|
||||
expect(matched).toEqual([s1[0], 1, s2[0], 2]);
|
||||
|
||||
reset();
|
||||
expect(matcher.match(CssSelector.parse('[someAttr=someValue][someAttr2]')[0],
|
||||
selectableCollector))
|
||||
expect(matcher.match(
|
||||
CssSelector.parse('[someAttr=someValue][someAttr2]')[0], selectableCollector))
|
||||
.toEqual(true);
|
||||
expect(matched).toEqual([s1[0], 1, s2[0], 2]);
|
||||
|
||||
reset();
|
||||
expect(matcher.match(CssSelector.parse('[someAttr2][someAttr=someValue]')[0],
|
||||
selectableCollector))
|
||||
expect(matcher.match(
|
||||
CssSelector.parse('[someAttr2][someAttr=someValue]')[0], selectableCollector))
|
||||
.toEqual(true);
|
||||
expect(matched).toEqual([s1[0], 1, s2[0], 2]);
|
||||
|
||||
reset();
|
||||
expect(matcher.match(CssSelector.parse('[someAttr2=someValue][someAttr]')[0],
|
||||
selectableCollector))
|
||||
expect(matcher.match(
|
||||
CssSelector.parse('[someAttr2=someValue][someAttr]')[0], selectableCollector))
|
||||
.toEqual(true);
|
||||
expect(matched).toEqual([s1[0], 1, s2[0], 2]);
|
||||
});
|
||||
@@ -120,18 +120,20 @@ export function main() {
|
||||
it('should select by element name, class name and attribute name with value', () => {
|
||||
matcher.addSelectables(s1 = CssSelector.parse('someTag.someClass[someAttr=someValue]'), 1);
|
||||
|
||||
expect(matcher.match(CssSelector.parse('someOtherTag.someOtherClass[someOtherAttr]')[0],
|
||||
selectableCollector))
|
||||
expect(matcher.match(
|
||||
CssSelector.parse('someOtherTag.someOtherClass[someOtherAttr]')[0],
|
||||
selectableCollector))
|
||||
.toEqual(false);
|
||||
expect(matched).toEqual([]);
|
||||
|
||||
expect(matcher.match(CssSelector.parse('someTag.someOtherClass[someOtherAttr]')[0],
|
||||
selectableCollector))
|
||||
expect(
|
||||
matcher.match(
|
||||
CssSelector.parse('someTag.someOtherClass[someOtherAttr]')[0], selectableCollector))
|
||||
.toEqual(false);
|
||||
expect(matched).toEqual([]);
|
||||
|
||||
expect(matcher.match(CssSelector.parse('someTag.someClass[someOtherAttr]')[0],
|
||||
selectableCollector))
|
||||
expect(matcher.match(
|
||||
CssSelector.parse('someTag.someClass[someOtherAttr]')[0], selectableCollector))
|
||||
.toEqual(false);
|
||||
expect(matched).toEqual([]);
|
||||
|
||||
@@ -140,8 +142,9 @@ export function main() {
|
||||
.toEqual(false);
|
||||
expect(matched).toEqual([]);
|
||||
|
||||
expect(matcher.match(CssSelector.parse('someTag.someClass[someAttr=someValue]')[0],
|
||||
selectableCollector))
|
||||
expect(
|
||||
matcher.match(
|
||||
CssSelector.parse('someTag.someClass[someAttr=someValue]')[0], selectableCollector))
|
||||
.toEqual(true);
|
||||
expect(matched).toEqual([s1[0], 1]);
|
||||
});
|
||||
@@ -202,8 +205,8 @@ export function main() {
|
||||
matcher.addSelectables(s3 = CssSelector.parse(':not(.someClass)'), 3);
|
||||
matcher.addSelectables(s4 = CssSelector.parse(':not(.someOtherClass[someAttr])'), 4);
|
||||
|
||||
expect(matcher.match(CssSelector.parse('p[someOtherAttr].someOtherClass')[0],
|
||||
selectableCollector))
|
||||
expect(matcher.match(
|
||||
CssSelector.parse('p[someOtherAttr].someOtherClass')[0], selectableCollector))
|
||||
.toEqual(true);
|
||||
expect(matched).toEqual([s1[0], 1, s2[0], 2, s3[0], 3, s4[0], 4]);
|
||||
});
|
||||
@@ -297,7 +300,7 @@ export function main() {
|
||||
|
||||
it('should detect :not without truthy', () => {
|
||||
var cssSelector = CssSelector.parse(':not([attrname=attrvalue].someclass)')[0];
|
||||
expect(cssSelector.element).toEqual("*");
|
||||
expect(cssSelector.element).toEqual('*');
|
||||
|
||||
var notSelector = cssSelector.notSelectors[0];
|
||||
expect(notSelector.attrs).toEqual(['attrname', 'attrvalue']);
|
||||
@@ -307,13 +310,15 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should throw when nested :not', () => {
|
||||
expect(() => { CssSelector.parse('sometag:not(:not([attrname=attrvalue].someclass))')[0]; })
|
||||
.toThrowError('Nesting :not is not allowed in a selector');
|
||||
expect(() => {
|
||||
CssSelector.parse('sometag:not(:not([attrname=attrvalue].someclass))')[0];
|
||||
}).toThrowError('Nesting :not is not allowed in a selector');
|
||||
});
|
||||
|
||||
it('should throw when multiple selectors in :not', () => {
|
||||
expect(() => { CssSelector.parse('sometag:not(a,b)'); })
|
||||
.toThrowError('Multiple selectors in :not are not supported');
|
||||
expect(() => {
|
||||
CssSelector.parse('sometag:not(a,b)');
|
||||
}).toThrowError('Multiple selectors in :not are not supported');
|
||||
});
|
||||
|
||||
it('should detect lists of selectors', () => {
|
||||
|
||||
@@ -1,14 +1,4 @@
|
||||
import {
|
||||
describe,
|
||||
beforeEach,
|
||||
it,
|
||||
expect,
|
||||
ddescribe,
|
||||
iit,
|
||||
SpyObject,
|
||||
el,
|
||||
normalizeCSS
|
||||
} from 'angular2/testing_internal';
|
||||
import {describe, beforeEach, it, expect, ddescribe, iit, SpyObject, el, normalizeCSS} from 'angular2/testing_internal';
|
||||
import {ShadowCss, processRules, CssRule} from 'angular2/src/compiler/shadow_css';
|
||||
|
||||
import {RegExpWrapper, StringWrapper, isPresent} from 'angular2/src/facade/lang';
|
||||
@@ -106,7 +96,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should support polyfill-next-selector', () => {
|
||||
var css = s("polyfill-next-selector {content: 'x > y'} z {}", 'a');
|
||||
var css = s('polyfill-next-selector {content: \'x > y\'} z {}', 'a');
|
||||
expect(css).toEqual('x[a] > y[a]{}');
|
||||
|
||||
css = s('polyfill-next-selector {content: "x > y"} z {}', 'a');
|
||||
@@ -114,7 +104,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should support polyfill-unscoped-rule', () => {
|
||||
var css = s("polyfill-unscoped-rule {content: '#menu > .bar';color: blue;}", 'a');
|
||||
var css = s('polyfill-unscoped-rule {content: \'#menu > .bar\';color: blue;}', 'a');
|
||||
expect(StringWrapper.contains(css, '#menu > .bar {;color:blue;}')).toBeTruthy();
|
||||
|
||||
css = s('polyfill-unscoped-rule {content: "#menu > .bar";color: blue;}', 'a');
|
||||
@@ -122,15 +112,16 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should support multiple instances polyfill-unscoped-rule', () => {
|
||||
var css = s("polyfill-unscoped-rule {content: 'foo';color: blue;}" +
|
||||
"polyfill-unscoped-rule {content: 'bar';color: blue;}",
|
||||
'a');
|
||||
var css =
|
||||
s('polyfill-unscoped-rule {content: \'foo\';color: blue;}' +
|
||||
'polyfill-unscoped-rule {content: \'bar\';color: blue;}',
|
||||
'a');
|
||||
expect(StringWrapper.contains(css, 'foo {;color:blue;}')).toBeTruthy();
|
||||
expect(StringWrapper.contains(css, 'bar {;color:blue;}')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should support polyfill-rule', () => {
|
||||
var css = s("polyfill-rule {content: ':host.foo .bar';color: blue;}", 'a', 'a-host');
|
||||
var css = s('polyfill-rule {content: \':host.foo .bar\';color: blue;}', 'a', 'a-host');
|
||||
expect(css).toEqual('[a-host].foo .bar {;color:blue;}');
|
||||
|
||||
css = s('polyfill-rule {content: ":host.foo .bar";color:blue;}', 'a', 'a-host');
|
||||
@@ -199,26 +190,29 @@ export function main() {
|
||||
() => { expect(captureRules('a {b}')).toEqual([new CssRule('a', 'b')]); });
|
||||
|
||||
it('should capture css rules with nested rules', () => {
|
||||
expect(captureRules('a {b {c}} d {e}'))
|
||||
.toEqual([new CssRule('a', 'b {c}'), new CssRule('d', 'e')]);
|
||||
expect(captureRules('a {b {c}} d {e}')).toEqual([
|
||||
new CssRule('a', 'b {c}'), new CssRule('d', 'e')
|
||||
]);
|
||||
});
|
||||
|
||||
it('should capture multiple rules where some have no body', () => {
|
||||
expect(captureRules('@import a ; b {c}'))
|
||||
.toEqual([new CssRule('@import a', ''), new CssRule('b', 'c')]);
|
||||
expect(captureRules('@import a ; b {c}')).toEqual([
|
||||
new CssRule('@import a', ''), new CssRule('b', 'c')
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('modify rules', () => {
|
||||
it('should allow to change the selector while preserving whitespaces', () => {
|
||||
expect(processRules('@import a; b {c {d}} e {f}',
|
||||
(cssRule) => new CssRule(cssRule.selector + '2', cssRule.content)))
|
||||
expect(processRules(
|
||||
'@import a; b {c {d}} e {f}',
|
||||
(cssRule) => new CssRule(cssRule.selector + '2', cssRule.content)))
|
||||
.toEqual('@import a2; b2 {c {d}} e2 {f}');
|
||||
});
|
||||
|
||||
it('should allow to change the content', () => {
|
||||
expect(processRules('a {b}',
|
||||
(cssRule) => new CssRule(cssRule.selector, cssRule.content + '2')))
|
||||
expect(processRules(
|
||||
'a {b}', (cssRule) => new CssRule(cssRule.selector, cssRule.content + '2')))
|
||||
.toEqual('a {b2}');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,16 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
TestComponentBuilder
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit, TestComponentBuilder} from 'angular2/testing_internal';
|
||||
|
||||
import {SourceModule, moduleRef} from 'angular2/src/compiler/source_module';
|
||||
|
||||
|
||||
@@ -1,17 +1,4 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
xdescribe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
AsyncTestCompleter,
|
||||
inject,
|
||||
beforeEachProviders
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal';
|
||||
|
||||
import {StaticReflector, StaticReflectorHost} from 'angular2/src/compiler/static_reflector';
|
||||
|
||||
@@ -34,8 +21,8 @@ export function main() {
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
let NgFor = reflector.getStaticType('angular2/src/common/directives/ng_for', 'NgFor');
|
||||
let ViewContainerRef = reflector.getStaticType('angular2/src/core/linker/view_container_ref',
|
||||
'ViewContainerRef');
|
||||
let ViewContainerRef = reflector.getStaticType(
|
||||
'angular2/src/core/linker/view_container_ref', 'ViewContainerRef');
|
||||
let TemplateRef =
|
||||
reflector.getStaticType('angular2/src/core/linker/template_ref', 'TemplateRef');
|
||||
let IterableDiffers = reflector.getStaticType(
|
||||
@@ -44,8 +31,9 @@ export function main() {
|
||||
'angular2/src/core/change_detection/change_detector_ref', 'ChangeDetectorRef');
|
||||
|
||||
let parameters = reflector.parameters(NgFor);
|
||||
expect(parameters)
|
||||
.toEqual([ViewContainerRef, TemplateRef, IterableDiffers, ChangeDetectorRef]);
|
||||
expect(parameters).toEqual([
|
||||
ViewContainerRef, TemplateRef, IterableDiffers, ChangeDetectorRef
|
||||
]);
|
||||
});
|
||||
|
||||
it('should get annotations for HeroDetailComponent', () => {
|
||||
@@ -76,7 +64,7 @@ export function main() {
|
||||
|
||||
expect(reflector.simplify('', 1)).toBe(1);
|
||||
expect(reflector.simplify('', true)).toBe(true);
|
||||
expect(reflector.simplify('', "some value")).toBe("some value");
|
||||
expect(reflector.simplify('', 'some value')).toBe('some value');
|
||||
});
|
||||
|
||||
it('should simplify an array into a copy of the array', () => {
|
||||
@@ -96,196 +84,261 @@ export function main() {
|
||||
it('should simplify &&', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '&&', left: true, right: true}))).toBe(true);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '&&', left: true, right: false}))).toBe(false);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '&&', left: false, right: true}))).toBe(false);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '&&', left: false, right: false}))).toBe(false);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '&&', left: true, right: true})))
|
||||
.toBe(true);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '&&', left: true, right: false})))
|
||||
.toBe(false);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '&&', left: false, right: true})))
|
||||
.toBe(false);
|
||||
expect(reflector.simplify(
|
||||
'', ({__symbolic: 'binop', operator: '&&', left: false, right: false})))
|
||||
.toBe(false);
|
||||
});
|
||||
|
||||
it('should simplify ||', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '||', left: true, right: true}))).toBe(true);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '||', left: true, right: false}))).toBe(true);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '||', left: false, right: true}))).toBe(true);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '||', left: false, right: false}))).toBe(false);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '||', left: true, right: true})))
|
||||
.toBe(true);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '||', left: true, right: false})))
|
||||
.toBe(true);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '||', left: false, right: true})))
|
||||
.toBe(true);
|
||||
expect(reflector.simplify(
|
||||
'', ({__symbolic: 'binop', operator: '||', left: false, right: false})))
|
||||
.toBe(false);
|
||||
});
|
||||
|
||||
it('should simplify &', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '&', left: 0x22, right: 0x0F}))).toBe(0x22 & 0x0F);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '&', left: 0x22, right: 0xF0}))).toBe(0x22 & 0xF0);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '&', left: 0x22, right: 0x0F})))
|
||||
.toBe(0x22 & 0x0F);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '&', left: 0x22, right: 0xF0})))
|
||||
.toBe(0x22 & 0xF0);
|
||||
});
|
||||
|
||||
it('should simplify |', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '|', left: 0x22, right: 0x0F}))).toBe(0x22 | 0x0F);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '|', left: 0x22, right: 0xF0}))).toBe(0x22 | 0xF0);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '|', left: 0x22, right: 0x0F})))
|
||||
.toBe(0x22 | 0x0F);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '|', left: 0x22, right: 0xF0})))
|
||||
.toBe(0x22 | 0xF0);
|
||||
});
|
||||
|
||||
it('should simplify ^', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '|', left: 0x22, right: 0x0F}))).toBe(0x22 | 0x0F);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '|', left: 0x22, right: 0xF0}))).toBe(0x22 | 0xF0);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '|', left: 0x22, right: 0x0F})))
|
||||
.toBe(0x22 | 0x0F);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '|', left: 0x22, right: 0xF0})))
|
||||
.toBe(0x22 | 0xF0);
|
||||
});
|
||||
|
||||
it('should simplify ==', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '==', left: 0x22, right: 0x22}))).toBe(0x22 == 0x22);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '==', left: 0x22, right: 0xF0}))).toBe(0x22 == 0xF0);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '==', left: 0x22, right: 0x22})))
|
||||
.toBe(0x22 == 0x22);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '==', left: 0x22, right: 0xF0})))
|
||||
.toBe(0x22 == 0xF0);
|
||||
});
|
||||
|
||||
it('should simplify !=', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '!=', left: 0x22, right: 0x22}))).toBe(0x22 != 0x22);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '!=', left: 0x22, right: 0xF0}))).toBe(0x22 != 0xF0);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '!=', left: 0x22, right: 0x22})))
|
||||
.toBe(0x22 != 0x22);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '!=', left: 0x22, right: 0xF0})))
|
||||
.toBe(0x22 != 0xF0);
|
||||
});
|
||||
|
||||
it('should simplify ===', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '===', left: 0x22, right: 0x22}))).toBe(0x22 === 0x22);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '===', left: 0x22, right: 0xF0}))).toBe(0x22 === 0xF0);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '===', left: 0x22, right: 0x22})))
|
||||
.toBe(0x22 === 0x22);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '===', left: 0x22, right: 0xF0})))
|
||||
.toBe(0x22 === 0xF0);
|
||||
});
|
||||
|
||||
it('should simplify !==', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '!==', left: 0x22, right: 0x22}))).toBe(0x22 !== 0x22);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '!==', left: 0x22, right: 0xF0}))).toBe(0x22 !== 0xF0);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '!==', left: 0x22, right: 0x22})))
|
||||
.toBe(0x22 !== 0x22);
|
||||
expect(
|
||||
reflector.simplify('', ({__symbolic: 'binop', operator: '!==', left: 0x22, right: 0xF0})))
|
||||
.toBe(0x22 !== 0xF0);
|
||||
});
|
||||
|
||||
it('should simplify >', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '>', left: 1, right: 1}))).toBe(1 > 1);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '>', left: 1, right: 0}))).toBe(1 > 0);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '>', left: 0, right: 1}))).toBe(0 > 1);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '>', left: 1, right: 1})))
|
||||
.toBe(1 > 1);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '>', left: 1, right: 0})))
|
||||
.toBe(1 > 0);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '>', left: 0, right: 1})))
|
||||
.toBe(0 > 1);
|
||||
});
|
||||
|
||||
it('should simplify >=', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '>=', left: 1, right: 1}))).toBe(1 >= 1);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '>=', left: 1, right: 0}))).toBe(1 >= 0);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '>=', left: 0, right: 1}))).toBe(0 >= 1);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '>=', left: 1, right: 1})))
|
||||
.toBe(1 >= 1);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '>=', left: 1, right: 0})))
|
||||
.toBe(1 >= 0);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '>=', left: 0, right: 1})))
|
||||
.toBe(0 >= 1);
|
||||
});
|
||||
|
||||
it('should simplify <=', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '<=', left: 1, right: 1}))).toBe(1 <= 1);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '<=', left: 1, right: 0}))).toBe(1 <= 0);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '<=', left: 0, right: 1}))).toBe(0 <= 1);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '<=', left: 1, right: 1})))
|
||||
.toBe(1 <= 1);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '<=', left: 1, right: 0})))
|
||||
.toBe(1 <= 0);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '<=', left: 0, right: 1})))
|
||||
.toBe(0 <= 1);
|
||||
});
|
||||
|
||||
it('should simplify <', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '<', left: 1, right: 1}))).toBe(1 < 1);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '<', left: 1, right: 0}))).toBe(1 < 0);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '<', left: 0, right: 1}))).toBe(0 < 1);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '<', left: 1, right: 1})))
|
||||
.toBe(1 < 1);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '<', left: 1, right: 0})))
|
||||
.toBe(1 < 0);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '<', left: 0, right: 1})))
|
||||
.toBe(0 < 1);
|
||||
});
|
||||
|
||||
it('should simplify <<', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '<<', left: 0x55, right: 2}))).toBe(0x55 << 2);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '<<', left: 0x55, right: 2})))
|
||||
.toBe(0x55 << 2);
|
||||
});
|
||||
|
||||
it('should simplify >>', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '>>', left: 0x55, right: 2}))).toBe(0x55 >> 2);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '>>', left: 0x55, right: 2})))
|
||||
.toBe(0x55 >> 2);
|
||||
});
|
||||
|
||||
it('should simplify +', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '+', left: 0x55, right: 2}))).toBe(0x55 + 2);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '+', left: 0x55, right: 2})))
|
||||
.toBe(0x55 + 2);
|
||||
});
|
||||
|
||||
it('should simplify -', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '-', left: 0x55, right: 2}))).toBe(0x55 - 2);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '-', left: 0x55, right: 2})))
|
||||
.toBe(0x55 - 2);
|
||||
});
|
||||
|
||||
it('should simplify *', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '*', left: 0x55, right: 2}))).toBe(0x55 * 2);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '*', left: 0x55, right: 2})))
|
||||
.toBe(0x55 * 2);
|
||||
});
|
||||
|
||||
it('should simplify /', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '/', left: 0x55, right: 2}))).toBe(0x55 / 2);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '/', left: 0x55, right: 2})))
|
||||
.toBe(0x55 / 2);
|
||||
});
|
||||
|
||||
it('should simplify %', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'binop', operator: '%', left: 0x55, right: 2}))).toBe(0x55 % 2);
|
||||
expect(reflector.simplify('', ({__symbolic: 'binop', operator: '%', left: 0x55, right: 2})))
|
||||
.toBe(0x55 % 2);
|
||||
});
|
||||
|
||||
it('should simplify prefix -', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'pre', operator: '-', operand: 2}))).toBe(-2);
|
||||
expect(reflector.simplify('', ({__symbolic: 'pre', operator: '-', operand: 2}))).toBe(-2);
|
||||
});
|
||||
|
||||
it('should simplify prefix ~', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'pre', operator: '~', operand: 2}))).toBe(~2);
|
||||
expect(reflector.simplify('', ({__symbolic: 'pre', operator: '~', operand: 2}))).toBe(~2);
|
||||
});
|
||||
|
||||
it('should simplify prefix !', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({ __symbolic: 'pre', operator: '!', operand: true}))).toBe(!true);
|
||||
expect(reflector.simplify('', ({ __symbolic: 'pre', operator: '!', operand: false}))).toBe(!false);
|
||||
expect(reflector.simplify('', ({__symbolic: 'pre', operator: '!', operand: true})))
|
||||
.toBe(!true);
|
||||
expect(reflector.simplify('', ({__symbolic: 'pre', operator: '!', operand: false})))
|
||||
.toBe(!false);
|
||||
});
|
||||
|
||||
it('should simpify an array index', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(reflector.simplify('', ({__symbolic: "index", expression: [1, 2, 3], index: 2})))
|
||||
expect(reflector.simplify('', ({__symbolic: 'index', expression: [1, 2, 3], index: 2})))
|
||||
.toBe(3);
|
||||
});
|
||||
|
||||
it('should simplify an object index', () => {
|
||||
let host = new MockReflectorHost();
|
||||
let reflector = new StaticReflector(host);
|
||||
let expr = {__symbolic: "select", expression: {a: 1, b: 2, c: 3}, member: "b"};
|
||||
let expr = {__symbolic: 'select', expression: {a: 1, b: 2, c: 3}, member: 'b'};
|
||||
expect(reflector.simplify('', expr)).toBe(2);
|
||||
});
|
||||
|
||||
@@ -294,8 +347,8 @@ export function main() {
|
||||
let reflector = new StaticReflector(host);
|
||||
|
||||
expect(
|
||||
reflector.simplify('./cases', ({__symbolic: "reference", module: "./extern", name: "s"})))
|
||||
.toEqual("s");
|
||||
reflector.simplify('./cases', ({__symbolic: 'reference', module: './extern', name: 's'})))
|
||||
.toEqual('s');
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -303,139 +356,101 @@ export function main() {
|
||||
class MockReflectorHost implements StaticReflectorHost {
|
||||
getMetadataFor(moduleId: string): any {
|
||||
return {
|
||||
'angular2/src/common/directives/ng_for':
|
||||
{
|
||||
"__symbolic": "module",
|
||||
"module": "./ng_for",
|
||||
"metadata":
|
||||
{
|
||||
"NgFor":
|
||||
{
|
||||
"__symbolic": "class",
|
||||
"decorators":
|
||||
[
|
||||
{
|
||||
"__symbolic": "call",
|
||||
"expression": {
|
||||
"__symbolic": "reference",
|
||||
"name": "Directive",
|
||||
"module": "../../core/metadata"
|
||||
},
|
||||
"arguments":
|
||||
[
|
||||
{
|
||||
"selector": "[ngFor][ngForOf]",
|
||||
"inputs": ["ngForTrackBy", "ngForOf", "ngForTemplate"]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"members":
|
||||
{
|
||||
"__ctor__": [
|
||||
{
|
||||
"__symbolic": "constructor",
|
||||
"parameters":
|
||||
[
|
||||
{
|
||||
"__symbolic": "reference",
|
||||
"module": "../../core/linker/view_container_ref",
|
||||
"name": "ViewContainerRef"
|
||||
},
|
||||
{
|
||||
"__symbolic": "reference",
|
||||
"module": "../../core/linker/template_ref",
|
||||
"name": "TemplateRef"
|
||||
},
|
||||
{
|
||||
"__symbolic": "reference",
|
||||
"module":
|
||||
"../../core/change_detection/differs/iterable_differs",
|
||||
"name": "IterableDiffers"
|
||||
},
|
||||
{
|
||||
"__symbolic": "reference",
|
||||
"module":
|
||||
"../../core/change_detection/change_detector_ref",
|
||||
"name": "ChangeDetectorRef"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'angular2/src/core/linker/view_container_ref':
|
||||
{
|
||||
"module": "./view_container_ref",
|
||||
"metadata": {"ViewContainerRef": {"__symbolic": "class"}}
|
||||
'angular2/src/common/directives/ng_for': {
|
||||
'__symbolic': 'module',
|
||||
'module': './ng_for',
|
||||
'metadata': {
|
||||
'NgFor': {
|
||||
'__symbolic': 'class',
|
||||
'decorators': [{
|
||||
'__symbolic': 'call',
|
||||
'expression':
|
||||
{'__symbolic': 'reference', 'name': 'Directive', 'module': '../../core/metadata'},
|
||||
'arguments': [{
|
||||
'selector': '[ngFor][ngForOf]',
|
||||
'inputs': ['ngForTrackBy', 'ngForOf', 'ngForTemplate']
|
||||
}]
|
||||
}],
|
||||
'members': {
|
||||
'__ctor__': [{
|
||||
'__symbolic': 'constructor',
|
||||
'parameters': [
|
||||
{
|
||||
'__symbolic': 'reference',
|
||||
'module': '../../core/linker/view_container_ref',
|
||||
'name': 'ViewContainerRef'
|
||||
},
|
||||
{
|
||||
'__symbolic': 'reference',
|
||||
'module': '../../core/linker/template_ref',
|
||||
'name': 'TemplateRef'
|
||||
},
|
||||
{
|
||||
'__symbolic': 'reference',
|
||||
'module': '../../core/change_detection/differs/iterable_differs',
|
||||
'name': 'IterableDiffers'
|
||||
},
|
||||
{
|
||||
'__symbolic': 'reference',
|
||||
'module': '../../core/change_detection/change_detector_ref',
|
||||
'name': 'ChangeDetectorRef'
|
||||
}
|
||||
]
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'angular2/src/core/linker/view_container_ref': {
|
||||
'module': './view_container_ref',
|
||||
'metadata': {'ViewContainerRef': {'__symbolic': 'class'}}
|
||||
},
|
||||
'angular2/src/core/linker/template_ref':
|
||||
{'module': './template_ref', 'metadata': {'TemplateRef': {'__symbolic': 'class'}}},
|
||||
'angular2/src/core/change_detection/differs/iterable_differs': {
|
||||
'module': './iterable_differs',
|
||||
'metadata': {'IterableDiffers': {'__symbolic': 'class'}}
|
||||
},
|
||||
'angular2/src/core/change_detection/change_detector_ref': {
|
||||
'module': './change_detector_ref',
|
||||
'metadata': {'ChangeDetectorRef': {'__symbolic': 'class'}}
|
||||
},
|
||||
'./app/hero-detail.component': {
|
||||
'__symbolic': 'module',
|
||||
'module': './hero-detail.component',
|
||||
'metadata': {
|
||||
'HeroDetailComponent': {
|
||||
'__symbolic': 'class',
|
||||
'decorators': [{
|
||||
'__symbolic': 'call',
|
||||
'expression': {
|
||||
'__symbolic': 'reference',
|
||||
'name': 'Component',
|
||||
'module': 'angular2/src/core/metadata'
|
||||
},
|
||||
'angular2/src/core/linker/template_ref':
|
||||
{"module": "./template_ref", "metadata": {"TemplateRef": {"__symbolic": "class"}}},
|
||||
'angular2/src/core/change_detection/differs/iterable_differs':
|
||||
{
|
||||
"module": "./iterable_differs",
|
||||
"metadata": {"IterableDiffers": {"__symbolic": "class"}}
|
||||
},
|
||||
'angular2/src/core/change_detection/change_detector_ref':
|
||||
{
|
||||
"module": "./change_detector_ref",
|
||||
"metadata": {"ChangeDetectorRef": {"__symbolic": "class"}}
|
||||
},
|
||||
'./app/hero-detail.component':
|
||||
{
|
||||
"__symbolic": "module",
|
||||
"module": "./hero-detail.component",
|
||||
"metadata":
|
||||
{
|
||||
"HeroDetailComponent":
|
||||
{
|
||||
"__symbolic": "class",
|
||||
"decorators":
|
||||
[
|
||||
{
|
||||
"__symbolic": "call",
|
||||
"expression": {
|
||||
"__symbolic": "reference",
|
||||
"name": "Component",
|
||||
"module": "angular2/src/core/metadata"
|
||||
},
|
||||
"arguments": [
|
||||
{
|
||||
"selector": "my-hero-detail",
|
||||
"template": "\n <div *ngIf=\"hero\">\n <h2>{{hero.name}} details!</h2>\n <div><label>id: </label>{{hero.id}}</div>\n <div>\n <label>name: </label>\n <input [(ngModel)]=\"hero.name\" placeholder=\"name\"/>\n </div>\n </div>\n"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"members":
|
||||
{
|
||||
"hero": [
|
||||
{
|
||||
"__symbolic": "property",
|
||||
"decorators":
|
||||
[
|
||||
{
|
||||
"__symbolic": "call",
|
||||
"expression":
|
||||
{
|
||||
"__symbolic": "reference",
|
||||
"name": "Input",
|
||||
"module": "angular2/src/core/metadata"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'./extern': {
|
||||
"__symbolic": "module", module: './extern', metadata: { s: "s" }
|
||||
}
|
||||
}
|
||||
[moduleId];
|
||||
'arguments': [{
|
||||
'selector': 'my-hero-detail',
|
||||
'template':
|
||||
'\n <div *ngIf="hero">\n <h2>{{hero.name}} details!</h2>\n <div><label>id: </label>{{hero.id}}</div>\n <div>\n <label>name: </label>\n <input [(ngModel)]="hero.name" placeholder="name"/>\n </div>\n </div>\n'
|
||||
}]
|
||||
}],
|
||||
'members': {
|
||||
'hero': [{
|
||||
'__symbolic': 'property',
|
||||
'decorators': [{
|
||||
'__symbolic': 'call',
|
||||
'expression': {
|
||||
'__symbolic': 'reference',
|
||||
'name': 'Input',
|
||||
'module': 'angular2/src/core/metadata'
|
||||
}
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'./extern': {'__symbolic': 'module', module: './extern', metadata: {s: 's'}}
|
||||
}[moduleId];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,38 +1,14 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
xdescribe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
AsyncTestCompleter,
|
||||
inject,
|
||||
beforeEachProviders
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal';
|
||||
import {provide} from 'angular2/src/core/di';
|
||||
import {SpyXHR} from './spies';
|
||||
import {XHR} from 'angular2/src/compiler/xhr';
|
||||
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
|
||||
|
||||
import {
|
||||
CONST_EXPR,
|
||||
isPresent,
|
||||
isBlank,
|
||||
StringWrapper,
|
||||
isArray,
|
||||
IS_DART
|
||||
} from 'angular2/src/facade/lang';
|
||||
import {CONST_EXPR, isPresent, isBlank, StringWrapper, isArray, IS_DART} from 'angular2/src/facade/lang';
|
||||
import {PromiseWrapper} from 'angular2/src/facade/async';
|
||||
import {evalModule} from './eval_module';
|
||||
import {StyleCompiler} from 'angular2/src/compiler/style_compiler';
|
||||
import {
|
||||
CompileDirectiveMetadata,
|
||||
CompileTemplateMetadata,
|
||||
CompileTypeMetadata
|
||||
} from 'angular2/src/compiler/directive_metadata';
|
||||
import {CompileDirectiveMetadata, CompileTemplateMetadata, CompileTypeMetadata} from 'angular2/src/compiler/directive_metadata';
|
||||
import {SourceExpression, SourceModule} from 'angular2/src/compiler/source_module';
|
||||
import {ViewEncapsulation} from 'angular2/src/core/metadata/view';
|
||||
import {TEST_PROVIDERS} from './test_bindings';
|
||||
@@ -76,8 +52,8 @@ export function main() {
|
||||
`a {color: green}@import ${IMPORT_REL_STYLESHEET_URL};`;
|
||||
});
|
||||
|
||||
function compile(styles: string[], styleAbsUrls: string[],
|
||||
encapsulation: ViewEncapsulation): Promise<string[]> {
|
||||
function compile(styles: string[], styleAbsUrls: string[], encapsulation: ViewEncapsulation):
|
||||
Promise<string[]> {
|
||||
// Note: Can't use MockXHR as the xhr is called recursively,
|
||||
// so we can't trigger flush.
|
||||
xhr.spy('get').andCallFake((url) => {
|
||||
@@ -96,11 +72,10 @@ export function main() {
|
||||
var encapsulation = ViewEncapsulation.None;
|
||||
|
||||
it('should compile plain css rules', inject([AsyncTestCompleter], (async) => {
|
||||
compile(['div {color: red}', 'span {color: blue}'], [], encapsulation)
|
||||
.then(styles => {
|
||||
expect(styles).toEqual(['div {color: red}', 'span {color: blue}']);
|
||||
async.done();
|
||||
});
|
||||
compile(['div {color: red}', 'span {color: blue}'], [], encapsulation).then(styles => {
|
||||
expect(styles).toEqual(['div {color: red}', 'span {color: blue}']);
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should allow to import rules', inject([AsyncTestCompleter], (async) => {
|
||||
@@ -114,8 +89,8 @@ export function main() {
|
||||
it('should allow to import rules transitively', inject([AsyncTestCompleter], (async) => {
|
||||
compile(['div {color: red}'], [IMPORT_ABS_STYLESHEET_URL_WITH_IMPORT], encapsulation)
|
||||
.then(styles => {
|
||||
expect(styles)
|
||||
.toEqual(['div {color: red}', ['a {color: green}', ['span {color: blue}']]]);
|
||||
expect(styles).toEqual(
|
||||
['div {color: red}', ['a {color: green}', ['span {color: blue}']]]);
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
@@ -147,8 +122,8 @@ export function main() {
|
||||
}));
|
||||
|
||||
it('should allow to import rules transitively', inject([AsyncTestCompleter], (async) => {
|
||||
compile(['div {\ncolor: red;\n}'], [IMPORT_ABS_STYLESHEET_URL_WITH_IMPORT],
|
||||
encapsulation)
|
||||
compile(
|
||||
['div {\ncolor: red;\n}'], [IMPORT_ABS_STYLESHEET_URL_WITH_IMPORT], encapsulation)
|
||||
.then(styles => {
|
||||
compareStyles(styles, [
|
||||
'div[_ngcontent-%COMP%] {\ncolor: red;\n}',
|
||||
@@ -163,10 +138,11 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should cache stylesheets for parallel requests', inject([AsyncTestCompleter], (async) => {
|
||||
PromiseWrapper.all([
|
||||
compile([], [IMPORT_ABS_STYLESHEET_URL], ViewEncapsulation.None),
|
||||
compile([], [IMPORT_ABS_STYLESHEET_URL], ViewEncapsulation.None)
|
||||
])
|
||||
PromiseWrapper
|
||||
.all([
|
||||
compile([], [IMPORT_ABS_STYLESHEET_URL], ViewEncapsulation.None),
|
||||
compile([], [IMPORT_ABS_STYLESHEET_URL], ViewEncapsulation.None)
|
||||
])
|
||||
.then((styleArrays) => {
|
||||
expect(styleArrays[0]).toEqual([['span {color: blue}']]);
|
||||
expect(styleArrays[1]).toEqual([['span {color: blue}']]);
|
||||
@@ -176,17 +152,16 @@ export function main() {
|
||||
}));
|
||||
|
||||
it('should cache stylesheets for serial requests', inject([AsyncTestCompleter], (async) => {
|
||||
compile([], [IMPORT_ABS_STYLESHEET_URL], ViewEncapsulation.None)
|
||||
.then((styles0) => {
|
||||
xhrUrlResults[IMPORT_ABS_STYLESHEET_URL] = 'span {color: black}';
|
||||
return compile([], [IMPORT_ABS_STYLESHEET_URL], ViewEncapsulation.None)
|
||||
.then((styles1) => {
|
||||
expect(styles0).toEqual([['span {color: blue}']]);
|
||||
expect(styles1).toEqual([['span {color: blue}']]);
|
||||
expect(xhrCount).toBe(1);
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
compile([], [IMPORT_ABS_STYLESHEET_URL], ViewEncapsulation.None).then((styles0) => {
|
||||
xhrUrlResults[IMPORT_ABS_STYLESHEET_URL] = 'span {color: black}';
|
||||
return compile([], [IMPORT_ABS_STYLESHEET_URL], ViewEncapsulation.None)
|
||||
.then((styles1) => {
|
||||
expect(styles0).toEqual([['span {color: blue}']]);
|
||||
expect(styles1).toEqual([['span {color: blue}']]);
|
||||
expect(xhrCount).toBe(1);
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
}));
|
||||
|
||||
it('should allow to clear the cache', inject([AsyncTestCompleter], (async) => {
|
||||
@@ -205,8 +180,8 @@ export function main() {
|
||||
});
|
||||
|
||||
describe('compileComponentCodeGen', () => {
|
||||
function compile(styles: string[], styleAbsUrls: string[],
|
||||
encapsulation: ViewEncapsulation): Promise<string[]> {
|
||||
function compile(styles: string[], styleAbsUrls: string[], encapsulation: ViewEncapsulation):
|
||||
Promise<string[]> {
|
||||
var sourceExpression = compiler.compileComponentCodeGen(new CompileTemplateMetadata(
|
||||
{styles: styles, styleUrls: styleAbsUrls, encapsulation: encapsulation}));
|
||||
var sourceWithImports = testableExpression(sourceExpression).getSourceWithImports();
|
||||
@@ -217,20 +192,18 @@ export function main() {
|
||||
var encapsulation = ViewEncapsulation.None;
|
||||
|
||||
it('should compile plain css rules', inject([AsyncTestCompleter], (async) => {
|
||||
compile(['div {color: red}', 'span {color: blue}'], [], encapsulation)
|
||||
.then(styles => {
|
||||
expect(styles).toEqual(['div {color: red}', 'span {color: blue}']);
|
||||
async.done();
|
||||
});
|
||||
compile(['div {color: red}', 'span {color: blue}'], [], encapsulation).then(styles => {
|
||||
expect(styles).toEqual(['div {color: red}', 'span {color: blue}']);
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should compile css rules with newlines and quotes',
|
||||
inject([AsyncTestCompleter], (async) => {
|
||||
compile(['div\n{"color": \'red\'}'], [], encapsulation)
|
||||
.then(styles => {
|
||||
expect(styles).toEqual(['div\n{"color": \'red\'}']);
|
||||
async.done();
|
||||
});
|
||||
compile(['div\n{"color": \'red\'}'], [], encapsulation).then(styles => {
|
||||
expect(styles).toEqual(['div\n{"color": \'red\'}']);
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should allow to import rules', inject([AsyncTestCompleter], (async) => {
|
||||
@@ -279,13 +252,12 @@ export function main() {
|
||||
}
|
||||
|
||||
it('should compile plain css rules', inject([AsyncTestCompleter], (async) => {
|
||||
compile('div {color: red;}')
|
||||
.then(stylesAndShimStyles => {
|
||||
var expected = [['div {color: red;}'], ['div[_ngcontent-%COMP%] {color: red;}']];
|
||||
compareStyles(stylesAndShimStyles[0], expected[0]);
|
||||
compareStyles(stylesAndShimStyles[1], expected[1]);
|
||||
async.done();
|
||||
});
|
||||
compile('div {color: red;}').then(stylesAndShimStyles => {
|
||||
var expected = [['div {color: red;}'], ['div[_ngcontent-%COMP%] {color: red;}']];
|
||||
compareStyles(stylesAndShimStyles[0], expected[0]);
|
||||
compareStyles(stylesAndShimStyles[1], expected[1]);
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should allow to import rules with relative paths',
|
||||
@@ -324,7 +296,7 @@ function testableModule(sourceModule: SourceModule): SourceModule {
|
||||
}
|
||||
|
||||
// Needed for Android browsers which add an extra space at the end of some lines
|
||||
function compareStyles(styles: Array<string | any[]>, expectedStyles: Array<string | any[]>) {
|
||||
function compareStyles(styles: Array<string|any[]>, expectedStyles: Array<string|any[]>) {
|
||||
expect(styles.length).toEqual(expectedStyles.length);
|
||||
for (var i = 0; i < styles.length; i++) {
|
||||
var style = styles[i];
|
||||
|
||||
@@ -38,8 +38,9 @@ export function main() {
|
||||
`;
|
||||
var styleWithImports = extractStyleUrls(urlResolver, 'http://ng.io', css);
|
||||
expect(styleWithImports.style.trim()).toEqual('');
|
||||
expect(styleWithImports.styleUrls)
|
||||
.toEqual(['http://ng.io/3.css', 'http://ng.io/4.css', 'http://ng.io/5.css']);
|
||||
expect(styleWithImports.styleUrls).toEqual([
|
||||
'http://ng.io/3.css', 'http://ng.io/4.css', 'http://ng.io/5.css'
|
||||
]);
|
||||
});
|
||||
|
||||
it('should extract "@import urls and keep rules in the same line', () => {
|
||||
@@ -56,8 +57,9 @@ export function main() {
|
||||
`;
|
||||
var styleWithImports = extractStyleUrls(urlResolver, 'http://ng.io', css);
|
||||
expect(styleWithImports.style.trim()).toEqual('');
|
||||
expect(styleWithImports.styleUrls)
|
||||
.toEqual(['http://ng.io/print1.css', 'http://ng.io/print2.css']);
|
||||
expect(styleWithImports.styleUrls).toEqual([
|
||||
'http://ng.io/print1.css', 'http://ng.io/print2.css'
|
||||
]);
|
||||
});
|
||||
|
||||
it('should leave absolute non-package @import urls intact', () => {
|
||||
|
||||
@@ -1,31 +1,10 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
xdescribe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
AsyncTestCompleter,
|
||||
inject,
|
||||
beforeEachProviders
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal';
|
||||
|
||||
import {PromiseWrapper} from 'angular2/src/facade/async';
|
||||
import {Type, isPresent, isBlank, stringify, isString, IS_DART} from 'angular2/src/facade/lang';
|
||||
import {
|
||||
MapWrapper,
|
||||
SetWrapper,
|
||||
ListWrapper,
|
||||
StringMapWrapper
|
||||
} from 'angular2/src/facade/collection';
|
||||
import {MapWrapper, SetWrapper, ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
|
||||
import {RuntimeMetadataResolver} from 'angular2/src/compiler/runtime_metadata';
|
||||
import {
|
||||
TemplateCompiler,
|
||||
NormalizedComponentWithViewDirectives
|
||||
} from 'angular2/src/compiler/template_compiler';
|
||||
import {TemplateCompiler, NormalizedComponentWithViewDirectives} from 'angular2/src/compiler/template_compiler';
|
||||
import {CompileDirectiveMetadata} from 'angular2/src/compiler/directive_metadata';
|
||||
import {evalModule} from './eval_module';
|
||||
import {SourceModule, moduleRef} from 'angular2/src/compiler/source_module';
|
||||
@@ -40,12 +19,7 @@ import {Locals, ChangeDetectorGenConfig} from 'angular2/src/core/change_detectio
|
||||
import {Component, Directive, provide, RenderComponentType} from 'angular2/core';
|
||||
|
||||
import {TEST_PROVIDERS} from './test_bindings';
|
||||
import {
|
||||
codeGenValueFn,
|
||||
codeGenFnHeader,
|
||||
codeGenExportVariable,
|
||||
MODULE_SUFFIX
|
||||
} from 'angular2/src/compiler/util';
|
||||
import {codeGenValueFn, codeGenFnHeader, codeGenExportVariable, MODULE_SUFFIX} from 'angular2/src/compiler/util';
|
||||
import {PipeTransform, WrappedValue, Injectable, Pipe} from 'angular2/core';
|
||||
|
||||
|
||||
@@ -68,11 +42,11 @@ export function main() {
|
||||
var runtimeMetadataResolver: RuntimeMetadataResolver;
|
||||
|
||||
beforeEachProviders(() => TEST_PROVIDERS);
|
||||
beforeEach(inject([TemplateCompiler, RuntimeMetadataResolver],
|
||||
(_compiler, _runtimeMetadataResolver) => {
|
||||
compiler = _compiler;
|
||||
runtimeMetadataResolver = _runtimeMetadataResolver;
|
||||
}));
|
||||
beforeEach(inject(
|
||||
[TemplateCompiler, RuntimeMetadataResolver], (_compiler, _runtimeMetadataResolver) => {
|
||||
compiler = _compiler;
|
||||
runtimeMetadataResolver = _runtimeMetadataResolver;
|
||||
}));
|
||||
|
||||
describe('compile templates', () => {
|
||||
|
||||
@@ -88,100 +62,96 @@ export function main() {
|
||||
}));
|
||||
|
||||
it('should compile host components', inject([AsyncTestCompleter], (async) => {
|
||||
compile([CompWithBindingsAndStylesAndPipes])
|
||||
.then((humanizedView) => {
|
||||
expect(humanizedView['styles']).toEqual([]);
|
||||
expect(humanizedView['elements']).toEqual(['<comp-a>']);
|
||||
expect(humanizedView['pipes']).toEqual({});
|
||||
expect(humanizedView['cd']).toEqual(['prop(title)=someHostValue']);
|
||||
async.done();
|
||||
});
|
||||
compile([CompWithBindingsAndStylesAndPipes]).then((humanizedView) => {
|
||||
expect(humanizedView['styles']).toEqual([]);
|
||||
expect(humanizedView['elements']).toEqual(['<comp-a>']);
|
||||
expect(humanizedView['pipes']).toEqual({});
|
||||
expect(humanizedView['cd']).toEqual(['prop(title)=someHostValue']);
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should compile nested components', inject([AsyncTestCompleter], (async) => {
|
||||
compile([CompWithBindingsAndStylesAndPipes])
|
||||
.then((humanizedView) => {
|
||||
var componentView = humanizedView['componentViews'][0];
|
||||
expect(componentView['styles']).toEqual(['div {color: red}']);
|
||||
expect(componentView['elements']).toEqual(['<a>']);
|
||||
expect(componentView['pipes']).toEqual({'uppercase': stringify(UpperCasePipe)});
|
||||
expect(componentView['cd']).toEqual(['prop(href)=SOMECTXVALUE']);
|
||||
compile([CompWithBindingsAndStylesAndPipes]).then((humanizedView) => {
|
||||
var componentView = humanizedView['componentViews'][0];
|
||||
expect(componentView['styles']).toEqual(['div {color: red}']);
|
||||
expect(componentView['elements']).toEqual(['<a>']);
|
||||
expect(componentView['pipes']).toEqual({'uppercase': stringify(UpperCasePipe)});
|
||||
expect(componentView['cd']).toEqual(['prop(href)=SOMECTXVALUE']);
|
||||
|
||||
async.done();
|
||||
});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should compile components at various nesting levels',
|
||||
inject([AsyncTestCompleter], (async) => {
|
||||
compile([CompWith2NestedComps, Comp1, Comp2])
|
||||
.then((humanizedView) => {
|
||||
expect(humanizedView['elements']).toEqual(['<comp-with-2nested>']);
|
||||
expect(humanizedView['componentViews'][0]['elements'])
|
||||
.toEqual(['<comp1>', '<comp2>']);
|
||||
expect(humanizedView['componentViews'][0]['componentViews'][0]['elements'])
|
||||
.toEqual(['<a>', '<comp2>']);
|
||||
expect(humanizedView['componentViews'][0]['componentViews'][1]['elements'])
|
||||
.toEqual(['<b>']);
|
||||
compile([CompWith2NestedComps, Comp1, Comp2]).then((humanizedView) => {
|
||||
expect(humanizedView['elements']).toEqual(['<comp-with-2nested>']);
|
||||
expect(humanizedView['componentViews'][0]['elements']).toEqual([
|
||||
'<comp1>', '<comp2>'
|
||||
]);
|
||||
expect(humanizedView['componentViews'][0]['componentViews'][0]['elements']).toEqual([
|
||||
'<a>', '<comp2>'
|
||||
]);
|
||||
expect(humanizedView['componentViews'][0]['componentViews'][1]['elements']).toEqual([
|
||||
'<b>'
|
||||
]);
|
||||
|
||||
async.done();
|
||||
});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should compile recursive components', inject([AsyncTestCompleter], (async) => {
|
||||
compile([TreeComp])
|
||||
.then((humanizedView) => {
|
||||
expect(humanizedView['elements']).toEqual(['<tree>']);
|
||||
expect(humanizedView['componentViews'][0]['embeddedViews'][0]['elements'])
|
||||
.toEqual(['<tree>']);
|
||||
expect(humanizedView['componentViews'][0]['embeddedViews'][0]['componentViews']
|
||||
[0]['embeddedViews'][0]['elements'])
|
||||
.toEqual(['<tree>']);
|
||||
compile([TreeComp]).then((humanizedView) => {
|
||||
expect(humanizedView['elements']).toEqual(['<tree>']);
|
||||
expect(humanizedView['componentViews'][0]['embeddedViews'][0]['elements']).toEqual([
|
||||
'<tree>'
|
||||
]);
|
||||
expect(humanizedView['componentViews'][0]['embeddedViews'][0]['componentViews'][0]
|
||||
['embeddedViews'][0]['elements'])
|
||||
.toEqual(['<tree>']);
|
||||
|
||||
async.done();
|
||||
});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should compile embedded templates', inject([AsyncTestCompleter], (async) => {
|
||||
compile([CompWithEmbeddedTemplate])
|
||||
.then((humanizedView) => {
|
||||
var embeddedView = humanizedView['componentViews'][0]['embeddedViews'][0];
|
||||
expect(embeddedView['elements']).toEqual(['<a>']);
|
||||
expect(embeddedView['cd']).toEqual(['prop(href)=someEmbeddedValue']);
|
||||
compile([CompWithEmbeddedTemplate]).then((humanizedView) => {
|
||||
var embeddedView = humanizedView['componentViews'][0]['embeddedViews'][0];
|
||||
expect(embeddedView['elements']).toEqual(['<a>']);
|
||||
expect(embeddedView['cd']).toEqual(['prop(href)=someEmbeddedValue']);
|
||||
|
||||
async.done();
|
||||
});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should dedup directives', inject([AsyncTestCompleter], (async) => {
|
||||
compile([CompWithDupDirectives, TreeComp])
|
||||
.then((humanizedView) => {
|
||||
expect(humanizedView['componentViews'][0]['componentViews'].length).toBe(1);
|
||||
async.done();
|
||||
compile([CompWithDupDirectives, TreeComp]).then((humanizedView) => {
|
||||
expect(humanizedView['componentViews'][0]['componentViews'].length).toBe(1);
|
||||
async.done();
|
||||
|
||||
});
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
describe('compileHostComponentRuntime', () => {
|
||||
function compile(components: Type[]): Promise<any[]> {
|
||||
return compiler.compileHostComponentRuntime(components[0])
|
||||
.then((compiledHostTemplate) =>
|
||||
humanizeViewFactory(compiledHostTemplate.viewFactory));
|
||||
.then(
|
||||
(compiledHostTemplate) => humanizeViewFactory(compiledHostTemplate.viewFactory));
|
||||
}
|
||||
|
||||
describe('no jit', () => {
|
||||
beforeEachProviders(() => [
|
||||
provide(ChangeDetectorGenConfig,
|
||||
{useValue: new ChangeDetectorGenConfig(true, false, false)})
|
||||
]);
|
||||
beforeEachProviders(() => [provide(ChangeDetectorGenConfig, {
|
||||
useValue: new ChangeDetectorGenConfig(true, false, false)
|
||||
})]);
|
||||
runTests(compile);
|
||||
});
|
||||
|
||||
describe('jit', () => {
|
||||
beforeEachProviders(() => [
|
||||
provide(ChangeDetectorGenConfig,
|
||||
{useValue: new ChangeDetectorGenConfig(true, false, true)})
|
||||
]);
|
||||
beforeEachProviders(() => [provide(ChangeDetectorGenConfig, {
|
||||
useValue: new ChangeDetectorGenConfig(true, false, true)
|
||||
})]);
|
||||
runTests(compile);
|
||||
});
|
||||
|
||||
@@ -203,15 +173,13 @@ export function main() {
|
||||
inject([AsyncTestCompleter, XHR], (async, xhr: MockXHR) => {
|
||||
// Expecting only one xhr...
|
||||
xhr.expect('package:angular2/test/compiler/compUrl.html', '<a>');
|
||||
compile([CompWithTemplateUrl])
|
||||
.then((humanizedView0) => {
|
||||
return compile([CompWithTemplateUrl])
|
||||
.then((humanizedView1) => {
|
||||
expect(humanizedView0['componentViews'][0]['elements']).toEqual(['<a>']);
|
||||
expect(humanizedView1['componentViews'][0]['elements']).toEqual(['<a>']);
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
compile([CompWithTemplateUrl]).then((humanizedView0) => {
|
||||
return compile([CompWithTemplateUrl]).then((humanizedView1) => {
|
||||
expect(humanizedView0['componentViews'][0]['elements']).toEqual(['<a>']);
|
||||
expect(humanizedView1['componentViews'][0]['elements']).toEqual(['<a>']);
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
xhr.flush();
|
||||
}));
|
||||
|
||||
@@ -235,19 +203,20 @@ export function main() {
|
||||
});
|
||||
|
||||
describe('compileTemplatesCodeGen', () => {
|
||||
function normalizeComponent(
|
||||
component: Type): Promise<NormalizedComponentWithViewDirectives> {
|
||||
function normalizeComponent(component: Type):
|
||||
Promise<NormalizedComponentWithViewDirectives> {
|
||||
var compAndViewDirMetas =
|
||||
[runtimeMetadataResolver.getDirectiveMetadata(component)].concat(
|
||||
runtimeMetadataResolver.getViewDirectivesMetadata(component));
|
||||
var upperCasePipeMeta = runtimeMetadataResolver.getPipeMetadata(UpperCasePipe);
|
||||
upperCasePipeMeta.type.moduleUrl = `package:${THIS_MODULE_ID}${MODULE_SUFFIX}`;
|
||||
return PromiseWrapper.all(compAndViewDirMetas.map(
|
||||
meta => compiler.normalizeDirectiveMetadata(meta)))
|
||||
.then((normalizedCompAndViewDirMetas: CompileDirectiveMetadata[]) =>
|
||||
new NormalizedComponentWithViewDirectives(
|
||||
normalizedCompAndViewDirMetas[0],
|
||||
normalizedCompAndViewDirMetas.slice(1), [upperCasePipeMeta]));
|
||||
return PromiseWrapper
|
||||
.all(compAndViewDirMetas.map(meta => compiler.normalizeDirectiveMetadata(meta)))
|
||||
.then(
|
||||
(normalizedCompAndViewDirMetas: CompileDirectiveMetadata[]) =>
|
||||
new NormalizedComponentWithViewDirectives(
|
||||
normalizedCompAndViewDirMetas[0], normalizedCompAndViewDirMetas.slice(1),
|
||||
[upperCasePipeMeta]));
|
||||
}
|
||||
|
||||
function compile(components: Type[]): Promise<any[]> {
|
||||
@@ -255,8 +224,8 @@ export function main() {
|
||||
.then((normalizedCompWithViewDirMetas: NormalizedComponentWithViewDirectives[]) => {
|
||||
var sourceModule = compiler.compileTemplatesCodeGen(normalizedCompWithViewDirMetas);
|
||||
var sourceWithImports =
|
||||
testableTemplateModule(sourceModule,
|
||||
normalizedCompWithViewDirMetas[0].component)
|
||||
testableTemplateModule(
|
||||
sourceModule, normalizedCompWithViewDirMetas[0].component)
|
||||
.getSourceWithImports();
|
||||
return evalModule(sourceWithImports.source, sourceWithImports.imports, null);
|
||||
});
|
||||
@@ -280,8 +249,9 @@ export function main() {
|
||||
it('should normalize the template',
|
||||
inject([AsyncTestCompleter, XHR], (async, xhr: MockXHR) => {
|
||||
xhr.expect('package:angular2/test/compiler/compUrl.html', 'loadedTemplate');
|
||||
compiler.normalizeDirectiveMetadata(
|
||||
runtimeMetadataResolver.getDirectiveMetadata(CompWithTemplateUrl))
|
||||
compiler
|
||||
.normalizeDirectiveMetadata(
|
||||
runtimeMetadataResolver.getDirectiveMetadata(CompWithTemplateUrl))
|
||||
.then((meta: CompileDirectiveMetadata) => {
|
||||
expect(meta.template.template).toEqual('loadedTemplate');
|
||||
async.done();
|
||||
@@ -420,8 +390,8 @@ export class Comp1 {
|
||||
export class CompWith2NestedComps {
|
||||
}
|
||||
|
||||
function testableTemplateModule(sourceModule: SourceModule,
|
||||
normComp: CompileDirectiveMetadata): SourceModule {
|
||||
function testableTemplateModule(
|
||||
sourceModule: SourceModule, normComp: CompileDirectiveMetadata): SourceModule {
|
||||
var testableSource = `
|
||||
${sourceModule.sourceWithModuleRefs}
|
||||
${codeGenFnHeader(['_'], '_run')}{
|
||||
@@ -485,11 +455,11 @@ export function humanizeViewFactory(
|
||||
}
|
||||
var viewManager = new SpyAppViewManager();
|
||||
viewManager.spy('createRenderComponentType')
|
||||
.andCallFake((encapsulation: ViewEncapsulation, styles: Array<string | any[]>) => {
|
||||
.andCallFake((encapsulation: ViewEncapsulation, styles: Array<string|any[]>) => {
|
||||
return new RenderComponentType('someId', encapsulation, styles);
|
||||
});
|
||||
var view: AppView = viewFactory(new RecordingRenderer([]), viewManager, containerAppElement, [],
|
||||
null, null, null);
|
||||
var view: AppView = viewFactory(
|
||||
new RecordingRenderer([]), viewManager, containerAppElement, [], null, null, null);
|
||||
return humanizeView(view, cachedResults);
|
||||
}
|
||||
|
||||
@@ -501,9 +471,11 @@ class RecordingRenderer extends SpyRenderer {
|
||||
super();
|
||||
this.spy('renderComponent')
|
||||
.andCallFake((componentProto) => new RecordingRenderer(componentProto.styles));
|
||||
this.spy('setElementProperty')
|
||||
.andCallFake((el, prop, value) => { this.props.push(`prop(${prop})=${value}`); });
|
||||
this.spy('createElement')
|
||||
.andCallFake((parent, elName) => { this.elements.push(`<${elName}>`); });
|
||||
this.spy('setElementProperty').andCallFake((el, prop, value) => {
|
||||
this.props.push(`prop(${prop})=${value}`);
|
||||
});
|
||||
this.spy('createElement').andCallFake((parent, elName) => {
|
||||
this.elements.push(`<${elName}>`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,6 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
TestComponentBuilder,
|
||||
beforeEachProviders
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit, TestComponentBuilder, beforeEachProviders} from 'angular2/testing_internal';
|
||||
|
||||
import {
|
||||
CompileTypeMetadata,
|
||||
CompileTemplateMetadata
|
||||
} from 'angular2/src/compiler/directive_metadata';
|
||||
import {CompileTypeMetadata, CompileTemplateMetadata} from 'angular2/src/compiler/directive_metadata';
|
||||
import {ViewEncapsulation} from 'angular2/src/core/metadata/view';
|
||||
|
||||
import {TemplateNormalizer} from 'angular2/src/compiler/template_normalizer';
|
||||
@@ -40,121 +24,133 @@ export function main() {
|
||||
describe('loadTemplate', () => {
|
||||
describe('inline template', () => {
|
||||
it('should store the template',
|
||||
inject([AsyncTestCompleter, TemplateNormalizer],
|
||||
(async, normalizer: TemplateNormalizer) => {
|
||||
normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
|
||||
encapsulation: null,
|
||||
template: 'a',
|
||||
templateUrl: null,
|
||||
styles: [],
|
||||
styleUrls: ['test.css']
|
||||
}))
|
||||
.then((template: CompileTemplateMetadata) => {
|
||||
expect(template.template).toEqual('a');
|
||||
expect(template.templateUrl).toEqual('package:some/module/a.js');
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
inject(
|
||||
[AsyncTestCompleter, TemplateNormalizer],
|
||||
(async, normalizer: TemplateNormalizer) => {
|
||||
normalizer
|
||||
.normalizeTemplate(dirType, new CompileTemplateMetadata({
|
||||
encapsulation: null,
|
||||
template: 'a',
|
||||
templateUrl: null,
|
||||
styles: [],
|
||||
styleUrls: ['test.css']
|
||||
}))
|
||||
.then((template: CompileTemplateMetadata) => {
|
||||
expect(template.template).toEqual('a');
|
||||
expect(template.templateUrl).toEqual('package:some/module/a.js');
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should resolve styles on the annotation against the moduleUrl',
|
||||
inject([AsyncTestCompleter, TemplateNormalizer],
|
||||
(async, normalizer: TemplateNormalizer) => {
|
||||
normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
|
||||
encapsulation: null,
|
||||
template: '',
|
||||
templateUrl: null,
|
||||
styles: [],
|
||||
styleUrls: ['test.css']
|
||||
}))
|
||||
.then((template: CompileTemplateMetadata) => {
|
||||
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
inject(
|
||||
[AsyncTestCompleter, TemplateNormalizer],
|
||||
(async, normalizer: TemplateNormalizer) => {
|
||||
normalizer
|
||||
.normalizeTemplate(dirType, new CompileTemplateMetadata({
|
||||
encapsulation: null,
|
||||
template: '',
|
||||
templateUrl: null,
|
||||
styles: [],
|
||||
styleUrls: ['test.css']
|
||||
}))
|
||||
.then((template: CompileTemplateMetadata) => {
|
||||
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should resolve styles in the template against the moduleUrl',
|
||||
inject([AsyncTestCompleter, TemplateNormalizer],
|
||||
(async, normalizer: TemplateNormalizer) => {
|
||||
normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
|
||||
encapsulation: null,
|
||||
template: '<style>@import test.css</style>',
|
||||
templateUrl: null,
|
||||
styles: [],
|
||||
styleUrls: []
|
||||
}))
|
||||
.then((template: CompileTemplateMetadata) => {
|
||||
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
inject(
|
||||
[AsyncTestCompleter, TemplateNormalizer],
|
||||
(async, normalizer: TemplateNormalizer) => {
|
||||
normalizer
|
||||
.normalizeTemplate(dirType, new CompileTemplateMetadata({
|
||||
encapsulation: null,
|
||||
template: '<style>@import test.css</style>',
|
||||
templateUrl: null,
|
||||
styles: [],
|
||||
styleUrls: []
|
||||
}))
|
||||
.then((template: CompileTemplateMetadata) => {
|
||||
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
});
|
||||
|
||||
describe('templateUrl', () => {
|
||||
|
||||
it('should load a template from a url that is resolved against moduleUrl',
|
||||
inject([AsyncTestCompleter, TemplateNormalizer, XHR],
|
||||
(async, normalizer: TemplateNormalizer, xhr: MockXHR) => {
|
||||
xhr.expect('package:some/module/sometplurl.html', 'a');
|
||||
normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
|
||||
encapsulation: null,
|
||||
template: null,
|
||||
templateUrl: 'sometplurl.html',
|
||||
styles: [],
|
||||
styleUrls: ['test.css']
|
||||
}))
|
||||
.then((template: CompileTemplateMetadata) => {
|
||||
expect(template.template).toEqual('a');
|
||||
expect(template.templateUrl)
|
||||
.toEqual('package:some/module/sometplurl.html');
|
||||
async.done();
|
||||
});
|
||||
xhr.flush();
|
||||
}));
|
||||
inject(
|
||||
[AsyncTestCompleter, TemplateNormalizer, XHR],
|
||||
(async, normalizer: TemplateNormalizer, xhr: MockXHR) => {
|
||||
xhr.expect('package:some/module/sometplurl.html', 'a');
|
||||
normalizer
|
||||
.normalizeTemplate(dirType, new CompileTemplateMetadata({
|
||||
encapsulation: null,
|
||||
template: null,
|
||||
templateUrl: 'sometplurl.html',
|
||||
styles: [],
|
||||
styleUrls: ['test.css']
|
||||
}))
|
||||
.then((template: CompileTemplateMetadata) => {
|
||||
expect(template.template).toEqual('a');
|
||||
expect(template.templateUrl).toEqual('package:some/module/sometplurl.html');
|
||||
async.done();
|
||||
});
|
||||
xhr.flush();
|
||||
}));
|
||||
|
||||
it('should resolve styles on the annotation against the moduleUrl',
|
||||
inject([AsyncTestCompleter, TemplateNormalizer, XHR],
|
||||
(async, normalizer: TemplateNormalizer, xhr: MockXHR) => {
|
||||
xhr.expect('package:some/module/tpl/sometplurl.html', '');
|
||||
normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
|
||||
encapsulation: null,
|
||||
template: null,
|
||||
templateUrl: 'tpl/sometplurl.html',
|
||||
styles: [],
|
||||
styleUrls: ['test.css']
|
||||
}))
|
||||
.then((template: CompileTemplateMetadata) => {
|
||||
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
|
||||
async.done();
|
||||
});
|
||||
xhr.flush();
|
||||
}));
|
||||
inject(
|
||||
[AsyncTestCompleter, TemplateNormalizer, XHR],
|
||||
(async, normalizer: TemplateNormalizer, xhr: MockXHR) => {
|
||||
xhr.expect('package:some/module/tpl/sometplurl.html', '');
|
||||
normalizer
|
||||
.normalizeTemplate(dirType, new CompileTemplateMetadata({
|
||||
encapsulation: null,
|
||||
template: null,
|
||||
templateUrl: 'tpl/sometplurl.html',
|
||||
styles: [],
|
||||
styleUrls: ['test.css']
|
||||
}))
|
||||
.then((template: CompileTemplateMetadata) => {
|
||||
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
|
||||
async.done();
|
||||
});
|
||||
xhr.flush();
|
||||
}));
|
||||
|
||||
it('should resolve styles in the template against the templateUrl',
|
||||
inject([AsyncTestCompleter, TemplateNormalizer, XHR],
|
||||
(async, normalizer: TemplateNormalizer, xhr: MockXHR) => {
|
||||
xhr.expect('package:some/module/tpl/sometplurl.html',
|
||||
'<style>@import test.css</style>');
|
||||
normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
|
||||
encapsulation: null,
|
||||
template: null,
|
||||
templateUrl: 'tpl/sometplurl.html',
|
||||
styles: [],
|
||||
styleUrls: []
|
||||
}))
|
||||
.then((template: CompileTemplateMetadata) => {
|
||||
expect(template.styleUrls).toEqual(['package:some/module/tpl/test.css']);
|
||||
async.done();
|
||||
});
|
||||
xhr.flush();
|
||||
}));
|
||||
inject(
|
||||
[AsyncTestCompleter, TemplateNormalizer, XHR],
|
||||
(async, normalizer: TemplateNormalizer, xhr: MockXHR) => {
|
||||
xhr.expect(
|
||||
'package:some/module/tpl/sometplurl.html', '<style>@import test.css</style>');
|
||||
normalizer
|
||||
.normalizeTemplate(dirType, new CompileTemplateMetadata({
|
||||
encapsulation: null,
|
||||
template: null,
|
||||
templateUrl: 'tpl/sometplurl.html',
|
||||
styles: [],
|
||||
styleUrls: []
|
||||
}))
|
||||
.then((template: CompileTemplateMetadata) => {
|
||||
expect(template.styleUrls).toEqual(['package:some/module/tpl/test.css']);
|
||||
async.done();
|
||||
});
|
||||
xhr.flush();
|
||||
}));
|
||||
|
||||
});
|
||||
|
||||
it('should throw if no template was specified',
|
||||
inject([TemplateNormalizer], (normalizer: TemplateNormalizer) => {
|
||||
expect(() => normalizer.normalizeTemplate(
|
||||
dirType, new CompileTemplateMetadata(
|
||||
{encapsulation: null, styles: [], styleUrls: []})))
|
||||
expect(
|
||||
() => normalizer.normalizeTemplate(
|
||||
dirType,
|
||||
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []})))
|
||||
.toThrowError('No template specified for component SomeComp');
|
||||
}));
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,24 +1,7 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
xdescribe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
AsyncTestCompleter,
|
||||
inject,
|
||||
beforeEachProviders
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal';
|
||||
|
||||
import {HtmlParser} from 'angular2/src/compiler/html_parser';
|
||||
import {
|
||||
preparseElement,
|
||||
PreparsedElementType,
|
||||
PreparsedElement
|
||||
} from 'angular2/src/compiler/template_preparser';
|
||||
import {preparseElement, PreparsedElementType, PreparsedElement} from 'angular2/src/compiler/template_preparser';
|
||||
|
||||
export function main() {
|
||||
describe('preparseElement', () => {
|
||||
|
||||
@@ -1,14 +1,4 @@
|
||||
import {
|
||||
describe,
|
||||
it,
|
||||
expect,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
iit,
|
||||
xit,
|
||||
el,
|
||||
inject
|
||||
} from 'angular2/testing_internal';
|
||||
import {describe, it, expect, beforeEach, ddescribe, iit, xit, el, inject} from 'angular2/testing_internal';
|
||||
import {IS_DART} from 'angular2/src/facade/lang';
|
||||
import {UrlResolver} from 'angular2/src/compiler/url_resolver';
|
||||
|
||||
@@ -83,47 +73,47 @@ export function main() {
|
||||
|
||||
it('should not resolve urls against the baseUrl when the url contains a scheme', () => {
|
||||
resolver = new UrlResolver('my_packages_dir');
|
||||
expect(resolver.resolve("base/", 'package:file')).toEqual('my_packages_dir/file');
|
||||
expect(resolver.resolve("base/", 'http:super_file')).toEqual('http:super_file');
|
||||
expect(resolver.resolve("base/", './mega_file')).toEqual('base/mega_file');
|
||||
expect(resolver.resolve('base/', 'package:file')).toEqual('my_packages_dir/file');
|
||||
expect(resolver.resolve('base/', 'http:super_file')).toEqual('http:super_file');
|
||||
expect(resolver.resolve('base/', './mega_file')).toEqual('base/mega_file');
|
||||
});
|
||||
});
|
||||
|
||||
describe('packages',
|
||||
() => {
|
||||
it('should resolve a url based on the application package', () => {
|
||||
resolver = new UrlResolver('my_packages_dir');
|
||||
expect(resolver.resolve(null, 'package:some/dir/file.txt'))
|
||||
.toEqual('my_packages_dir/some/dir/file.txt');
|
||||
expect(resolver.resolve(null, 'some/dir/file.txt')).toEqual('some/dir/file.txt');
|
||||
});
|
||||
describe('packages', () => {
|
||||
it('should resolve a url based on the application package', () => {
|
||||
resolver = new UrlResolver('my_packages_dir');
|
||||
expect(resolver.resolve(null, 'package:some/dir/file.txt'))
|
||||
.toEqual('my_packages_dir/some/dir/file.txt');
|
||||
expect(resolver.resolve(null, 'some/dir/file.txt')).toEqual('some/dir/file.txt');
|
||||
});
|
||||
|
||||
it('should contain a default value of "/packages" when nothing is provided for DART',
|
||||
inject([UrlResolver], (resolver: UrlResolver) => {
|
||||
if (IS_DART) {
|
||||
expect(resolver.resolve(null, 'package:file')).toEqual('/packages/file');
|
||||
}
|
||||
}));
|
||||
it('should contain a default value of "/packages" when nothing is provided for DART',
|
||||
inject([UrlResolver], (resolver: UrlResolver) => {
|
||||
if (IS_DART) {
|
||||
expect(resolver.resolve(null, 'package:file')).toEqual('/packages/file');
|
||||
}
|
||||
}));
|
||||
|
||||
it('should contain a default value of "/" when nothing is provided for TS/ESM',
|
||||
inject([UrlResolver], (resolver: UrlResolver) => {
|
||||
if (!IS_DART) {
|
||||
expect(resolver.resolve(null, 'package:file')).toEqual('/file');
|
||||
}
|
||||
}));
|
||||
it('should contain a default value of "/" when nothing is provided for TS/ESM',
|
||||
inject([UrlResolver], (resolver: UrlResolver) => {
|
||||
if (!IS_DART) {
|
||||
expect(resolver.resolve(null, 'package:file')).toEqual('/file');
|
||||
}
|
||||
}));
|
||||
|
||||
it('should resolve a package value when present within the baseurl', () => {
|
||||
resolver = new UrlResolver('/my_special_dir');
|
||||
expect(resolver.resolve('package:some_dir/', 'matias.html'))
|
||||
.toEqual('/my_special_dir/some_dir/matias.html');
|
||||
});
|
||||
})
|
||||
it('should resolve a package value when present within the baseurl', () => {
|
||||
resolver = new UrlResolver('/my_special_dir');
|
||||
expect(resolver.resolve('package:some_dir/', 'matias.html'))
|
||||
.toEqual('/my_special_dir/some_dir/matias.html');
|
||||
});
|
||||
})
|
||||
|
||||
describe('corner and error cases', () => {
|
||||
it('should encode URLs before resolving', () => {
|
||||
expect(resolver.resolve('foo/baz', `<p #p>Hello
|
||||
describe('corner and error cases', () => {
|
||||
it('should encode URLs before resolving',
|
||||
() => {
|
||||
expect(resolver.resolve('foo/baz', `<p #p>Hello
|
||||
</p>`)).toEqual('foo/%3Cp%20#p%3EHello%0A%20%20%20%20%20%20%20%20%3C/p%3E');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,16 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
TestComponentBuilder
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit, TestComponentBuilder} from 'angular2/testing_internal';
|
||||
|
||||
import {IS_DART} from 'angular2/src/facade/lang';
|
||||
import {escapeSingleQuoteString, escapeDoubleQuoteString} from 'angular2/src/compiler/util';
|
||||
|
||||
@@ -1,14 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it,} from 'angular2/testing_internal';
|
||||
import {MockXHR} from 'angular2/src/compiler/xhr_mock';
|
||||
import {PromiseWrapper} from 'angular2/src/facade/async';
|
||||
import {isPresent} from 'angular2/src/facade/lang';
|
||||
|
||||
@@ -1,43 +1,28 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
el,
|
||||
AsyncTestCompleter,
|
||||
fakeAsync,
|
||||
tick,
|
||||
inject,
|
||||
SpyObject
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, el, AsyncTestCompleter, fakeAsync, tick, inject, SpyObject} from 'angular2/testing_internal';
|
||||
import {SpyChangeDetector} from './spies';
|
||||
import {ApplicationRef_, ApplicationRef, PlatformRef_} from "angular2/src/core/application_ref";
|
||||
import {Injector, Provider, APP_INITIALIZER} from "angular2/core";
|
||||
import {ChangeDetectorRef_} from "angular2/src/core/change_detection/change_detector_ref";
|
||||
import {PromiseWrapper, PromiseCompleter, TimerWrapper} from "angular2/src/facade/async";
|
||||
import {ListWrapper} from "angular2/src/facade/collection";
|
||||
import {ApplicationRef_, ApplicationRef, PlatformRef_} from 'angular2/src/core/application_ref';
|
||||
import {Injector, Provider, APP_INITIALIZER} from 'angular2/core';
|
||||
import {ChangeDetectorRef_} from 'angular2/src/core/change_detection/change_detector_ref';
|
||||
import {PromiseWrapper, PromiseCompleter, TimerWrapper} from 'angular2/src/facade/async';
|
||||
import {ListWrapper} from 'angular2/src/facade/collection';
|
||||
import {ExceptionHandler} from 'angular2/src/facade/exception_handler';
|
||||
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
|
||||
|
||||
export function main() {
|
||||
describe("ApplicationRef", () => {
|
||||
it("should throw when reentering tick", () => {
|
||||
describe('ApplicationRef', () => {
|
||||
it('should throw when reentering tick', () => {
|
||||
var cd = <any>new SpyChangeDetector();
|
||||
var ref = new ApplicationRef_(null, null, null);
|
||||
ref.registerChangeDetector(new ChangeDetectorRef_(cd));
|
||||
cd.spy("detectChanges").andCallFake(() => ref.tick());
|
||||
expect(() => ref.tick()).toThrowError("ApplicationRef.tick is called recursively");
|
||||
cd.spy('detectChanges').andCallFake(() => ref.tick());
|
||||
expect(() => ref.tick()).toThrowError('ApplicationRef.tick is called recursively');
|
||||
});
|
||||
});
|
||||
|
||||
describe("PlatformRef", () => {
|
||||
describe('PlatformRef', () => {
|
||||
var exceptionHandler =
|
||||
new Provider(ExceptionHandler, {useValue: new ExceptionHandler(DOM, true)});
|
||||
describe("asyncApplication", () => {
|
||||
describe('asyncApplication', () => {
|
||||
function expectProviders(injector: Injector, providers: Array<any>): void {
|
||||
for (let i = 0; i < providers.length; i++) {
|
||||
let provider = providers[i];
|
||||
@@ -45,7 +30,7 @@ export function main() {
|
||||
}
|
||||
}
|
||||
|
||||
it("should merge syncronous and asyncronous providers",
|
||||
it('should merge syncronous and asyncronous providers',
|
||||
inject([AsyncTestCompleter, Injector], (async, injector) => {
|
||||
let ref = new PlatformRef_(injector, null);
|
||||
let ASYNC_PROVIDERS = [new Provider(Foo, {useValue: new Foo()}), exceptionHandler];
|
||||
@@ -58,19 +43,18 @@ export function main() {
|
||||
});
|
||||
}));
|
||||
|
||||
it("should allow function to be null",
|
||||
it('should allow function to be null',
|
||||
inject([AsyncTestCompleter, Injector], (async, injector) => {
|
||||
let ref = new PlatformRef_(injector, null);
|
||||
let SYNC_PROVIDERS = [new Provider(Bar, {useValue: new Bar()}), exceptionHandler];
|
||||
ref.asyncApplication(null, SYNC_PROVIDERS)
|
||||
.then((appRef) => {
|
||||
expectProviders(appRef.injector, SYNC_PROVIDERS);
|
||||
async.done();
|
||||
});
|
||||
ref.asyncApplication(null, SYNC_PROVIDERS).then((appRef) => {
|
||||
expectProviders(appRef.injector, SYNC_PROVIDERS);
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
function mockAsyncAppInitializer(completer: PromiseCompleter<any>,
|
||||
providers: Array<any> = null, injector?: Injector) {
|
||||
function mockAsyncAppInitializer(
|
||||
completer: PromiseCompleter<any>, providers: Array<any> = null, injector?: Injector) {
|
||||
return () => {
|
||||
if (providers != null) {
|
||||
expectProviders(injector, providers);
|
||||
@@ -80,57 +64,54 @@ export function main() {
|
||||
};
|
||||
}
|
||||
|
||||
it("should wait for asyncronous app initializers",
|
||||
it('should wait for asyncronous app initializers',
|
||||
inject([AsyncTestCompleter, Injector], (async, injector) => {
|
||||
let ref = new PlatformRef_(injector, null);
|
||||
|
||||
let completer: PromiseCompleter<any> = PromiseWrapper.completer();
|
||||
let SYNC_PROVIDERS = [
|
||||
new Provider(Bar, {useValue: new Bar()}),
|
||||
new Provider(APP_INITIALIZER,
|
||||
{useValue: mockAsyncAppInitializer(completer), multi: true})
|
||||
new Provider(
|
||||
APP_INITIALIZER, {useValue: mockAsyncAppInitializer(completer), multi: true})
|
||||
];
|
||||
ref.asyncApplication(null, [SYNC_PROVIDERS, exceptionHandler])
|
||||
.then((appRef) => {
|
||||
expectProviders(appRef.injector,
|
||||
SYNC_PROVIDERS.slice(0, SYNC_PROVIDERS.length - 1));
|
||||
completer.promise.then((_) => async.done());
|
||||
});
|
||||
ref.asyncApplication(null, [SYNC_PROVIDERS, exceptionHandler]).then((appRef) => {
|
||||
expectProviders(appRef.injector, SYNC_PROVIDERS.slice(0, SYNC_PROVIDERS.length - 1));
|
||||
completer.promise.then((_) => async.done());
|
||||
});
|
||||
}));
|
||||
|
||||
it("should wait for async providers and then async app initializers",
|
||||
it('should wait for async providers and then async app initializers',
|
||||
inject([AsyncTestCompleter, Injector], (async, injector) => {
|
||||
let ref = new PlatformRef_(injector, null);
|
||||
let ASYNC_PROVIDERS = [new Provider(Foo, {useValue: new Foo()})];
|
||||
let completer: PromiseCompleter<any> = PromiseWrapper.completer();
|
||||
let SYNC_PROVIDERS = [
|
||||
new Provider(Bar, {useValue: new Bar()}),
|
||||
new Provider(APP_INITIALIZER,
|
||||
{
|
||||
useFactory: (injector) => mockAsyncAppInitializer(
|
||||
<any>completer, ASYNC_PROVIDERS, injector),
|
||||
multi: true,
|
||||
deps: [Injector]
|
||||
})
|
||||
new Provider(Bar, {useValue: new Bar()}), new Provider(APP_INITIALIZER, {
|
||||
useFactory: (injector) =>
|
||||
mockAsyncAppInitializer(<any>completer, ASYNC_PROVIDERS, injector),
|
||||
multi: true,
|
||||
deps: [Injector]
|
||||
})
|
||||
];
|
||||
ref.asyncApplication((zone) => PromiseWrapper.resolve(ASYNC_PROVIDERS),
|
||||
[SYNC_PROVIDERS, exceptionHandler])
|
||||
ref.asyncApplication(
|
||||
(zone) => PromiseWrapper.resolve(ASYNC_PROVIDERS),
|
||||
[SYNC_PROVIDERS, exceptionHandler])
|
||||
.then((appRef) => {
|
||||
expectProviders(appRef.injector,
|
||||
SYNC_PROVIDERS.slice(0, SYNC_PROVIDERS.length - 1));
|
||||
expectProviders(
|
||||
appRef.injector, SYNC_PROVIDERS.slice(0, SYNC_PROVIDERS.length - 1));
|
||||
completer.promise.then((_) => async.done());
|
||||
});
|
||||
}));
|
||||
});
|
||||
|
||||
describe("application", () => {
|
||||
it("should throw if an APP_INITIIALIZER returns a promise", inject([Injector], (injector) => {
|
||||
describe('application', () => {
|
||||
it('should throw if an APP_INITIIALIZER returns a promise', inject([Injector], (injector) => {
|
||||
let ref = new PlatformRef_(injector, null);
|
||||
let appInitializer = new Provider(
|
||||
APP_INITIALIZER, {useValue: () => PromiseWrapper.resolve([]), multi: true});
|
||||
expect(() => ref.application([appInitializer, exceptionHandler]))
|
||||
.toThrowError(
|
||||
"Cannot use asyncronous app initializers with application. Use asyncApplication instead.");
|
||||
'Cannot use asyncronous app initializers with application. Use asyncApplication instead.');
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,16 +1,6 @@
|
||||
import {ListWrapper, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
|
||||
import {isBlank, isPresent} from 'angular2/src/facade/lang';
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
BindingRecord,
|
||||
ChangeDetectorDefinition,
|
||||
DirectiveIndex,
|
||||
DirectiveRecord,
|
||||
Lexer,
|
||||
Locals,
|
||||
Parser,
|
||||
ChangeDetectorGenConfig
|
||||
} from 'angular2/src/core/change_detection/change_detection';
|
||||
import {ChangeDetectionStrategy, BindingRecord, ChangeDetectorDefinition, DirectiveIndex, DirectiveRecord, Lexer, Locals, Parser, ChangeDetectorGenConfig} from 'angular2/src/core/change_detection/change_detection';
|
||||
import {reflector} from 'angular2/src/core/reflection/reflection';
|
||||
import {ReflectionCapabilities} from 'angular2/src/core/reflection/reflection_capabilities';
|
||||
|
||||
@@ -32,16 +22,16 @@ function _createBindingRecords(expression: string): BindingRecord[] {
|
||||
}
|
||||
|
||||
function _createEventRecords(expression: string): BindingRecord[] {
|
||||
var eq = expression.indexOf("=");
|
||||
var eq = expression.indexOf('=');
|
||||
var eventName = expression.substring(1, eq - 1);
|
||||
var exp = expression.substring(eq + 2, expression.length - 1);
|
||||
var ast = _getParser().parseAction(exp, 'location');
|
||||
return [BindingRecord.createForEvent(ast, eventName, 0)];
|
||||
}
|
||||
|
||||
function _createHostEventRecords(expression: string,
|
||||
directiveRecord: DirectiveRecord): BindingRecord[] {
|
||||
var parts = expression.split("=");
|
||||
function _createHostEventRecords(
|
||||
expression: string, directiveRecord: DirectiveRecord): BindingRecord[] {
|
||||
var parts = expression.split('=');
|
||||
var eventName = parts[0].substring(1, parts[0].length - 1);
|
||||
var exp = parts[1].substring(1, parts[1].length - 1);
|
||||
|
||||
@@ -90,8 +80,8 @@ export function getDefinition(id: string): TestDefinition {
|
||||
var variableBindings = [];
|
||||
var eventRecords = _createBindingRecords(id);
|
||||
var directiveRecords = [];
|
||||
let cdDef = new ChangeDetectorDefinition(id, strategy, variableBindings, eventRecords, [],
|
||||
directiveRecords, genConfig);
|
||||
let cdDef = new ChangeDetectorDefinition(
|
||||
id, strategy, variableBindings, eventRecords, [], directiveRecords, genConfig);
|
||||
testDef = new TestDefinition(id, cdDef, null);
|
||||
|
||||
} else if (ListWrapper.indexOf(_availableEventDefinitions, id) >= 0) {
|
||||
@@ -106,9 +96,9 @@ export function getDefinition(id: string): TestDefinition {
|
||||
[_DirectiveUpdating.basicRecords[0], _DirectiveUpdating.basicRecords[1]], genConfig);
|
||||
testDef = new TestDefinition(id, cdDef, null);
|
||||
|
||||
} else if (id == "updateElementProduction") {
|
||||
} else if (id == 'updateElementProduction') {
|
||||
var genConfig = new ChangeDetectorGenConfig(false, false, true);
|
||||
var records = _createBindingRecords("name");
|
||||
var records = _createBindingRecords('name');
|
||||
let cdDef = new ChangeDetectorDefinition(id, null, [], records, [], [], genConfig);
|
||||
testDef = new TestDefinition(id, cdDef, null);
|
||||
}
|
||||
@@ -130,13 +120,13 @@ export class TestDefinition {
|
||||
*/
|
||||
export function getAllDefinitions(): TestDefinition[] {
|
||||
var allDefs = _availableDefinitions;
|
||||
allDefs = ListWrapper.concat(allDefs,
|
||||
StringMapWrapper.keys(_ExpressionWithLocals.availableDefinitions));
|
||||
allDefs = ListWrapper.concat(
|
||||
allDefs, StringMapWrapper.keys(_ExpressionWithLocals.availableDefinitions));
|
||||
allDefs = allDefs.concat(StringMapWrapper.keys(_ExpressionWithMode.availableDefinitions));
|
||||
allDefs = allDefs.concat(StringMapWrapper.keys(_DirectiveUpdating.availableDefinitions));
|
||||
allDefs = allDefs.concat(_availableEventDefinitions);
|
||||
allDefs = allDefs.concat(_availableHostEventDefinitions);
|
||||
allDefs = allDefs.concat(["updateElementProduction"]);
|
||||
allDefs = allDefs.concat(['updateElementProduction']);
|
||||
return allDefs.map(getDefinition);
|
||||
}
|
||||
|
||||
@@ -149,8 +139,8 @@ class _ExpressionWithLocals {
|
||||
var bindingRecords = _createBindingRecords(this._expression);
|
||||
var directiveRecords = [];
|
||||
var genConfig = new ChangeDetectorGenConfig(true, true, true);
|
||||
return new ChangeDetectorDefinition('(empty id)', strategy, variableBindings, bindingRecords,
|
||||
[], directiveRecords, genConfig);
|
||||
return new ChangeDetectorDefinition(
|
||||
'(empty id)', strategy, variableBindings, bindingRecords, [], directiveRecords, genConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -175,8 +165,9 @@ class _ExpressionWithLocals {
|
||||
}
|
||||
|
||||
class _ExpressionWithMode {
|
||||
constructor(private _strategy: ChangeDetectionStrategy, private _withRecords: boolean,
|
||||
private _withEvents: boolean) {}
|
||||
constructor(
|
||||
private _strategy: ChangeDetectionStrategy, private _withRecords: boolean,
|
||||
private _withEvents: boolean) {}
|
||||
|
||||
createChangeDetectorDefinition(): ChangeDetectorDefinition {
|
||||
var variableBindings = [];
|
||||
@@ -194,12 +185,12 @@ class _ExpressionWithMode {
|
||||
});
|
||||
|
||||
if (this._withRecords) {
|
||||
var updateDirWithOnDefaultRecord =
|
||||
BindingRecord.createForDirective(_getParser().parseBinding('42', 'location'), 'a',
|
||||
(o, v) => (<any>o).a = v, dirRecordWithDefault);
|
||||
var updateDirWithOnPushRecord =
|
||||
BindingRecord.createForDirective(_getParser().parseBinding('42', 'location'), 'a',
|
||||
(o, v) => (<any>o).a = v, dirRecordWithOnPush);
|
||||
var updateDirWithOnDefaultRecord = BindingRecord.createForDirective(
|
||||
_getParser().parseBinding('42', 'location'), 'a', (o, v) => (<any>o).a = v,
|
||||
dirRecordWithDefault);
|
||||
var updateDirWithOnPushRecord = BindingRecord.createForDirective(
|
||||
_getParser().parseBinding('42', 'location'), 'a', (o, v) => (<any>o).a = v,
|
||||
dirRecordWithOnPush);
|
||||
|
||||
directiveRecords = [dirRecordWithDefault, dirRecordWithOnPush];
|
||||
bindingRecords = [updateDirWithOnDefaultRecord, updateDirWithOnPushRecord];
|
||||
@@ -207,15 +198,16 @@ class _ExpressionWithMode {
|
||||
|
||||
if (this._withEvents) {
|
||||
directiveRecords = [dirRecordWithDefault, dirRecordWithOnPush];
|
||||
eventRecords =
|
||||
ListWrapper.concat(_createEventRecords("(event)='false'"),
|
||||
_createHostEventRecords("(host-event)='false'", dirRecordWithOnPush))
|
||||
eventRecords = ListWrapper.concat(
|
||||
_createEventRecords('(event)=\'false\''),
|
||||
_createHostEventRecords('(host-event)=\'false\'', dirRecordWithOnPush))
|
||||
}
|
||||
|
||||
var genConfig = new ChangeDetectorGenConfig(true, true, true);
|
||||
|
||||
return new ChangeDetectorDefinition('(empty id)', this._strategy, variableBindings,
|
||||
bindingRecords, eventRecords, directiveRecords, genConfig);
|
||||
return new ChangeDetectorDefinition(
|
||||
'(empty id)', this._strategy, variableBindings, bindingRecords, eventRecords,
|
||||
directiveRecords, genConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -235,27 +227,29 @@ class _ExpressionWithMode {
|
||||
}
|
||||
|
||||
class _DirectiveUpdating {
|
||||
constructor(private _bindingRecords: BindingRecord[],
|
||||
private _directiveRecords: DirectiveRecord[]) {}
|
||||
constructor(
|
||||
private _bindingRecords: BindingRecord[], private _directiveRecords: DirectiveRecord[]) {}
|
||||
|
||||
createChangeDetectorDefinition(): ChangeDetectorDefinition {
|
||||
var strategy = null;
|
||||
var variableBindings = [];
|
||||
var genConfig = new ChangeDetectorGenConfig(true, true, true);
|
||||
|
||||
return new ChangeDetectorDefinition('(empty id)', strategy, variableBindings,
|
||||
this._bindingRecords, [], this._directiveRecords,
|
||||
genConfig);
|
||||
return new ChangeDetectorDefinition(
|
||||
'(empty id)', strategy, variableBindings, this._bindingRecords, [], this._directiveRecords,
|
||||
genConfig);
|
||||
}
|
||||
|
||||
static updateA(expression: string, dirRecord): BindingRecord {
|
||||
return BindingRecord.createForDirective(_getParser().parseBinding(expression, 'location'), 'a',
|
||||
(o, v) => (<any>o).a = v, dirRecord);
|
||||
return BindingRecord.createForDirective(
|
||||
_getParser().parseBinding(expression, 'location'), 'a', (o, v) => (<any>o).a = v,
|
||||
dirRecord);
|
||||
}
|
||||
|
||||
static updateB(expression: string, dirRecord): BindingRecord {
|
||||
return BindingRecord.createForDirective(_getParser().parseBinding(expression, 'location'), 'b',
|
||||
(o, v) => (<any>o).b = v, dirRecord);
|
||||
return BindingRecord.createForDirective(
|
||||
_getParser().parseBinding(expression, 'location'), 'b', (o, v) => (<any>o).b = v,
|
||||
dirRecord);
|
||||
}
|
||||
|
||||
static basicRecords: DirectiveRecord[] = [
|
||||
@@ -304,16 +298,15 @@ class _DirectiveUpdating {
|
||||
'directNoDispatcher': new _DirectiveUpdating(
|
||||
[_DirectiveUpdating.updateA('42', _DirectiveUpdating.basicRecords[0])],
|
||||
[_DirectiveUpdating.basicRecords[0]]),
|
||||
'groupChanges':
|
||||
new _DirectiveUpdating(
|
||||
[
|
||||
_DirectiveUpdating.updateA('1', _DirectiveUpdating.basicRecords[0]),
|
||||
_DirectiveUpdating.updateB('2', _DirectiveUpdating.basicRecords[0]),
|
||||
BindingRecord.createDirectiveOnChanges(_DirectiveUpdating.basicRecords[0]),
|
||||
_DirectiveUpdating.updateA('3', _DirectiveUpdating.basicRecords[1]),
|
||||
BindingRecord.createDirectiveOnChanges(_DirectiveUpdating.basicRecords[1])
|
||||
],
|
||||
[_DirectiveUpdating.basicRecords[0], _DirectiveUpdating.basicRecords[1]]),
|
||||
'groupChanges': new _DirectiveUpdating(
|
||||
[
|
||||
_DirectiveUpdating.updateA('1', _DirectiveUpdating.basicRecords[0]),
|
||||
_DirectiveUpdating.updateB('2', _DirectiveUpdating.basicRecords[0]),
|
||||
BindingRecord.createDirectiveOnChanges(_DirectiveUpdating.basicRecords[0]),
|
||||
_DirectiveUpdating.updateA('3', _DirectiveUpdating.basicRecords[1]),
|
||||
BindingRecord.createDirectiveOnChanges(_DirectiveUpdating.basicRecords[1])
|
||||
],
|
||||
[_DirectiveUpdating.basicRecords[0], _DirectiveUpdating.basicRecords[1]]),
|
||||
'directiveDoCheck': new _DirectiveUpdating(
|
||||
[BindingRecord.createDirectiveDoCheck(_DirectiveUpdating.basicRecords[0])],
|
||||
[_DirectiveUpdating.basicRecords[0]]),
|
||||
@@ -325,20 +318,14 @@ class _DirectiveUpdating {
|
||||
'noCallbacks': new _DirectiveUpdating(
|
||||
[_DirectiveUpdating.updateA('1', _DirectiveUpdating.recordNoCallbacks)],
|
||||
[_DirectiveUpdating.recordNoCallbacks]),
|
||||
'readingDirectives':
|
||||
new _DirectiveUpdating(
|
||||
[
|
||||
BindingRecord.createForHostProperty(
|
||||
new DirectiveIndex(0, 0), _getParser().parseBinding('a', 'location'), PROP_NAME)
|
||||
],
|
||||
[_DirectiveUpdating.basicRecords[0]]),
|
||||
'interpolation':
|
||||
new _DirectiveUpdating(
|
||||
[
|
||||
BindingRecord.createForElementProperty(
|
||||
_getParser().parseInterpolation('B{{a}}A', 'location'), 0, PROP_NAME)
|
||||
],
|
||||
[])
|
||||
'readingDirectives': new _DirectiveUpdating(
|
||||
[BindingRecord.createForHostProperty(
|
||||
new DirectiveIndex(0, 0), _getParser().parseBinding('a', 'location'), PROP_NAME)],
|
||||
[_DirectiveUpdating.basicRecords[0]]),
|
||||
'interpolation': new _DirectiveUpdating(
|
||||
[BindingRecord.createForElementProperty(
|
||||
_getParser().parseInterpolation('B{{a}}A', 'location'), 0, PROP_NAME)],
|
||||
[])
|
||||
};
|
||||
}
|
||||
|
||||
@@ -390,8 +377,8 @@ var _availableDefinitions = [
|
||||
'{z: a}',
|
||||
'name | pipe',
|
||||
'(name | pipe).length',
|
||||
"name | pipe:'one':address.city",
|
||||
"name | pipe:'a':'b' | pipe:0:1:2",
|
||||
'name | pipe:\'one\':address.city',
|
||||
'name | pipe:\'a\':\'b\' | pipe:0:1:2',
|
||||
'value',
|
||||
'a',
|
||||
'address.city',
|
||||
|
||||
@@ -1,20 +1,6 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
tick,
|
||||
fakeAsync
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, tick, fakeAsync} from 'angular2/testing_internal';
|
||||
|
||||
import {
|
||||
ChangeDetectorRef,
|
||||
ChangeDetectorRef_
|
||||
} from 'angular2/src/core/change_detection/change_detector_ref';
|
||||
import {ChangeDetectorRef, ChangeDetectorRef_} from 'angular2/src/core/change_detection/change_detector_ref';
|
||||
import {SpyChangeDetector} from '../spies';
|
||||
|
||||
|
||||
|
||||
@@ -1,50 +1,13 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
tick,
|
||||
fakeAsync
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, tick, fakeAsync} from 'angular2/testing_internal';
|
||||
|
||||
import {SpyChangeDispatcher} from '../spies';
|
||||
|
||||
import {
|
||||
CONST_EXPR,
|
||||
isPresent,
|
||||
isBlank,
|
||||
isNumber,
|
||||
isJsObject,
|
||||
FunctionWrapper,
|
||||
NumberWrapper,
|
||||
normalizeBool
|
||||
} from 'angular2/src/facade/lang';
|
||||
import {CONST_EXPR, isPresent, isBlank, isNumber, isJsObject, FunctionWrapper, NumberWrapper, normalizeBool} from 'angular2/src/facade/lang';
|
||||
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
|
||||
import {MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
|
||||
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
|
||||
|
||||
import {
|
||||
ChangeDispatcher,
|
||||
DehydratedException,
|
||||
DynamicChangeDetector,
|
||||
ChangeDetectionError,
|
||||
BindingRecord,
|
||||
DirectiveRecord,
|
||||
DirectiveIndex,
|
||||
PipeTransform,
|
||||
ChangeDetectionStrategy,
|
||||
WrappedValue,
|
||||
DynamicProtoChangeDetector,
|
||||
ChangeDetectorDefinition,
|
||||
Lexer,
|
||||
Parser,
|
||||
Locals,
|
||||
ProtoChangeDetector
|
||||
} from 'angular2/src/core/change_detection/change_detection';
|
||||
import {ChangeDispatcher, DehydratedException, DynamicChangeDetector, ChangeDetectionError, BindingRecord, DirectiveRecord, DirectiveIndex, PipeTransform, ChangeDetectionStrategy, WrappedValue, DynamicProtoChangeDetector, ChangeDetectorDefinition, Lexer, Parser, Locals, ProtoChangeDetector} from 'angular2/src/core/change_detection/change_detection';
|
||||
|
||||
import {SelectedPipe, Pipes} from 'angular2/src/core/change_detection/pipes';
|
||||
import {JitProtoChangeDetector} from 'angular2/src/core/change_detection/jit_proto_change_detector';
|
||||
@@ -71,8 +34,8 @@ const _DEFAULT_CONTEXT = CONST_EXPR(new Object());
|
||||
*/
|
||||
export function main() {
|
||||
['dynamic', 'JIT', 'Pregen'].forEach(cdType => {
|
||||
if (cdType == "JIT" && IS_DART) return;
|
||||
if (cdType == "Pregen" && !IS_DART) return;
|
||||
if (cdType == 'JIT' && IS_DART) return;
|
||||
if (cdType == 'Pregen' && !IS_DART) return;
|
||||
|
||||
describe(`${cdType} Change Detector`, () => {
|
||||
|
||||
@@ -98,8 +61,8 @@ export function main() {
|
||||
}
|
||||
|
||||
|
||||
function _createChangeDetector(expression: string, context = _DEFAULT_CONTEXT,
|
||||
registry = null, dispatcher = null) {
|
||||
function _createChangeDetector(
|
||||
expression: string, context = _DEFAULT_CONTEXT, registry = null, dispatcher = null) {
|
||||
if (isBlank(dispatcher)) dispatcher = new TestDispatcher();
|
||||
var testDef = getDefinition(expression);
|
||||
var cd = _getChangeDetectorFactory(testDef.cdDef)();
|
||||
@@ -116,8 +79,9 @@ export function main() {
|
||||
describe('short-circuit', () => {
|
||||
it('should support short-circuit for the ternary operator', () => {
|
||||
var address = new Address('Sunnyvale', '94085');
|
||||
expect(_bindSimpleValue('true ? city : zipcode', address))
|
||||
.toEqual(['propName=Sunnyvale']);
|
||||
expect(_bindSimpleValue('true ? city : zipcode', address)).toEqual([
|
||||
'propName=Sunnyvale'
|
||||
]);
|
||||
expect(address.cityGetterCalls).toEqual(1);
|
||||
expect(address.zipCodeGetterCalls).toEqual(0);
|
||||
|
||||
@@ -412,7 +376,7 @@ export function main() {
|
||||
var registry = new FakePipes('pipe', () => new MultiArgPipe());
|
||||
var address = new Address('two');
|
||||
var person = new Person('value', address);
|
||||
var val = _createChangeDetector("name | pipe:'one':address.city", person, registry);
|
||||
var val = _createChangeDetector('name | pipe:\'one\':address.city', person, registry);
|
||||
val.changeDetector.detectChanges();
|
||||
expect(val.dispatcher.loggedValues).toEqual(['value one two default']);
|
||||
});
|
||||
@@ -420,7 +384,8 @@ export function main() {
|
||||
it('should associate pipes right-to-left', () => {
|
||||
var registry = new FakePipes('pipe', () => new MultiArgPipe());
|
||||
var person = new Person('value');
|
||||
var val = _createChangeDetector("name | pipe:'a':'b' | pipe:0:1:2", person, registry);
|
||||
var val =
|
||||
_createChangeDetector('name | pipe:\'a\':\'b\' | pipe:0:1:2', person, registry);
|
||||
val.changeDetector.detectChanges();
|
||||
expect(val.dispatcher.loggedValues).toEqual(['value a b default 0 1 2']);
|
||||
});
|
||||
@@ -489,8 +454,8 @@ export function main() {
|
||||
|
||||
it('should happen directly, without invoking the dispatcher', () => {
|
||||
var val = _createWithoutHydrate('directNoDispatcher');
|
||||
val.changeDetector.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([directive1], []),
|
||||
null);
|
||||
val.changeDetector.hydrate(
|
||||
_DEFAULT_CONTEXT, null, new TestDispatcher([directive1], []), null);
|
||||
val.changeDetector.detectChanges();
|
||||
expect(val.dispatcher.loggedValues).toEqual([]);
|
||||
expect(directive1.a).toEqual(42);
|
||||
@@ -500,8 +465,8 @@ export function main() {
|
||||
describe('ngOnChanges', () => {
|
||||
it('should notify the directive when a group of records changes', () => {
|
||||
var cd = _createWithoutHydrate('groupChanges').changeDetector;
|
||||
cd.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []),
|
||||
null);
|
||||
cd.hydrate(
|
||||
_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), null);
|
||||
cd.detectChanges();
|
||||
expect(directive1.changes).toEqual({'a': 1, 'b': 2});
|
||||
expect(directive2.changes).toEqual({'a': 3});
|
||||
@@ -537,8 +502,8 @@ export function main() {
|
||||
it('should notify the directive after it has been checked the first time', () => {
|
||||
var cd = _createWithoutHydrate('directiveOnInit').changeDetector;
|
||||
|
||||
cd.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []),
|
||||
null);
|
||||
cd.hydrate(
|
||||
_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), null);
|
||||
|
||||
cd.detectChanges();
|
||||
|
||||
@@ -580,7 +545,7 @@ export function main() {
|
||||
try {
|
||||
cd.detectChanges();
|
||||
} catch (e) {
|
||||
throw new BaseException("Second detectChanges() should not have run detection.");
|
||||
throw new BaseException('Second detectChanges() should not have run detection.');
|
||||
}
|
||||
expect(directive3.ngOnInitCalled).toBe(false);
|
||||
});
|
||||
@@ -589,8 +554,8 @@ export function main() {
|
||||
describe('ngAfterContentInit', () => {
|
||||
it('should be called after processing the content children', () => {
|
||||
var cd = _createWithoutHydrate('emptyWithDirectiveRecords').changeDetector;
|
||||
cd.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []),
|
||||
null);
|
||||
cd.hydrate(
|
||||
_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), null);
|
||||
|
||||
cd.detectChanges();
|
||||
|
||||
@@ -628,8 +593,8 @@ export function main() {
|
||||
describe('ngAfterContentChecked', () => {
|
||||
it('should be called after processing all the children', () => {
|
||||
var cd = _createWithoutHydrate('emptyWithDirectiveRecords').changeDetector;
|
||||
cd.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []),
|
||||
null);
|
||||
cd.hydrate(
|
||||
_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), null);
|
||||
|
||||
cd.detectChanges();
|
||||
|
||||
@@ -693,10 +658,10 @@ export function main() {
|
||||
parentDirective =
|
||||
new TestDirective(() => { orderOfOperations.push(parentDirective); });
|
||||
|
||||
parent.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([parentDirective], []),
|
||||
null);
|
||||
child.hydrate(_DEFAULT_CONTEXT, null,
|
||||
new TestDispatcher([directiveInShadowDom], []), null);
|
||||
parent.hydrate(
|
||||
_DEFAULT_CONTEXT, null, new TestDispatcher([parentDirective], []), null);
|
||||
child.hydrate(
|
||||
_DEFAULT_CONTEXT, null, new TestDispatcher([directiveInShadowDom], []), null);
|
||||
|
||||
parent.detectChanges();
|
||||
expect(orderOfOperations).toEqual([parentDirective, directiveInShadowDom]);
|
||||
@@ -707,8 +672,8 @@ export function main() {
|
||||
describe('ngAfterViewInit', () => {
|
||||
it('should be called after processing the view children', () => {
|
||||
var cd = _createWithoutHydrate('emptyWithDirectiveRecords').changeDetector;
|
||||
cd.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []),
|
||||
null);
|
||||
cd.hydrate(
|
||||
_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), null);
|
||||
|
||||
cd.detectChanges();
|
||||
|
||||
@@ -747,8 +712,8 @@ export function main() {
|
||||
describe('ngAfterViewChecked', () => {
|
||||
it('should be called after processing the view children', () => {
|
||||
var cd = _createWithoutHydrate('emptyWithDirectiveRecords').changeDetector;
|
||||
cd.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []),
|
||||
null);
|
||||
cd.hydrate(
|
||||
_DEFAULT_CONTEXT, null, new TestDispatcher([directive1, directive2], []), null);
|
||||
|
||||
cd.detectChanges();
|
||||
|
||||
@@ -812,10 +777,10 @@ export function main() {
|
||||
parentDirective =
|
||||
new TestDirective(null, () => { orderOfOperations.push(parentDirective); });
|
||||
|
||||
parent.hydrate(_DEFAULT_CONTEXT, null, new TestDispatcher([parentDirective], []),
|
||||
null);
|
||||
child.hydrate(_DEFAULT_CONTEXT, null,
|
||||
new TestDispatcher([directiveInShadowDom], []), null);
|
||||
parent.hydrate(
|
||||
_DEFAULT_CONTEXT, null, new TestDispatcher([parentDirective], []), null);
|
||||
child.hydrate(
|
||||
_DEFAULT_CONTEXT, null, new TestDispatcher([directiveInShadowDom], []), null);
|
||||
|
||||
parent.detectChanges();
|
||||
expect(orderOfOperations).toEqual([directiveInShadowDom, parentDirective]);
|
||||
@@ -824,8 +789,9 @@ export function main() {
|
||||
|
||||
describe('ngOnDestroy', () => {
|
||||
it('should be called on dehydration', () => {
|
||||
var cd = _createChangeDetector('emptyWithDirectiveRecords', _DEFAULT_CONTEXT, null,
|
||||
new TestDispatcher([directive1, directive2], []))
|
||||
var cd = _createChangeDetector(
|
||||
'emptyWithDirectiveRecords', _DEFAULT_CONTEXT, null,
|
||||
new TestDispatcher([directive1, directive2], []))
|
||||
.changeDetector;
|
||||
|
||||
cd.dehydrate();
|
||||
@@ -840,7 +806,7 @@ export function main() {
|
||||
});
|
||||
});
|
||||
|
||||
describe("logBindingUpdate", () => {
|
||||
describe('logBindingUpdate', () => {
|
||||
it('should be called for element updates in the dev mode', () => {
|
||||
var person = new Person('bob');
|
||||
var val = _createChangeDetector('name', person);
|
||||
@@ -849,10 +815,11 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should be called for directive updates in the dev mode', () => {
|
||||
var val = _createChangeDetector('directNoDispatcher', _DEFAULT_CONTEXT, null,
|
||||
new TestDispatcher([new TestDirective()], []));
|
||||
var val = _createChangeDetector(
|
||||
'directNoDispatcher', _DEFAULT_CONTEXT, null,
|
||||
new TestDispatcher([new TestDirective()], []));
|
||||
val.changeDetector.detectChanges();
|
||||
expect(val.dispatcher.debugLog).toEqual(["a=42"]);
|
||||
expect(val.dispatcher.debugLog).toEqual(['a=42']);
|
||||
});
|
||||
|
||||
it('should not be called in the prod mode', () => {
|
||||
@@ -869,8 +836,8 @@ export function main() {
|
||||
var directive = new TestDirective();
|
||||
directive.a = 'aaa';
|
||||
|
||||
var val = _createChangeDetector('readingDirectives', _DEFAULT_CONTEXT, null,
|
||||
new TestDispatcher([directive], []));
|
||||
var val = _createChangeDetector(
|
||||
'readingDirectives', _DEFAULT_CONTEXT, null, new TestDispatcher([directive], []));
|
||||
|
||||
val.changeDetector.detectChanges();
|
||||
|
||||
@@ -918,8 +885,9 @@ export function main() {
|
||||
|
||||
it('should handle unexpected errors in the event handler itself', () => {
|
||||
var throwingDispatcher = new SpyChangeDispatcher();
|
||||
throwingDispatcher.spy("getDebugContext")
|
||||
.andCallFake((_, __) => { throw new BaseException('boom'); });
|
||||
throwingDispatcher.spy('getDebugContext').andCallFake((_, __) => {
|
||||
throw new BaseException('boom');
|
||||
});
|
||||
|
||||
var val =
|
||||
_createChangeDetector('invalidFn(1)', _DEFAULT_CONTEXT, null, throwingDispatcher);
|
||||
@@ -946,18 +914,21 @@ export function main() {
|
||||
it('should fall back to a regular field read when the locals map' +
|
||||
'does not have the requested field',
|
||||
() => {
|
||||
expect(_bindSimpleValue('fallbackLocals', new Person('Jim')))
|
||||
.toEqual(['propName=Jim']);
|
||||
expect(_bindSimpleValue('fallbackLocals', new Person('Jim'))).toEqual([
|
||||
'propName=Jim'
|
||||
]);
|
||||
});
|
||||
|
||||
it('should correctly handle nested properties', () => {
|
||||
var address = new Address('Grenoble');
|
||||
var person = new Person('Victor', address);
|
||||
|
||||
expect(_bindSimpleValue('contextNestedPropertyWithLocals', person))
|
||||
.toEqual(['propName=Grenoble']);
|
||||
expect(_bindSimpleValue('localPropertyWithSimilarContext', person))
|
||||
.toEqual(['propName=MTV']);
|
||||
expect(_bindSimpleValue('contextNestedPropertyWithLocals', person)).toEqual([
|
||||
'propName=Grenoble'
|
||||
]);
|
||||
expect(_bindSimpleValue('localPropertyWithSimilarContext', person)).toEqual([
|
||||
'propName=MTV'
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1067,9 +1038,9 @@ export function main() {
|
||||
childDirectiveDetectorOnPush.hydrate(_DEFAULT_CONTEXT, null, null, null);
|
||||
childDirectiveDetectorOnPush.mode = ChangeDetectionStrategy.Checked;
|
||||
|
||||
directives =
|
||||
new TestDispatcher([new TestData(null), new TestData(null)],
|
||||
[childDirectiveDetectorRegular, childDirectiveDetectorOnPush]);
|
||||
directives = new TestDispatcher(
|
||||
[new TestData(null), new TestData(null)],
|
||||
[childDirectiveDetectorRegular, childDirectiveDetectorOnPush]);
|
||||
});
|
||||
|
||||
it('should set the mode to CheckOnce when a binding is updated', () => {
|
||||
@@ -1090,7 +1061,7 @@ export function main() {
|
||||
cd.hydrate(_DEFAULT_CONTEXT, null, directives, null);
|
||||
cd.mode = ChangeDetectionStrategy.Checked;
|
||||
|
||||
cd.handleEvent("event", 0, null);
|
||||
cd.handleEvent('event', 0, null);
|
||||
|
||||
expect(cd.mode).toEqual(ChangeDetectionStrategy.CheckOnce);
|
||||
});
|
||||
@@ -1099,7 +1070,7 @@ export function main() {
|
||||
var cd = _createWithoutHydrate('onPushWithHostEvent').changeDetector;
|
||||
cd.hydrate(_DEFAULT_CONTEXT, null, directives, null);
|
||||
|
||||
cd.handleEvent("host-event", 0, null);
|
||||
cd.handleEvent('host-event', 0, null);
|
||||
|
||||
expect(childDirectiveDetectorOnPush.mode).toEqual(ChangeDetectionStrategy.CheckOnce);
|
||||
});
|
||||
@@ -1177,7 +1148,7 @@ export function main() {
|
||||
|
||||
val.changeDetector.dehydrate();
|
||||
expect(() => {val.changeDetector.detectChanges()})
|
||||
.toThrowErrorWith("Attempt to use a dehydrated detector");
|
||||
.toThrowErrorWith('Attempt to use a dehydrated detector');
|
||||
expect(val.dispatcher.log).toEqual(['propName=Bob']);
|
||||
});
|
||||
});
|
||||
@@ -1214,42 +1185,42 @@ export function main() {
|
||||
var d: TestDirective;
|
||||
|
||||
beforeEach(() => {
|
||||
event = "EVENT";
|
||||
event = 'EVENT';
|
||||
d = new TestDirective();
|
||||
});
|
||||
|
||||
it('should execute events', () => {
|
||||
var val = _createChangeDetector('(event)="onEvent($event)"', d, null);
|
||||
val.changeDetector.handleEvent("event", 0, event);
|
||||
expect(d.event).toEqual("EVENT");
|
||||
val.changeDetector.handleEvent('event', 0, event);
|
||||
expect(d.event).toEqual('EVENT');
|
||||
});
|
||||
|
||||
it('should execute host events', () => {
|
||||
var val = _createWithoutHydrate('(host-event)="onEvent($event)"');
|
||||
val.changeDetector.hydrate(_DEFAULT_CONTEXT, null,
|
||||
new TestDispatcher([d, new TestDirective()], []), null);
|
||||
val.changeDetector.handleEvent("host-event", 0, event);
|
||||
expect(d.event).toEqual("EVENT");
|
||||
val.changeDetector.hydrate(
|
||||
_DEFAULT_CONTEXT, null, new TestDispatcher([d, new TestDirective()], []), null);
|
||||
val.changeDetector.handleEvent('host-event', 0, event);
|
||||
expect(d.event).toEqual('EVENT');
|
||||
});
|
||||
|
||||
it('should support field assignments', () => {
|
||||
var val = _createChangeDetector('(event)="b=a=$event"', d, null);
|
||||
val.changeDetector.handleEvent("event", 0, event);
|
||||
expect(d.a).toEqual("EVENT");
|
||||
expect(d.b).toEqual("EVENT");
|
||||
val.changeDetector.handleEvent('event', 0, event);
|
||||
expect(d.a).toEqual('EVENT');
|
||||
expect(d.b).toEqual('EVENT');
|
||||
});
|
||||
|
||||
it('should support keyed assignments', () => {
|
||||
d.a = ["OLD"];
|
||||
d.a = ['OLD'];
|
||||
var val = _createChangeDetector('(event)="a[0]=$event"', d, null);
|
||||
val.changeDetector.handleEvent("event", 0, event);
|
||||
expect(d.a).toEqual(["EVENT"]);
|
||||
val.changeDetector.handleEvent('event', 0, event);
|
||||
expect(d.a).toEqual(['EVENT']);
|
||||
});
|
||||
|
||||
it('should support chains', () => {
|
||||
d.a = 0;
|
||||
var val = _createChangeDetector('(event)="a=a+1; a=a+1;"', d, null);
|
||||
val.changeDetector.handleEvent("event", 0, event);
|
||||
val.changeDetector.handleEvent('event', 0, event);
|
||||
expect(d.a).toEqual(2);
|
||||
});
|
||||
|
||||
@@ -1262,22 +1233,22 @@ export function main() {
|
||||
|
||||
it('should return false if the event handler returned false', () => {
|
||||
var val = _createChangeDetector('(event)="false"', d, null);
|
||||
var res = val.changeDetector.handleEvent("event", 0, event);
|
||||
var res = val.changeDetector.handleEvent('event', 0, event);
|
||||
expect(res).toBe(false);
|
||||
|
||||
val = _createChangeDetector('(event)="true"', d, null);
|
||||
res = val.changeDetector.handleEvent("event", 0, event);
|
||||
res = val.changeDetector.handleEvent('event', 0, event);
|
||||
expect(res).toBe(true);
|
||||
|
||||
val = _createChangeDetector('(event)="true; false"', d, null);
|
||||
res = val.changeDetector.handleEvent("event", 0, event);
|
||||
res = val.changeDetector.handleEvent('event', 0, event);
|
||||
expect(res).toBe(false);
|
||||
});
|
||||
|
||||
it('should support short-circuiting', () => {
|
||||
d.a = 0;
|
||||
var val = _createChangeDetector('(event)="true ? a = a + 1 : a = a + 1"', d, null);
|
||||
val.changeDetector.handleEvent("event", 0, event);
|
||||
val.changeDetector.handleEvent('event', 0, event);
|
||||
expect(d.a).toEqual(1);
|
||||
});
|
||||
});
|
||||
@@ -1287,8 +1258,9 @@ export function main() {
|
||||
it('should call handleEvent when an output of a directive fires', fakeAsync(() => {
|
||||
var directive1 = new TestDirective();
|
||||
var directive2 = new TestDirective();
|
||||
_createChangeDetector('(host-event)="onEvent(\$event)"', new Object(), null,
|
||||
new TestDispatcher([directive1, directive2]));
|
||||
_createChangeDetector(
|
||||
'(host-event)="onEvent(\$event)"', new Object(), null,
|
||||
new TestDispatcher([directive1, directive2]));
|
||||
ObservableWrapper.callEmit(directive2.eventEmitter, 'EVENT');
|
||||
|
||||
tick();
|
||||
@@ -1299,8 +1271,9 @@ export function main() {
|
||||
it('should ignore events when dehydrated', fakeAsync(() => {
|
||||
var directive1 = new TestDirective();
|
||||
var directive2 = new TestDirective();
|
||||
var cd = _createChangeDetector('(host-event)="onEvent(\$event)"', new Object(), null,
|
||||
new TestDispatcher([directive1, directive2]))
|
||||
var cd = _createChangeDetector(
|
||||
'(host-event)="onEvent(\$event)"', new Object(), null,
|
||||
new TestDispatcher([directive1, directive2]))
|
||||
.changeDetector;
|
||||
cd.dehydrate();
|
||||
ObservableWrapper.callEmit(directive2.eventEmitter, 'EVENT');
|
||||
@@ -1405,8 +1378,9 @@ class TestDirective {
|
||||
event;
|
||||
eventEmitter: EventEmitter<string> = new EventEmitter<string>();
|
||||
|
||||
constructor(public ngAfterContentCheckedSpy = null, public ngAfterViewCheckedSpy = null,
|
||||
public throwOnInit = false) {}
|
||||
constructor(
|
||||
public ngAfterContentCheckedSpy = null, public ngAfterViewCheckedSpy = null,
|
||||
public throwOnInit = false) {}
|
||||
|
||||
onEvent(event) { this.event = event; }
|
||||
|
||||
@@ -1415,7 +1389,7 @@ class TestDirective {
|
||||
ngOnInit() {
|
||||
this.ngOnInitCalled = true;
|
||||
if (this.throwOnInit) {
|
||||
throw "simulated ngOnInit failure";
|
||||
throw 'simulated ngOnInit failure';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1521,8 +1495,8 @@ class TestDispatcher implements ChangeDispatcher {
|
||||
ngAfterViewCheckedCalled: boolean = false;
|
||||
ngOnDestroyCalled: boolean = false;
|
||||
|
||||
constructor(public directives: Array<TestData | TestDirective> = null,
|
||||
public detectors: any[] = null) {
|
||||
constructor(
|
||||
public directives: Array<TestData|TestDirective> = null, public detectors: any[] = null) {
|
||||
if (isBlank(this.directives)) {
|
||||
this.directives = [];
|
||||
}
|
||||
|
||||
@@ -1,20 +1,11 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
|
||||
import {ChangeDetectionUtil} from 'angular2/src/core/change_detection/change_detection_util';
|
||||
|
||||
export function main() {
|
||||
describe("ChangeDetectionUtil", () => {
|
||||
describe("devModeEqual", () => {
|
||||
it("should do the deep comparison of iterables", () => {
|
||||
describe('ChangeDetectionUtil', () => {
|
||||
describe('devModeEqual', () => {
|
||||
it('should do the deep comparison of iterables', () => {
|
||||
expect(ChangeDetectionUtil.devModeEqual([['one']], [['one']])).toBe(true);
|
||||
expect(ChangeDetectionUtil.devModeEqual(['one'], ['one', 'two'])).toBe(false);
|
||||
expect(ChangeDetectionUtil.devModeEqual(['one', 'two'], ['one'])).toBe(false);
|
||||
@@ -24,35 +15,35 @@ export function main() {
|
||||
expect(ChangeDetectionUtil.devModeEqual(new Object(), ['one'])).toBe(false);
|
||||
});
|
||||
|
||||
it("should compare primitive numbers", () => {
|
||||
it('should compare primitive numbers', () => {
|
||||
expect(ChangeDetectionUtil.devModeEqual(1, 1)).toBe(true);
|
||||
expect(ChangeDetectionUtil.devModeEqual(1, 2)).toBe(false);
|
||||
expect(ChangeDetectionUtil.devModeEqual(new Object(), 2)).toBe(false);
|
||||
expect(ChangeDetectionUtil.devModeEqual(1, new Object())).toBe(false);
|
||||
});
|
||||
|
||||
it("should compare primitive strings", () => {
|
||||
it('should compare primitive strings', () => {
|
||||
expect(ChangeDetectionUtil.devModeEqual('one', 'one')).toBe(true);
|
||||
expect(ChangeDetectionUtil.devModeEqual('one', 'two')).toBe(false);
|
||||
expect(ChangeDetectionUtil.devModeEqual(new Object(), 'one')).toBe(false);
|
||||
expect(ChangeDetectionUtil.devModeEqual('one', new Object())).toBe(false);
|
||||
});
|
||||
|
||||
it("should compare primitive booleans", () => {
|
||||
it('should compare primitive booleans', () => {
|
||||
expect(ChangeDetectionUtil.devModeEqual(true, true)).toBe(true);
|
||||
expect(ChangeDetectionUtil.devModeEqual(true, false)).toBe(false);
|
||||
expect(ChangeDetectionUtil.devModeEqual(new Object(), true)).toBe(false);
|
||||
expect(ChangeDetectionUtil.devModeEqual(true, new Object())).toBe(false);
|
||||
});
|
||||
|
||||
it("should compare null", () => {
|
||||
it('should compare null', () => {
|
||||
expect(ChangeDetectionUtil.devModeEqual(null, null)).toBe(true);
|
||||
expect(ChangeDetectionUtil.devModeEqual(null, 1)).toBe(false);
|
||||
expect(ChangeDetectionUtil.devModeEqual(new Object(), null)).toBe(false);
|
||||
expect(ChangeDetectionUtil.devModeEqual(null, new Object())).toBe(false);
|
||||
});
|
||||
|
||||
it("should return true for other objects", () => {
|
||||
it('should return true for other objects', () => {
|
||||
expect(ChangeDetectionUtil.devModeEqual(new Object(), new Object())).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,4 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
import {isBlank} from 'angular2/src/facade/lang';
|
||||
|
||||
import {coalesce} from 'angular2/src/core/change_detection/coalesce';
|
||||
@@ -15,92 +6,91 @@ import {RecordType, ProtoRecord} from 'angular2/src/core/change_detection/proto_
|
||||
import {DirectiveIndex} from 'angular2/src/core/change_detection/directive_record';
|
||||
|
||||
export function main() {
|
||||
function r(funcOrValue, args, contextIndex, selfIndex,
|
||||
{lastInBinding, mode, name, directiveIndex, argumentToPureFunction, fixedArgs}: {
|
||||
lastInBinding?: any,
|
||||
mode?: any,
|
||||
name?: any,
|
||||
directiveIndex?: any,
|
||||
argumentToPureFunction?: boolean,
|
||||
fixedArgs?: any[]
|
||||
} = {}) {
|
||||
function r(
|
||||
funcOrValue, args, contextIndex, selfIndex,
|
||||
{lastInBinding, mode, name, directiveIndex, argumentToPureFunction, fixedArgs}: {
|
||||
lastInBinding?: any,
|
||||
mode?: any,
|
||||
name?: any,
|
||||
directiveIndex?: any,
|
||||
argumentToPureFunction?: boolean,
|
||||
fixedArgs?: any[]
|
||||
} = {}) {
|
||||
if (isBlank(lastInBinding)) lastInBinding = false;
|
||||
if (isBlank(mode)) mode = RecordType.PropertyRead;
|
||||
if (isBlank(name)) name = "name";
|
||||
if (isBlank(name)) name = 'name';
|
||||
if (isBlank(directiveIndex)) directiveIndex = null;
|
||||
if (isBlank(argumentToPureFunction)) argumentToPureFunction = false;
|
||||
if (isBlank(fixedArgs)) fixedArgs = null;
|
||||
|
||||
return new ProtoRecord(mode, name, funcOrValue, args, fixedArgs, contextIndex, directiveIndex,
|
||||
selfIndex, null, lastInBinding, false, argumentToPureFunction, false, 0);
|
||||
return new ProtoRecord(
|
||||
mode, name, funcOrValue, args, fixedArgs, contextIndex, directiveIndex, selfIndex, null,
|
||||
lastInBinding, false, argumentToPureFunction, false, 0);
|
||||
}
|
||||
|
||||
describe("change detection - coalesce", () => {
|
||||
it("should work with an empty list", () => { expect(coalesce([])).toEqual([]); });
|
||||
describe('change detection - coalesce', () => {
|
||||
it('should work with an empty list', () => { expect(coalesce([])).toEqual([]); });
|
||||
|
||||
it("should remove non-terminal duplicate records and update the context indices referencing them",
|
||||
it('should remove non-terminal duplicate records and update the context indices referencing them',
|
||||
() => {
|
||||
var rs = coalesce(
|
||||
[r("user", [], 0, 1), r("first", [], 1, 2), r("user", [], 0, 3), r("last", [], 3, 4)]);
|
||||
[r('user', [], 0, 1), r('first', [], 1, 2), r('user', [], 0, 3), r('last', [], 3, 4)]);
|
||||
|
||||
expect(rs).toEqual([r("user", [], 0, 1), r("first", [], 1, 2), r("last", [], 1, 3)]);
|
||||
expect(rs).toEqual([r('user', [], 0, 1), r('first', [], 1, 2), r('last', [], 1, 3)]);
|
||||
});
|
||||
|
||||
it("should update indices of other records", () => {
|
||||
it('should update indices of other records', () => {
|
||||
var rs = coalesce(
|
||||
[r("dup", [], 0, 1), r("dup", [], 0, 2), r("user", [], 0, 3), r("first", [3], 3, 4)]);
|
||||
[r('dup', [], 0, 1), r('dup', [], 0, 2), r('user', [], 0, 3), r('first', [3], 3, 4)]);
|
||||
|
||||
expect(rs).toEqual([r("dup", [], 0, 1), r("user", [], 0, 2), r("first", [2], 2, 3)]);
|
||||
expect(rs).toEqual([r('dup', [], 0, 1), r('user', [], 0, 2), r('first', [2], 2, 3)]);
|
||||
});
|
||||
|
||||
it("should remove non-terminal duplicate records and update the args indices referencing them",
|
||||
it('should remove non-terminal duplicate records and update the args indices referencing them',
|
||||
() => {
|
||||
var rs = coalesce([
|
||||
r("user1", [], 0, 1),
|
||||
r("user2", [], 0, 2),
|
||||
r("hi", [1], 0, 3),
|
||||
r("hi", [1], 0, 4),
|
||||
r("hi", [2], 0, 5)
|
||||
r('user1', [], 0, 1), r('user2', [], 0, 2), r('hi', [1], 0, 3), r('hi', [1], 0, 4),
|
||||
r('hi', [2], 0, 5)
|
||||
]);
|
||||
|
||||
expect(rs).toEqual(
|
||||
[r("user1", [], 0, 1), r("user2", [], 0, 2), r("hi", [1], 0, 3), r("hi", [2], 0, 4)]);
|
||||
[r('user1', [], 0, 1), r('user2', [], 0, 2), r('hi', [1], 0, 3), r('hi', [2], 0, 4)]);
|
||||
});
|
||||
|
||||
it("should replace duplicate terminal records with self records", () => {
|
||||
it('should replace duplicate terminal records with self records', () => {
|
||||
var rs = coalesce(
|
||||
[r("user", [], 0, 1, {lastInBinding: true}), r("user", [], 0, 2, {lastInBinding: true})]);
|
||||
[r('user', [], 0, 1, {lastInBinding: true}), r('user', [], 0, 2, {lastInBinding: true})]);
|
||||
|
||||
expect(rs[1]).toEqual(new ProtoRecord(RecordType.Self, "self", null, [], null, 1, null, 2,
|
||||
null, true, false, false, false, 0));
|
||||
expect(rs[1]).toEqual(new ProtoRecord(
|
||||
RecordType.Self, 'self', null, [], null, 1, null, 2, null, true, false, false, false, 0));
|
||||
});
|
||||
|
||||
it("should set referencedBySelf", () => {
|
||||
it('should set referencedBySelf', () => {
|
||||
var rs = coalesce(
|
||||
[r("user", [], 0, 1, {lastInBinding: true}), r("user", [], 0, 2, {lastInBinding: true})]);
|
||||
[r('user', [], 0, 1, {lastInBinding: true}), r('user', [], 0, 2, {lastInBinding: true})]);
|
||||
|
||||
expect(rs[0].referencedBySelf).toBeTruthy();
|
||||
});
|
||||
|
||||
it("should not coalesce directive lifecycle records", () => {
|
||||
it('should not coalesce directive lifecycle records', () => {
|
||||
var rs = coalesce([
|
||||
r("ngDoCheck", [], 0, 1, {mode: RecordType.DirectiveLifecycle}),
|
||||
r("ngDoCheck", [], 0, 1, {mode: RecordType.DirectiveLifecycle})
|
||||
r('ngDoCheck', [], 0, 1, {mode: RecordType.DirectiveLifecycle}),
|
||||
r('ngDoCheck', [], 0, 1, {mode: RecordType.DirectiveLifecycle})
|
||||
]);
|
||||
|
||||
expect(rs.length).toEqual(2);
|
||||
});
|
||||
|
||||
it("should not coalesce protos with different names but same value", () => {
|
||||
it('should not coalesce protos with different names but same value', () => {
|
||||
var nullFunc = () => {};
|
||||
var rs = coalesce([
|
||||
r(nullFunc, [], 0, 1, {name: "foo"}),
|
||||
r(nullFunc, [], 0, 1, {name: "bar"}),
|
||||
r(nullFunc, [], 0, 1, {name: 'foo'}),
|
||||
r(nullFunc, [], 0, 1, {name: 'bar'}),
|
||||
]);
|
||||
expect(rs.length).toEqual(2);
|
||||
});
|
||||
|
||||
it("should not coalesce protos with the same context index but different directive indices",
|
||||
it('should not coalesce protos with the same context index but different directive indices',
|
||||
() => {
|
||||
var nullFunc = () => {};
|
||||
var rs = coalesce([
|
||||
@@ -114,35 +104,32 @@ export function main() {
|
||||
|
||||
it('should preserve the argumentToPureFunction property', () => {
|
||||
var rs = coalesce([
|
||||
r("user", [], 0, 1),
|
||||
r("user", [], 0, 2, {argumentToPureFunction: true}),
|
||||
r("user", [], 0, 3),
|
||||
r("name", [], 3, 4)
|
||||
r('user', [], 0, 1), r('user', [], 0, 2, {argumentToPureFunction: true}),
|
||||
r('user', [], 0, 3), r('name', [], 3, 4)
|
||||
]);
|
||||
expect(rs)
|
||||
.toEqual([r("user", [], 0, 1, {argumentToPureFunction: true}), r("name", [], 1, 2)]);
|
||||
expect(rs).toEqual(
|
||||
[r('user', [], 0, 1, {argumentToPureFunction: true}), r('name', [], 1, 2)]);
|
||||
});
|
||||
|
||||
it('should preserve the argumentToPureFunction property (the original record)', () => {
|
||||
var rs = coalesce([
|
||||
r("user", [], 0, 1, {argumentToPureFunction: true}),
|
||||
r("user", [], 0, 2),
|
||||
r("name", [], 2, 3)
|
||||
r('user', [], 0, 1, {argumentToPureFunction: true}), r('user', [], 0, 2),
|
||||
r('name', [], 2, 3)
|
||||
]);
|
||||
expect(rs)
|
||||
.toEqual([r("user", [], 0, 1, {argumentToPureFunction: true}), r("name", [], 1, 2)]);
|
||||
expect(rs).toEqual(
|
||||
[r('user', [], 0, 1, {argumentToPureFunction: true}), r('name', [], 1, 2)]);
|
||||
});
|
||||
|
||||
describe('short-circuit', () => {
|
||||
it('should not use short-circuitable records', () => {
|
||||
var records = [
|
||||
r("sknot", [], 0, 1, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [3]}),
|
||||
r("a", [], 0, 2),
|
||||
r("sk", [], 0, 3, {mode: RecordType.SkipRecords, fixedArgs: [4]}),
|
||||
r("b", [], 0, 4),
|
||||
r("cond", [2, 4], 0, 5),
|
||||
r("a", [], 0, 6),
|
||||
r("b", [], 0, 7),
|
||||
r('sknot', [], 0, 1, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [3]}),
|
||||
r('a', [], 0, 2),
|
||||
r('sk', [], 0, 3, {mode: RecordType.SkipRecords, fixedArgs: [4]}),
|
||||
r('b', [], 0, 4),
|
||||
r('cond', [2, 4], 0, 5),
|
||||
r('a', [], 0, 6),
|
||||
r('b', [], 0, 7),
|
||||
];
|
||||
|
||||
expect(coalesce(records)).toEqual(records);
|
||||
@@ -150,18 +137,18 @@ export function main() {
|
||||
|
||||
it('should not use short-circuitable records from nested short-circuits', () => {
|
||||
var records = [
|
||||
r("sknot outer", [], 0, 1, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [7]}),
|
||||
r("sknot inner", [], 0, 2, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [4]}),
|
||||
r("a", [], 0, 3),
|
||||
r("sk inner", [], 0, 4, {mode: RecordType.SkipRecords, fixedArgs: [5]}),
|
||||
r("b", [], 0, 5),
|
||||
r("cond-inner", [3, 5], 0, 6),
|
||||
r("sk outer", [], 0, 7, {mode: RecordType.SkipRecords, fixedArgs: [8]}),
|
||||
r("c", [], 0, 8),
|
||||
r("cond-outer", [6, 8], 0, 9),
|
||||
r("a", [], 0, 10),
|
||||
r("b", [], 0, 11),
|
||||
r("c", [], 0, 12),
|
||||
r('sknot outer', [], 0, 1, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [7]}),
|
||||
r('sknot inner', [], 0, 2, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [4]}),
|
||||
r('a', [], 0, 3),
|
||||
r('sk inner', [], 0, 4, {mode: RecordType.SkipRecords, fixedArgs: [5]}),
|
||||
r('b', [], 0, 5),
|
||||
r('cond-inner', [3, 5], 0, 6),
|
||||
r('sk outer', [], 0, 7, {mode: RecordType.SkipRecords, fixedArgs: [8]}),
|
||||
r('c', [], 0, 8),
|
||||
r('cond-outer', [6, 8], 0, 9),
|
||||
r('a', [], 0, 10),
|
||||
r('b', [], 0, 11),
|
||||
r('c', [], 0, 12),
|
||||
];
|
||||
|
||||
expect(coalesce(records)).toEqual(records);
|
||||
@@ -169,65 +156,65 @@ export function main() {
|
||||
|
||||
it('should collapse the true branch', () => {
|
||||
var rs = coalesce([
|
||||
r("a", [], 0, 1),
|
||||
r("sknot", [], 0, 2, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [4]}),
|
||||
r("a", [], 0, 3),
|
||||
r("sk", [], 0, 4, {mode: RecordType.SkipRecords, fixedArgs: [6]}),
|
||||
r("a", [], 0, 5),
|
||||
r("b", [], 5, 6),
|
||||
r("cond", [3, 6], 0, 7),
|
||||
r('a', [], 0, 1),
|
||||
r('sknot', [], 0, 2, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [4]}),
|
||||
r('a', [], 0, 3),
|
||||
r('sk', [], 0, 4, {mode: RecordType.SkipRecords, fixedArgs: [6]}),
|
||||
r('a', [], 0, 5),
|
||||
r('b', [], 5, 6),
|
||||
r('cond', [3, 6], 0, 7),
|
||||
]);
|
||||
|
||||
expect(rs).toEqual([
|
||||
r("a", [], 0, 1),
|
||||
r("sknot", [], 0, 2, {mode: RecordType.SkipRecordsIf, fixedArgs: [3]}),
|
||||
r("b", [], 1, 3),
|
||||
r("cond", [1, 3], 0, 4),
|
||||
r('a', [], 0, 1),
|
||||
r('sknot', [], 0, 2, {mode: RecordType.SkipRecordsIf, fixedArgs: [3]}),
|
||||
r('b', [], 1, 3),
|
||||
r('cond', [1, 3], 0, 4),
|
||||
]);
|
||||
});
|
||||
|
||||
it('should collapse the false branch', () => {
|
||||
var rs = coalesce([
|
||||
r("a", [], 0, 1),
|
||||
r("sknot", [], 0, 2, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [5]}),
|
||||
r("a", [], 0, 3),
|
||||
r("b", [], 3, 4),
|
||||
r("sk", [], 0, 5, {mode: RecordType.SkipRecords, fixedArgs: [6]}),
|
||||
r("a", [], 0, 6),
|
||||
r("cond", [4, 6], 0, 7),
|
||||
r('a', [], 0, 1),
|
||||
r('sknot', [], 0, 2, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [5]}),
|
||||
r('a', [], 0, 3),
|
||||
r('b', [], 3, 4),
|
||||
r('sk', [], 0, 5, {mode: RecordType.SkipRecords, fixedArgs: [6]}),
|
||||
r('a', [], 0, 6),
|
||||
r('cond', [4, 6], 0, 7),
|
||||
]);
|
||||
|
||||
expect(rs).toEqual([
|
||||
r("a", [], 0, 1),
|
||||
r("sknot", [], 0, 2, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [3]}),
|
||||
r("b", [], 1, 3),
|
||||
r("cond", [3, 1], 0, 4),
|
||||
r('a', [], 0, 1),
|
||||
r('sknot', [], 0, 2, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [3]}),
|
||||
r('b', [], 1, 3),
|
||||
r('cond', [3, 1], 0, 4),
|
||||
]);
|
||||
});
|
||||
|
||||
it('should optimize skips', () => {
|
||||
var rs = coalesce([
|
||||
// skipIfNot(1) + skip(N) -> skipIf(+N)
|
||||
r("sknot", [], 0, 1, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [2]}),
|
||||
r("sk", [], 0, 2, {mode: RecordType.SkipRecords, fixedArgs: [3]}),
|
||||
r("a", [], 0, 3),
|
||||
r('sknot', [], 0, 1, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [2]}),
|
||||
r('sk', [], 0, 2, {mode: RecordType.SkipRecords, fixedArgs: [3]}),
|
||||
r('a', [], 0, 3),
|
||||
// skipIf(1) + skip(N) -> skipIfNot(N)
|
||||
r("skif", [], 0, 4, {mode: RecordType.SkipRecordsIf, fixedArgs: [5]}),
|
||||
r("sk", [], 0, 5, {mode: RecordType.SkipRecords, fixedArgs: [6]}),
|
||||
r("b", [], 0, 6),
|
||||
r('skif', [], 0, 4, {mode: RecordType.SkipRecordsIf, fixedArgs: [5]}),
|
||||
r('sk', [], 0, 5, {mode: RecordType.SkipRecords, fixedArgs: [6]}),
|
||||
r('b', [], 0, 6),
|
||||
// remove empty skips
|
||||
r("sknot", [], 0, 7, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [7]}),
|
||||
r("skif", [], 0, 8, {mode: RecordType.SkipRecordsIf, fixedArgs: [8]}),
|
||||
r("sk", [], 0, 9, {mode: RecordType.SkipRecords, fixedArgs: [9]}),
|
||||
r("end", [], 0, 10),
|
||||
r('sknot', [], 0, 7, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [7]}),
|
||||
r('skif', [], 0, 8, {mode: RecordType.SkipRecordsIf, fixedArgs: [8]}),
|
||||
r('sk', [], 0, 9, {mode: RecordType.SkipRecords, fixedArgs: [9]}),
|
||||
r('end', [], 0, 10),
|
||||
]);
|
||||
|
||||
expect(rs).toEqual([
|
||||
r("sknot", [], 0, 1, {mode: RecordType.SkipRecordsIf, fixedArgs: [2]}),
|
||||
r("a", [], 0, 2),
|
||||
r("skif", [], 0, 3, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [4]}),
|
||||
r("b", [], 0, 4),
|
||||
r("end", [], 0, 5),
|
||||
r('sknot', [], 0, 1, {mode: RecordType.SkipRecordsIf, fixedArgs: [2]}),
|
||||
r('a', [], 0, 2),
|
||||
r('skif', [], 0, 3, {mode: RecordType.SkipRecordsIfNot, fixedArgs: [4]}),
|
||||
r('b', [], 0, 4),
|
||||
r('end', [], 0, 5),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
+153
-182
@@ -1,17 +1,5 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {
|
||||
DefaultIterableDiffer,
|
||||
DefaultIterableDifferFactory
|
||||
} from 'angular2/src/core/change_detection/differs/default_iterable_differ';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
import {DefaultIterableDiffer, DefaultIterableDifferFactory} from 'angular2/src/core/change_detection/differs/default_iterable_differ';
|
||||
|
||||
import {NumberWrapper} from 'angular2/src/facade/lang';
|
||||
import {ListWrapper} from 'angular2/src/facade/collection';
|
||||
@@ -54,19 +42,19 @@ export function main() {
|
||||
|
||||
l.list = [1];
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(
|
||||
iterableChangesAsString({collection: ['1[null->0]'], additions: ['1[null->0]']}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['1[null->0]'],
|
||||
additions: ['1[null->0]']
|
||||
}));
|
||||
|
||||
l.list = [2, 1];
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['2[null->0]', '1[0->1]'],
|
||||
previous: ['1[0->1]'],
|
||||
additions: ['2[null->0]'],
|
||||
moves: ['1[0->1]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['2[null->0]', '1[0->1]'],
|
||||
previous: ['1[0->1]'],
|
||||
additions: ['2[null->0]'],
|
||||
moves: ['1[0->1]']
|
||||
}));
|
||||
});
|
||||
|
||||
it('should detect additions', () => {
|
||||
@@ -76,9 +64,10 @@ export function main() {
|
||||
|
||||
l.push('a');
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(
|
||||
iterableChangesAsString({collection: ['a[null->0]'], additions: ['a[null->0]']}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['a[null->0]'],
|
||||
additions: ['a[null->0]']
|
||||
}));
|
||||
|
||||
l.push('b');
|
||||
differ.check(l);
|
||||
@@ -93,23 +82,21 @@ export function main() {
|
||||
|
||||
l = [1, 0];
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['1[null->0]', '0[0->1]'],
|
||||
previous: ['0[0->1]'],
|
||||
additions: ['1[null->0]'],
|
||||
moves: ['0[0->1]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['1[null->0]', '0[0->1]'],
|
||||
previous: ['0[0->1]'],
|
||||
additions: ['1[null->0]'],
|
||||
moves: ['0[0->1]']
|
||||
}));
|
||||
|
||||
l = [2, 1, 0];
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['2[null->0]', '1[0->1]', '0[1->2]'],
|
||||
previous: ['1[0->1]', '0[1->2]'],
|
||||
additions: ['2[null->0]'],
|
||||
moves: ['1[0->1]', '0[1->2]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['2[null->0]', '1[0->1]', '0[1->2]'],
|
||||
previous: ['1[0->1]', '0[1->2]'],
|
||||
additions: ['2[null->0]'],
|
||||
moves: ['1[0->1]', '0[1->2]']
|
||||
}));
|
||||
});
|
||||
|
||||
it('should handle swapping element', () => {
|
||||
@@ -120,12 +107,11 @@ export function main() {
|
||||
l.push(2);
|
||||
l.push(1);
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['2[1->0]', '1[0->1]'],
|
||||
previous: ['1[0->1]', '2[1->0]'],
|
||||
moves: ['2[1->0]', '1[0->1]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['2[1->0]', '1[0->1]'],
|
||||
previous: ['1[0->1]', '2[1->0]'],
|
||||
moves: ['2[1->0]', '1[0->1]']
|
||||
}));
|
||||
});
|
||||
|
||||
it('should handle incremental swapping element', () => {
|
||||
@@ -135,22 +121,20 @@ export function main() {
|
||||
ListWrapper.removeAt(l, 1);
|
||||
ListWrapper.insert(l, 0, 'b');
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['b[1->0]', 'a[0->1]', 'c'],
|
||||
previous: ['a[0->1]', 'b[1->0]', 'c'],
|
||||
moves: ['b[1->0]', 'a[0->1]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['b[1->0]', 'a[0->1]', 'c'],
|
||||
previous: ['a[0->1]', 'b[1->0]', 'c'],
|
||||
moves: ['b[1->0]', 'a[0->1]']
|
||||
}));
|
||||
|
||||
ListWrapper.removeAt(l, 1);
|
||||
l.push('a');
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['b', 'c[2->1]', 'a[1->2]'],
|
||||
previous: ['b', 'a[1->2]', 'c[2->1]'],
|
||||
moves: ['c[2->1]', 'a[1->2]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['b', 'c[2->1]', 'a[1->2]'],
|
||||
previous: ['b', 'a[1->2]', 'c[2->1]'],
|
||||
moves: ['c[2->1]', 'a[1->2]']
|
||||
}));
|
||||
});
|
||||
|
||||
it('should detect changes in list', () => {
|
||||
@@ -159,9 +143,10 @@ export function main() {
|
||||
|
||||
l.push('a');
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(
|
||||
iterableChangesAsString({collection: ['a[null->0]'], additions: ['a[null->0]']}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['a[null->0]'],
|
||||
additions: ['a[null->0]']
|
||||
}));
|
||||
|
||||
l.push('b');
|
||||
differ.check(l);
|
||||
@@ -172,22 +157,20 @@ export function main() {
|
||||
l.push('c');
|
||||
l.push('d');
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['a', 'b', 'c[null->2]', 'd[null->3]'],
|
||||
previous: ['a', 'b'],
|
||||
additions: ['c[null->2]', 'd[null->3]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['a', 'b', 'c[null->2]', 'd[null->3]'],
|
||||
previous: ['a', 'b'],
|
||||
additions: ['c[null->2]', 'd[null->3]']
|
||||
}));
|
||||
|
||||
ListWrapper.removeAt(l, 2);
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['a', 'b', 'd[3->2]'],
|
||||
previous: ['a', 'b', 'c[2->null]', 'd[3->2]'],
|
||||
moves: ['d[3->2]'],
|
||||
removals: ['c[2->null]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['a', 'b', 'd[3->2]'],
|
||||
previous: ['a', 'b', 'c[2->null]', 'd[3->2]'],
|
||||
moves: ['d[3->2]'],
|
||||
removals: ['c[2->null]']
|
||||
}));
|
||||
|
||||
ListWrapper.clear(l);
|
||||
l.push('d');
|
||||
@@ -195,13 +178,12 @@ export function main() {
|
||||
l.push('b');
|
||||
l.push('a');
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['d[2->0]', 'c[null->1]', 'b[1->2]', 'a[0->3]'],
|
||||
previous: ['a[0->3]', 'b[1->2]', 'd[2->0]'],
|
||||
additions: ['c[null->1]'],
|
||||
moves: ['d[2->0]', 'b[1->2]', 'a[0->3]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['d[2->0]', 'c[null->1]', 'b[1->2]', 'a[0->3]'],
|
||||
previous: ['a[0->3]', 'b[1->2]', 'd[2->0]'],
|
||||
additions: ['c[null->1]'],
|
||||
moves: ['d[2->0]', 'b[1->2]', 'a[0->3]']
|
||||
}));
|
||||
});
|
||||
|
||||
it('should test string by value rather than by reference (Dart)', () => {
|
||||
@@ -220,9 +202,10 @@ export function main() {
|
||||
let l = [NumberWrapper.NaN];
|
||||
differ.check(l);
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString(
|
||||
{collection: [NumberWrapper.NaN], previous: [NumberWrapper.NaN]}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: [NumberWrapper.NaN],
|
||||
previous: [NumberWrapper.NaN]
|
||||
}));
|
||||
});
|
||||
|
||||
it('should detect [NaN] moves', () => {
|
||||
@@ -231,13 +214,12 @@ export function main() {
|
||||
|
||||
ListWrapper.insert<any>(l, 0, 'foo');
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['foo[null->0]', 'NaN[0->1]', 'NaN[1->2]'],
|
||||
previous: ['NaN[0->1]', 'NaN[1->2]'],
|
||||
additions: ['foo[null->0]'],
|
||||
moves: ['NaN[0->1]', 'NaN[1->2]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['foo[null->0]', 'NaN[0->1]', 'NaN[1->2]'],
|
||||
previous: ['NaN[0->1]', 'NaN[1->2]'],
|
||||
additions: ['foo[null->0]'],
|
||||
moves: ['NaN[0->1]', 'NaN[1->2]']
|
||||
}));
|
||||
});
|
||||
|
||||
it('should remove and add same item', () => {
|
||||
@@ -246,23 +228,21 @@ export function main() {
|
||||
|
||||
ListWrapper.removeAt(l, 1);
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['a', 'c[2->1]'],
|
||||
previous: ['a', 'b[1->null]', 'c[2->1]'],
|
||||
moves: ['c[2->1]'],
|
||||
removals: ['b[1->null]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['a', 'c[2->1]'],
|
||||
previous: ['a', 'b[1->null]', 'c[2->1]'],
|
||||
moves: ['c[2->1]'],
|
||||
removals: ['b[1->null]']
|
||||
}));
|
||||
|
||||
ListWrapper.insert(l, 1, 'b');
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['a', 'b[null->1]', 'c[1->2]'],
|
||||
previous: ['a', 'c[1->2]'],
|
||||
additions: ['b[null->1]'],
|
||||
moves: ['c[1->2]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['a', 'b[null->1]', 'c[1->2]'],
|
||||
previous: ['a', 'c[1->2]'],
|
||||
additions: ['b[null->1]'],
|
||||
moves: ['c[1->2]']
|
||||
}));
|
||||
});
|
||||
|
||||
|
||||
@@ -272,13 +252,12 @@ export function main() {
|
||||
|
||||
ListWrapper.removeAt(l, 0);
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['a', 'a', 'b[3->2]', 'b[4->3]'],
|
||||
previous: ['a', 'a', 'a[2->null]', 'b[3->2]', 'b[4->3]'],
|
||||
moves: ['b[3->2]', 'b[4->3]'],
|
||||
removals: ['a[2->null]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['a', 'a', 'b[3->2]', 'b[4->3]'],
|
||||
previous: ['a', 'a', 'a[2->null]', 'b[3->2]', 'b[4->3]'],
|
||||
moves: ['b[3->2]', 'b[4->3]'],
|
||||
removals: ['a[2->null]']
|
||||
}));
|
||||
});
|
||||
|
||||
it('should support insertions/moves', () => {
|
||||
@@ -287,13 +266,12 @@ export function main() {
|
||||
|
||||
ListWrapper.insert(l, 0, 'b');
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['b[2->0]', 'a[0->1]', 'a[1->2]', 'b', 'b[null->4]'],
|
||||
previous: ['a[0->1]', 'a[1->2]', 'b[2->0]', 'b'],
|
||||
additions: ['b[null->4]'],
|
||||
moves: ['b[2->0]', 'a[0->1]', 'a[1->2]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['b[2->0]', 'a[0->1]', 'a[1->2]', 'b', 'b[null->4]'],
|
||||
previous: ['a[0->1]', 'a[1->2]', 'b[2->0]', 'b'],
|
||||
additions: ['b[null->4]'],
|
||||
moves: ['b[2->0]', 'a[0->1]', 'a[1->2]']
|
||||
}));
|
||||
});
|
||||
|
||||
it('should not report unnecessary moves', () => {
|
||||
@@ -305,12 +283,11 @@ export function main() {
|
||||
l.push('a');
|
||||
l.push('c');
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['b[1->0]', 'a[0->1]', 'c'],
|
||||
previous: ['a[0->1]', 'b[1->0]', 'c'],
|
||||
moves: ['b[1->0]', 'a[0->1]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['b[1->0]', 'a[0->1]', 'c'],
|
||||
previous: ['a[0->1]', 'b[1->0]', 'c'],
|
||||
moves: ['b[1->0]', 'a[0->1]']
|
||||
}));
|
||||
});
|
||||
|
||||
it('should not diff immutable collections if they are the same', () => {
|
||||
@@ -325,9 +302,10 @@ export function main() {
|
||||
|
||||
differ.check(l1);
|
||||
expect(trackByCount).toBe(1);
|
||||
expect(differ.toString())
|
||||
.toEqual(
|
||||
iterableChangesAsString({collection: ['1[null->0]'], additions: ['1[null->0]']}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['1[null->0]'],
|
||||
additions: ['1[null->0]']
|
||||
}));
|
||||
|
||||
|
||||
trackByCount = 0;
|
||||
@@ -344,8 +322,9 @@ export function main() {
|
||||
});
|
||||
|
||||
describe('diff', () => {
|
||||
it('should return self when there is a change',
|
||||
() => { expect(differ.diff(['a', 'b'])).toBe(differ); });
|
||||
it('should return self when there is a change', () => {
|
||||
expect(differ.diff(['a', 'b'])).toBe(differ);
|
||||
});
|
||||
|
||||
it('should return null when there is no change', () => {
|
||||
differ.diff(['a', 'b']);
|
||||
@@ -354,15 +333,14 @@ export function main() {
|
||||
|
||||
it('should treat null as an empty list', () => {
|
||||
differ.diff(['a', 'b']);
|
||||
expect(differ.diff(null).toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
previous: ['a[0->null]', 'b[1->null]'],
|
||||
removals: ['a[0->null]', 'b[1->null]']
|
||||
}));
|
||||
expect(differ.diff(null).toString()).toEqual(iterableChangesAsString({
|
||||
previous: ['a[0->null]', 'b[1->null]'],
|
||||
removals: ['a[0->null]', 'b[1->null]']
|
||||
}));
|
||||
});
|
||||
|
||||
it('should throw when given an invalid collection', () => {
|
||||
expect(() => differ.diff("invalid")).toThrowErrorWith("Error trying to diff 'invalid'");
|
||||
expect(() => differ.diff('invalid')).toThrowErrorWith('Error trying to diff \'invalid\'');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -385,20 +363,18 @@ export function main() {
|
||||
it('should treat seen records as identity changes, not additions', () => {
|
||||
let l = buildItemList(['a', 'b', 'c']);
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: [`{id: a}[null->0]`, `{id: b}[null->1]`, `{id: c}[null->2]`],
|
||||
additions: [`{id: a}[null->0]`, `{id: b}[null->1]`, `{id: c}[null->2]`]
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: [`{id: a}[null->0]`, `{id: b}[null->1]`, `{id: c}[null->2]`],
|
||||
additions: [`{id: a}[null->0]`, `{id: b}[null->1]`, `{id: c}[null->2]`]
|
||||
}));
|
||||
|
||||
l = buildItemList(['a', 'b', 'c']);
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: [`{id: a}`, `{id: b}`, `{id: c}`],
|
||||
identityChanges: [`{id: a}`, `{id: b}`, `{id: c}`],
|
||||
previous: [`{id: a}`, `{id: b}`, `{id: c}`]
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: [`{id: a}`, `{id: b}`, `{id: c}`],
|
||||
identityChanges: [`{id: a}`, `{id: b}`, `{id: c}`],
|
||||
previous: [`{id: a}`, `{id: b}`, `{id: c}`]
|
||||
}));
|
||||
});
|
||||
|
||||
it('should have updated properties in identity change collection', () => {
|
||||
@@ -407,12 +383,11 @@ export function main() {
|
||||
|
||||
l = [new ComplexItem('a', 'orange'), new ComplexItem('b', 'red')];
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: [`{id: a, color: orange}`, `{id: b, color: red}`],
|
||||
identityChanges: [`{id: a, color: orange}`, `{id: b, color: red}`],
|
||||
previous: [`{id: a, color: orange}`, `{id: b, color: red}`]
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: [`{id: a, color: orange}`, `{id: b, color: red}`],
|
||||
identityChanges: [`{id: a, color: orange}`, `{id: b, color: red}`],
|
||||
previous: [`{id: a, color: orange}`, `{id: b, color: red}`]
|
||||
}));
|
||||
});
|
||||
|
||||
it('should track moves normally', () => {
|
||||
@@ -421,13 +396,12 @@ export function main() {
|
||||
|
||||
l = buildItemList(['b', 'a', 'c']);
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['{id: b}[1->0]', '{id: a}[0->1]', '{id: c}'],
|
||||
identityChanges: ['{id: b}[1->0]', '{id: a}[0->1]', '{id: c}'],
|
||||
previous: ['{id: a}[0->1]', '{id: b}[1->0]', '{id: c}'],
|
||||
moves: ['{id: b}[1->0]', '{id: a}[0->1]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['{id: b}[1->0]', '{id: a}[0->1]', '{id: c}'],
|
||||
identityChanges: ['{id: b}[1->0]', '{id: a}[0->1]', '{id: c}'],
|
||||
previous: ['{id: a}[0->1]', '{id: b}[1->0]', '{id: c}'],
|
||||
moves: ['{id: b}[1->0]', '{id: a}[0->1]']
|
||||
}));
|
||||
|
||||
});
|
||||
|
||||
@@ -437,14 +411,13 @@ export function main() {
|
||||
|
||||
l = buildItemList(['b', 'a', 'a']);
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['{id: b}[null->0]', '{id: a}[0->1]', '{id: a}[1->2]'],
|
||||
identityChanges: ['{id: a}[0->1]', '{id: a}[1->2]'],
|
||||
previous: ['{id: a}[0->1]', '{id: a}[1->2]'],
|
||||
moves: ['{id: a}[0->1]', '{id: a}[1->2]'],
|
||||
additions: ['{id: b}[null->0]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['{id: b}[null->0]', '{id: a}[0->1]', '{id: a}[1->2]'],
|
||||
identityChanges: ['{id: a}[0->1]', '{id: a}[1->2]'],
|
||||
previous: ['{id: a}[0->1]', '{id: a}[1->2]'],
|
||||
moves: ['{id: a}[0->1]', '{id: a}[1->2]'],
|
||||
additions: ['{id: b}[null->0]']
|
||||
}));
|
||||
|
||||
});
|
||||
|
||||
@@ -454,12 +427,11 @@ export function main() {
|
||||
|
||||
ListWrapper.removeAt(l, 2);
|
||||
differ.check(l);
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['{id: a}', '{id: b}'],
|
||||
previous: ['{id: a}', '{id: b}', '{id: c}[2->null]'],
|
||||
removals: ['{id: c}[2->null]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['{id: a}', '{id: b}'],
|
||||
previous: ['{id: a}', '{id: b}', '{id: c}[2->null]'],
|
||||
removals: ['{id: c}[2->null]']
|
||||
}));
|
||||
});
|
||||
});
|
||||
describe('trackBy function by index', function() {
|
||||
@@ -474,13 +446,12 @@ export function main() {
|
||||
differ.check(['e', 'f', 'g', 'h']);
|
||||
differ.check(['e', 'f', 'h']);
|
||||
|
||||
expect(differ.toString())
|
||||
.toEqual(iterableChangesAsString({
|
||||
collection: ['e', 'f', 'h'],
|
||||
previous: ['e', 'f', 'h', 'h[3->null]'],
|
||||
removals: ['h[3->null]'],
|
||||
identityChanges: ['h']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(iterableChangesAsString({
|
||||
collection: ['e', 'f', 'h'],
|
||||
previous: ['e', 'f', 'h', 'h[3->null]'],
|
||||
removals: ['h[3->null]'],
|
||||
identityChanges: ['h']
|
||||
}));
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
+35
-50
@@ -1,17 +1,5 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {
|
||||
DefaultKeyValueDiffer,
|
||||
DefaultKeyValueDifferFactory
|
||||
} from 'angular2/src/core/change_detection/differs/default_keyvalue_differ';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
import {DefaultKeyValueDiffer, DefaultKeyValueDifferFactory} from 'angular2/src/core/change_detection/differs/default_keyvalue_differ';
|
||||
import {NumberWrapper, isJsObject} from 'angular2/src/facade/lang';
|
||||
import {kvChangesAsString} from '../../../core/change_detection/util';
|
||||
|
||||
@@ -52,12 +40,11 @@ export function main() {
|
||||
m.set(2, 10);
|
||||
m.set(1, 20);
|
||||
differ.check(m);
|
||||
expect(differ.toString())
|
||||
.toEqual(kvChangesAsString({
|
||||
map: ['1[10->20]', '2[20->10]'],
|
||||
previous: ['1[10->20]', '2[20->10]'],
|
||||
changes: ['1[10->20]', '2[20->10]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(kvChangesAsString({
|
||||
map: ['1[10->20]', '2[20->10]'],
|
||||
previous: ['1[10->20]', '2[20->10]'],
|
||||
changes: ['1[10->20]', '2[20->10]']
|
||||
}));
|
||||
});
|
||||
|
||||
it('should expose previous and current value', () => {
|
||||
@@ -95,13 +82,12 @@ export function main() {
|
||||
m.set('b', 'BB');
|
||||
m.set('d', 'D');
|
||||
differ.check(m);
|
||||
expect(differ.toString())
|
||||
.toEqual(kvChangesAsString({
|
||||
map: ['a', 'b[B->BB]', 'd[null->D]'],
|
||||
previous: ['a', 'b[B->BB]'],
|
||||
additions: ['d[null->D]'],
|
||||
changes: ['b[B->BB]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(kvChangesAsString({
|
||||
map: ['a', 'b[B->BB]', 'd[null->D]'],
|
||||
previous: ['a', 'b[B->BB]'],
|
||||
additions: ['d[null->D]'],
|
||||
changes: ['b[B->BB]']
|
||||
}));
|
||||
|
||||
m.delete('b');
|
||||
differ.check(m);
|
||||
@@ -111,9 +97,10 @@ export function main() {
|
||||
|
||||
m.clear();
|
||||
differ.check(m);
|
||||
expect(differ.toString())
|
||||
.toEqual(kvChangesAsString(
|
||||
{previous: ['a[A->null]', 'd[D->null]'], removals: ['a[A->null]', 'd[D->null]']}));
|
||||
expect(differ.toString()).toEqual(kvChangesAsString({
|
||||
previous: ['a[A->null]', 'd[D->null]'],
|
||||
removals: ['a[A->null]', 'd[D->null]']
|
||||
}));
|
||||
});
|
||||
|
||||
it('should test string by value rather than by reference (DART)', () => {
|
||||
@@ -145,7 +132,7 @@ export function main() {
|
||||
it('should support JS Object', () => {
|
||||
var f = new DefaultKeyValueDifferFactory();
|
||||
expect(f.supports({})).toBeTruthy();
|
||||
expect(f.supports("not supported")).toBeFalsy();
|
||||
expect(f.supports('not supported')).toBeFalsy();
|
||||
expect(f.supports(0)).toBeFalsy();
|
||||
expect(f.supports(null)).toBeFalsy();
|
||||
});
|
||||
@@ -168,32 +155,29 @@ export function main() {
|
||||
m['b'] = 'BB';
|
||||
m['d'] = 'D';
|
||||
differ.check(m);
|
||||
expect(differ.toString())
|
||||
.toEqual(kvChangesAsString({
|
||||
map: ['a', 'b[B->BB]', 'd[null->D]'],
|
||||
previous: ['a', 'b[B->BB]'],
|
||||
additions: ['d[null->D]'],
|
||||
changes: ['b[B->BB]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(kvChangesAsString({
|
||||
map: ['a', 'b[B->BB]', 'd[null->D]'],
|
||||
previous: ['a', 'b[B->BB]'],
|
||||
additions: ['d[null->D]'],
|
||||
changes: ['b[B->BB]']
|
||||
}));
|
||||
|
||||
m = {};
|
||||
m['a'] = 'A';
|
||||
m['d'] = 'D';
|
||||
differ.check(m);
|
||||
expect(differ.toString())
|
||||
.toEqual(kvChangesAsString({
|
||||
map: ['a', 'd'],
|
||||
previous: ['a', 'b[BB->null]', 'd'],
|
||||
removals: ['b[BB->null]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(kvChangesAsString({
|
||||
map: ['a', 'd'],
|
||||
previous: ['a', 'b[BB->null]', 'd'],
|
||||
removals: ['b[BB->null]']
|
||||
}));
|
||||
|
||||
m = {};
|
||||
differ.check(m);
|
||||
expect(differ.toString())
|
||||
.toEqual(kvChangesAsString({
|
||||
previous: ['a[A->null]', 'd[D->null]'],
|
||||
removals: ['a[A->null]', 'd[D->null]']
|
||||
}));
|
||||
expect(differ.toString()).toEqual(kvChangesAsString({
|
||||
previous: ['a[A->null]', 'd[D->null]'],
|
||||
removals: ['a[A->null]', 'd[D->null]']
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -217,7 +201,8 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should throw when given an invalid collection', () => {
|
||||
expect(() => differ.diff("invalid")).toThrowErrorWith("Error trying to diff 'invalid'");
|
||||
expect(() => differ.diff('invalid'))
|
||||
.toThrowErrorWith('Error trying to diff \'invalid\'');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,13 +1,4 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
import {SpyIterableDifferFactory} from '../../spies';
|
||||
import {IterableDiffers} from 'angular2/src/core/change_detection/differs/iterable_differs';
|
||||
import {Injector, provide} from 'angular2/core';
|
||||
@@ -26,22 +17,22 @@ export function main() {
|
||||
|
||||
it('should throw when no suitable implementation found', () => {
|
||||
var differs = new IterableDiffers([]);
|
||||
expect(() => differs.find("some object"))
|
||||
.toThrowErrorWith("Cannot find a differ supporting object 'some object'")
|
||||
expect(() => differs.find('some object'))
|
||||
.toThrowErrorWith('Cannot find a differ supporting object \'some object\'')
|
||||
});
|
||||
|
||||
it('should return the first suitable implementation', () => {
|
||||
factory1.spy("supports").andReturn(false);
|
||||
factory2.spy("supports").andReturn(true);
|
||||
factory3.spy("supports").andReturn(true);
|
||||
factory1.spy('supports').andReturn(false);
|
||||
factory2.spy('supports').andReturn(true);
|
||||
factory3.spy('supports').andReturn(true);
|
||||
|
||||
var differs = IterableDiffers.create(<any>[factory1, factory2, factory3]);
|
||||
expect(differs.find("some object")).toBe(factory2);
|
||||
expect(differs.find('some object')).toBe(factory2);
|
||||
});
|
||||
|
||||
it('should copy over differs from the parent repo', () => {
|
||||
factory1.spy("supports").andReturn(true);
|
||||
factory2.spy("supports").andReturn(false);
|
||||
factory1.spy('supports').andReturn(true);
|
||||
factory2.spy('supports').andReturn(false);
|
||||
|
||||
var parent = IterableDiffers.create(<any>[factory1]);
|
||||
var child = IterableDiffers.create(<any>[factory2], parent);
|
||||
@@ -49,12 +40,12 @@ export function main() {
|
||||
expect(child.factories).toEqual([factory2, factory1]);
|
||||
});
|
||||
|
||||
describe(".extend()", () => {
|
||||
describe('.extend()', () => {
|
||||
it('should throw if calling extend when creating root injector', () => {
|
||||
var injector = Injector.resolveAndCreate([IterableDiffers.extend([])]);
|
||||
|
||||
expect(() => injector.get(IterableDiffers))
|
||||
.toThrowErrorWith("Cannot extend IterableDiffers without a parent injector");
|
||||
.toThrowErrorWith('Cannot extend IterableDiffers without a parent injector');
|
||||
});
|
||||
|
||||
it('should extend di-inherited diffesr', () => {
|
||||
|
||||
@@ -2,7 +2,7 @@ import {ddescribe, describe, it, expect} from 'angular2/testing_internal';
|
||||
|
||||
import {Lexer, Token} from 'angular2/src/core/change_detection/parser/lexer';
|
||||
|
||||
import {StringWrapper} from "angular2/src/facade/lang";
|
||||
import {StringWrapper} from 'angular2/src/facade/lang';
|
||||
|
||||
function lex(text: string): any[] {
|
||||
return new Lexer().tokenize(text);
|
||||
@@ -52,13 +52,13 @@ export function main() {
|
||||
describe('lexer', function() {
|
||||
describe('token', function() {
|
||||
it('should tokenize a simple identifier', function() {
|
||||
var tokens: number[] = lex("j");
|
||||
var tokens: number[] = lex('j');
|
||||
expect(tokens.length).toEqual(1);
|
||||
expectIdentifierToken(tokens[0], 0, 'j');
|
||||
});
|
||||
|
||||
it('should tokenize a dotted identifier', function() {
|
||||
var tokens: number[] = lex("j.k");
|
||||
var tokens: number[] = lex('j.k');
|
||||
expect(tokens.length).toEqual(3);
|
||||
expectIdentifierToken(tokens[0], 0, 'j');
|
||||
expectCharacterToken(tokens[1], 1, '.');
|
||||
@@ -66,35 +66,35 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should tokenize an operator', function() {
|
||||
var tokens: number[] = lex("j-k");
|
||||
var tokens: number[] = lex('j-k');
|
||||
expect(tokens.length).toEqual(3);
|
||||
expectOperatorToken(tokens[1], 1, '-');
|
||||
});
|
||||
|
||||
it('should tokenize an indexed operator', function() {
|
||||
var tokens: number[] = lex("j[k]");
|
||||
var tokens: number[] = lex('j[k]');
|
||||
expect(tokens.length).toEqual(4);
|
||||
expectCharacterToken(tokens[1], 1, "[");
|
||||
expectCharacterToken(tokens[3], 3, "]");
|
||||
expectCharacterToken(tokens[1], 1, '[');
|
||||
expectCharacterToken(tokens[3], 3, ']');
|
||||
});
|
||||
|
||||
it('should tokenize numbers', function() {
|
||||
var tokens: number[] = lex("88");
|
||||
var tokens: number[] = lex('88');
|
||||
expect(tokens.length).toEqual(1);
|
||||
expectNumberToken(tokens[0], 0, 88);
|
||||
});
|
||||
|
||||
it('should tokenize numbers within index ops',
|
||||
function() { expectNumberToken(lex("a[22]")[2], 2, 22); });
|
||||
function() { expectNumberToken(lex('a[22]')[2], 2, 22); });
|
||||
|
||||
it('should tokenize simple quoted strings',
|
||||
function() { expectStringToken(lex('"a"')[0], 0, "a"); });
|
||||
function() { expectStringToken(lex('"a"')[0], 0, 'a'); });
|
||||
|
||||
it('should tokenize quoted strings with escaped quotes',
|
||||
function() { expectStringToken(lex('"a\\""')[0], 0, 'a"'); });
|
||||
|
||||
it('should tokenize a string', function() {
|
||||
var tokens: Token[] = lex("j-a.bc[22]+1.3|f:'a\\\'c':\"d\\\"e\"");
|
||||
var tokens: Token[] = lex('j-a.bc[22]+1.3|f:\'a\\\'c\':"d\\"e"');
|
||||
expectIdentifierToken(tokens[0], 0, 'j');
|
||||
expectOperatorToken(tokens[1], 1, '-');
|
||||
expectIdentifierToken(tokens[2], 2, 'a');
|
||||
@@ -108,27 +108,27 @@ export function main() {
|
||||
expectOperatorToken(tokens[10], 14, '|');
|
||||
expectIdentifierToken(tokens[11], 15, 'f');
|
||||
expectCharacterToken(tokens[12], 16, ':');
|
||||
expectStringToken(tokens[13], 17, "a'c");
|
||||
expectStringToken(tokens[13], 17, 'a\'c');
|
||||
expectCharacterToken(tokens[14], 23, ':');
|
||||
expectStringToken(tokens[15], 24, 'd"e');
|
||||
});
|
||||
|
||||
it('should tokenize undefined', function() {
|
||||
var tokens: Token[] = lex("undefined");
|
||||
expectKeywordToken(tokens[0], 0, "undefined");
|
||||
var tokens: Token[] = lex('undefined');
|
||||
expectKeywordToken(tokens[0], 0, 'undefined');
|
||||
expect(tokens[0].isKeywordUndefined()).toBe(true);
|
||||
});
|
||||
|
||||
it('should ignore whitespace', function() {
|
||||
var tokens: Token[] = lex("a \t \n \r b");
|
||||
var tokens: Token[] = lex('a \t \n \r b');
|
||||
expectIdentifierToken(tokens[0], 0, 'a');
|
||||
expectIdentifierToken(tokens[1], 8, 'b');
|
||||
});
|
||||
|
||||
it('should tokenize quoted string', () => {
|
||||
var str = "['\\'', \"\\\"\"]";
|
||||
var str = '[\'\\\'\', "\\""]';
|
||||
var tokens: Token[] = lex(str);
|
||||
expectStringToken(tokens[1], 1, "'");
|
||||
expectStringToken(tokens[1], 1, '\'');
|
||||
expectStringToken(tokens[3], 7, '"');
|
||||
});
|
||||
|
||||
@@ -146,7 +146,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should tokenize relation', function() {
|
||||
var tokens: Token[] = lex("! == != < > <= >= === !==");
|
||||
var tokens: Token[] = lex('! == != < > <= >= === !==');
|
||||
expectOperatorToken(tokens[0], 0, '!');
|
||||
expectOperatorToken(tokens[1], 2, '==');
|
||||
expectOperatorToken(tokens[2], 5, '!=');
|
||||
@@ -159,7 +159,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should tokenize statements', function() {
|
||||
var tokens: Token[] = lex("a;b;");
|
||||
var tokens: Token[] = lex('a;b;');
|
||||
expectIdentifierToken(tokens[0], 0, 'a');
|
||||
expectCharacterToken(tokens[1], 1, ';');
|
||||
expectIdentifierToken(tokens[2], 2, 'b');
|
||||
@@ -167,19 +167,19 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should tokenize function invocation', function() {
|
||||
var tokens: Token[] = lex("a()");
|
||||
var tokens: Token[] = lex('a()');
|
||||
expectIdentifierToken(tokens[0], 0, 'a');
|
||||
expectCharacterToken(tokens[1], 1, '(');
|
||||
expectCharacterToken(tokens[2], 2, ')');
|
||||
});
|
||||
|
||||
it('should tokenize simple method invocations', function() {
|
||||
var tokens: Token[] = lex("a.method()");
|
||||
var tokens: Token[] = lex('a.method()');
|
||||
expectIdentifierToken(tokens[2], 2, 'method');
|
||||
});
|
||||
|
||||
it('should tokenize method invocation', function() {
|
||||
var tokens: Token[] = lex("a.b.c (d) - e.f()");
|
||||
var tokens: Token[] = lex('a.b.c (d) - e.f()');
|
||||
expectIdentifierToken(tokens[0], 0, 'a');
|
||||
expectCharacterToken(tokens[1], 1, '.');
|
||||
expectIdentifierToken(tokens[2], 2, 'b');
|
||||
@@ -197,7 +197,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should tokenize number', function() {
|
||||
var tokens: Token[] = lex("0.5");
|
||||
var tokens: Token[] = lex('0.5');
|
||||
expectNumberToken(tokens[0], 0, 0.5);
|
||||
});
|
||||
|
||||
@@ -208,34 +208,36 @@ export function main() {
|
||||
// });
|
||||
|
||||
it('should tokenize number with exponent', function() {
|
||||
var tokens: Token[] = lex("0.5E-10");
|
||||
var tokens: Token[] = lex('0.5E-10');
|
||||
expect(tokens.length).toEqual(1);
|
||||
expectNumberToken(tokens[0], 0, 0.5E-10);
|
||||
tokens = lex("0.5E+10");
|
||||
tokens = lex('0.5E+10');
|
||||
expectNumberToken(tokens[0], 0, 0.5E+10);
|
||||
});
|
||||
|
||||
it('should throws exception for invalid exponent', function() {
|
||||
expect(() => { lex("0.5E-"); })
|
||||
.toThrowError('Lexer Error: Invalid exponent at column 4 in expression [0.5E-]');
|
||||
expect(() => {
|
||||
lex('0.5E-');
|
||||
}).toThrowError('Lexer Error: Invalid exponent at column 4 in expression [0.5E-]');
|
||||
|
||||
expect(() => { lex("0.5E-A"); })
|
||||
.toThrowError('Lexer Error: Invalid exponent at column 4 in expression [0.5E-A]');
|
||||
expect(() => {
|
||||
lex('0.5E-A');
|
||||
}).toThrowError('Lexer Error: Invalid exponent at column 4 in expression [0.5E-A]');
|
||||
});
|
||||
|
||||
it('should tokenize number starting with a dot', function() {
|
||||
var tokens: Token[] = lex(".5");
|
||||
var tokens: Token[] = lex('.5');
|
||||
expectNumberToken(tokens[0], 0, 0.5);
|
||||
});
|
||||
|
||||
it('should throw error on invalid unicode', function() {
|
||||
expect(() => { lex("'\\u1''bla'"); })
|
||||
expect(() => { lex('\'\\u1\'\'bla\''); })
|
||||
.toThrowError(
|
||||
"Lexer Error: Invalid unicode escape [\\u1''b] at column 2 in expression ['\\u1''bla']");
|
||||
'Lexer Error: Invalid unicode escape [\\u1\'\'b] at column 2 in expression [\'\\u1\'\'bla\']');
|
||||
});
|
||||
|
||||
it('should tokenize hash as operator', function() {
|
||||
var tokens: Token[] = lex("#");
|
||||
var tokens: Token[] = lex('#');
|
||||
expectOperatorToken(tokens[0], 0, '#');
|
||||
});
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ export function main() {
|
||||
|
||||
it('should support getting values', () => {
|
||||
expect(locals.get('key')).toBe('value');
|
||||
expect(() => locals.get('notPresent')).toThrowError(new RegExp("Cannot find"));
|
||||
expect(() => locals.get('notPresent')).toThrowError(new RegExp('Cannot find'));
|
||||
});
|
||||
|
||||
it('should support checking if key is present', () => {
|
||||
|
||||
@@ -53,86 +53,86 @@ export function main() {
|
||||
|
||||
function expectBindingError(text) { return expect(() => parseBinding(text)); }
|
||||
|
||||
describe("parser", () => {
|
||||
describe("parseAction", () => {
|
||||
it('should parse numbers', () => { checkAction("1"); });
|
||||
describe('parser', () => {
|
||||
describe('parseAction', () => {
|
||||
it('should parse numbers', () => { checkAction('1'); });
|
||||
|
||||
it('should parse strings', () => {
|
||||
checkAction("'1'", '"1"');
|
||||
checkAction('\'1\'', '"1"');
|
||||
checkAction('"1"');
|
||||
});
|
||||
|
||||
it('should parse null', () => { checkAction("null"); });
|
||||
it('should parse null', () => { checkAction('null'); });
|
||||
|
||||
it('should parse unary - expressions', () => {
|
||||
checkAction("-1", "0 - 1");
|
||||
checkAction("+1", "1");
|
||||
checkAction('-1', '0 - 1');
|
||||
checkAction('+1', '1');
|
||||
});
|
||||
|
||||
it('should parse unary ! expressions', () => {
|
||||
checkAction("!true");
|
||||
checkAction("!!true");
|
||||
checkAction("!!!true");
|
||||
checkAction('!true');
|
||||
checkAction('!!true');
|
||||
checkAction('!!!true');
|
||||
});
|
||||
|
||||
it('should parse multiplicative expressions',
|
||||
() => { checkAction("3*4/2%5", "3 * 4 / 2 % 5"); });
|
||||
() => { checkAction('3*4/2%5', '3 * 4 / 2 % 5'); });
|
||||
|
||||
it('should parse additive expressions', () => { checkAction("3 + 6 - 2"); });
|
||||
it('should parse additive expressions', () => { checkAction('3 + 6 - 2'); });
|
||||
|
||||
it('should parse relational expressions', () => {
|
||||
checkAction("2 < 3");
|
||||
checkAction("2 > 3");
|
||||
checkAction("2 <= 2");
|
||||
checkAction("2 >= 2");
|
||||
checkAction('2 < 3');
|
||||
checkAction('2 > 3');
|
||||
checkAction('2 <= 2');
|
||||
checkAction('2 >= 2');
|
||||
});
|
||||
|
||||
it('should parse equality expressions', () => {
|
||||
checkAction("2 == 3");
|
||||
checkAction("2 != 3");
|
||||
checkAction('2 == 3');
|
||||
checkAction('2 != 3');
|
||||
});
|
||||
|
||||
it('should parse strict equality expressions', () => {
|
||||
checkAction("2 === 3");
|
||||
checkAction("2 !== 3");
|
||||
checkAction('2 === 3');
|
||||
checkAction('2 !== 3');
|
||||
});
|
||||
|
||||
it('should parse expressions', () => {
|
||||
checkAction("true && true");
|
||||
checkAction("true || false");
|
||||
checkAction('true && true');
|
||||
checkAction('true || false');
|
||||
});
|
||||
|
||||
it('should parse grouped expressions', () => { checkAction("(1 + 2) * 3", "1 + 2 * 3"); });
|
||||
it('should parse grouped expressions', () => { checkAction('(1 + 2) * 3', '1 + 2 * 3'); });
|
||||
|
||||
it('should parse an empty string', () => { checkAction(''); });
|
||||
|
||||
describe("literals", () => {
|
||||
describe('literals', () => {
|
||||
it('should parse array', () => {
|
||||
checkAction("[1][0]");
|
||||
checkAction("[[1]][0][0]");
|
||||
checkAction("[]");
|
||||
checkAction("[].length");
|
||||
checkAction("[1, 2].length");
|
||||
checkAction('[1][0]');
|
||||
checkAction('[[1]][0][0]');
|
||||
checkAction('[]');
|
||||
checkAction('[].length');
|
||||
checkAction('[1, 2].length');
|
||||
});
|
||||
|
||||
it('should parse map', () => {
|
||||
checkAction("{}");
|
||||
checkAction("{a: 1}[2]");
|
||||
checkAction("{}[\"a\"]");
|
||||
checkAction('{}');
|
||||
checkAction('{a: 1}[2]');
|
||||
checkAction('{}["a"]');
|
||||
});
|
||||
|
||||
it('should only allow identifier, string, or keyword as map key', () => {
|
||||
expectActionError('{(:0}')
|
||||
.toThrowError(new RegExp('expected identifier, keyword, or string'));
|
||||
expectActionError('{(:0}').toThrowError(
|
||||
new RegExp('expected identifier, keyword, or string'));
|
||||
expectActionError('{1234:0}')
|
||||
.toThrowError(new RegExp('expected identifier, keyword, or string'));
|
||||
});
|
||||
});
|
||||
|
||||
describe("member access", () => {
|
||||
it("should parse field access", () => {
|
||||
checkAction("a");
|
||||
checkAction("a.a");
|
||||
describe('member access', () => {
|
||||
it('should parse field access', () => {
|
||||
checkAction('a');
|
||||
checkAction('a.a');
|
||||
});
|
||||
|
||||
it('should only allow identifier or keyword as member names', () => {
|
||||
@@ -147,46 +147,47 @@ export function main() {
|
||||
});
|
||||
});
|
||||
|
||||
describe("method calls", () => {
|
||||
it("should parse method calls", () => {
|
||||
checkAction("fn()");
|
||||
checkAction("add(1, 2)");
|
||||
checkAction("a.add(1, 2)");
|
||||
checkAction("fn().add(1, 2)");
|
||||
describe('method calls', () => {
|
||||
it('should parse method calls', () => {
|
||||
checkAction('fn()');
|
||||
checkAction('add(1, 2)');
|
||||
checkAction('a.add(1, 2)');
|
||||
checkAction('fn().add(1, 2)');
|
||||
});
|
||||
});
|
||||
|
||||
describe("functional calls",
|
||||
() => { it("should parse function calls", () => { checkAction("fn()(1, 2)"); }); });
|
||||
describe('functional calls', () => {
|
||||
it('should parse function calls', () => { checkAction('fn()(1, 2)'); });
|
||||
});
|
||||
|
||||
describe("conditional", () => {
|
||||
describe('conditional', () => {
|
||||
it('should parse ternary/conditional expressions', () => {
|
||||
checkAction("7 == 3 + 4 ? 10 : 20");
|
||||
checkAction("false ? 10 : 20");
|
||||
checkAction('7 == 3 + 4 ? 10 : 20');
|
||||
checkAction('false ? 10 : 20');
|
||||
});
|
||||
|
||||
it('should throw on incorrect ternary operator syntax', () => {
|
||||
expectActionError("true?1").toThrowError(new RegExp(
|
||||
expectActionError('true?1').toThrowError(new RegExp(
|
||||
'Parser Error: Conditional expression true\\?1 requires all 3 expressions'));
|
||||
});
|
||||
});
|
||||
|
||||
describe("assignment", () => {
|
||||
it("should support field assignments", () => {
|
||||
checkAction("a = 12");
|
||||
checkAction("a.a.a = 123");
|
||||
checkAction("a = 123; b = 234;");
|
||||
describe('assignment', () => {
|
||||
it('should support field assignments', () => {
|
||||
checkAction('a = 12');
|
||||
checkAction('a.a.a = 123');
|
||||
checkAction('a = 123; b = 234;');
|
||||
});
|
||||
|
||||
it("should throw on safe field assignments", () => {
|
||||
expectActionError("a?.a = 123")
|
||||
it('should throw on safe field assignments', () => {
|
||||
expectActionError('a?.a = 123')
|
||||
.toThrowError(new RegExp('cannot be used in the assignment'));
|
||||
});
|
||||
|
||||
it("should support array updates", () => { checkAction("a[0] = 200"); });
|
||||
it('should support array updates', () => { checkAction('a[0] = 200'); });
|
||||
});
|
||||
|
||||
it("should error when using pipes",
|
||||
it('should error when using pipes',
|
||||
() => { expectActionError('x|blah').toThrowError(new RegExp('Cannot have a pipe')); });
|
||||
|
||||
it('should store the source in the result',
|
||||
@@ -195,31 +196,31 @@ export function main() {
|
||||
it('should store the passed-in location',
|
||||
() => { expect(parseAction('someExpr', 'location').location).toBe('location'); });
|
||||
|
||||
it("should throw when encountering interpolation", () => {
|
||||
expectActionError("{{a()}}")
|
||||
.toThrowErrorWith('Got interpolation ({{}}) where expression was expected');
|
||||
it('should throw when encountering interpolation', () => {
|
||||
expectActionError('{{a()}}').toThrowErrorWith(
|
||||
'Got interpolation ({{}}) where expression was expected');
|
||||
});
|
||||
});
|
||||
|
||||
describe("general error handling", () => {
|
||||
it("should throw on an unexpected token", () => {
|
||||
expectActionError("[1,2] trac").toThrowError(new RegExp('Unexpected token \'trac\''));
|
||||
describe('general error handling', () => {
|
||||
it('should throw on an unexpected token', () => {
|
||||
expectActionError('[1,2] trac').toThrowError(new RegExp('Unexpected token \'trac\''));
|
||||
});
|
||||
|
||||
it('should throw a reasonable error for unconsumed tokens', () => {
|
||||
expectActionError(")")
|
||||
.toThrowError(new RegExp("Unexpected token \\) at column 1 in \\[\\)\\]"));
|
||||
expectActionError(')').toThrowError(
|
||||
new RegExp('Unexpected token \\) at column 1 in \\[\\)\\]'));
|
||||
});
|
||||
|
||||
it('should throw on missing expected token', () => {
|
||||
expectActionError("a(b").toThrowError(
|
||||
new RegExp("Missing expected \\) at the end of the expression \\[a\\(b\\]"));
|
||||
expectActionError('a(b').toThrowError(
|
||||
new RegExp('Missing expected \\) at the end of the expression \\[a\\(b\\]'));
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseBinding", () => {
|
||||
describe("pipes", () => {
|
||||
it("should parse pipes", () => {
|
||||
describe('parseBinding', () => {
|
||||
describe('pipes', () => {
|
||||
it('should parse pipes', () => {
|
||||
checkBinding('a(b | c)', 'a((b | c))');
|
||||
checkBinding('a.b(c.d(e) | f)', 'a.b((c.d(e) | f))');
|
||||
checkBinding('[1, 2, 3] | a', '([1, 2, 3] | a)');
|
||||
@@ -257,16 +258,16 @@ export function main() {
|
||||
() => { expect(parseBinding('someExpr', 'location').location).toBe('location'); });
|
||||
|
||||
it('should throw on chain expressions', () => {
|
||||
expect(() => parseBinding("1;2")).toThrowError(new RegExp("contain chained expression"));
|
||||
expect(() => parseBinding('1;2')).toThrowError(new RegExp('contain chained expression'));
|
||||
});
|
||||
|
||||
it('should throw on assignment', () => {
|
||||
expect(() => parseBinding("a=2")).toThrowError(new RegExp("contain assignments"));
|
||||
expect(() => parseBinding('a=2')).toThrowError(new RegExp('contain assignments'));
|
||||
});
|
||||
|
||||
it('should throw when encountering interpolation', () => {
|
||||
expectBindingError("{{a.b}}")
|
||||
.toThrowErrorWith('Got interpolation ({{}}) where expression was expected');
|
||||
expectBindingError('{{a.b}}').toThrowErrorWith(
|
||||
'Got interpolation ({{}}) where expression was expected');
|
||||
});
|
||||
|
||||
it('should parse conditional expression', () => { checkBinding('a < b ? a : b'); });
|
||||
@@ -299,90 +300,93 @@ export function main() {
|
||||
() => { expect(keys(parseTemplateBindings('a'))).toEqual(['a']); });
|
||||
|
||||
it('should only allow identifier, string, or keyword including dashes as keys', () => {
|
||||
var bindings = parseTemplateBindings("a:'b'");
|
||||
var bindings = parseTemplateBindings('a:\'b\'');
|
||||
expect(keys(bindings)).toEqual(['a']);
|
||||
|
||||
bindings = parseTemplateBindings("'a':'b'");
|
||||
bindings = parseTemplateBindings('\'a\':\'b\'');
|
||||
expect(keys(bindings)).toEqual(['a']);
|
||||
|
||||
bindings = parseTemplateBindings("\"a\":'b'");
|
||||
bindings = parseTemplateBindings('"a":\'b\'');
|
||||
expect(keys(bindings)).toEqual(['a']);
|
||||
|
||||
bindings = parseTemplateBindings("a-b:'c'");
|
||||
bindings = parseTemplateBindings('a-b:\'c\'');
|
||||
expect(keys(bindings)).toEqual(['a-b']);
|
||||
|
||||
expect(() => { parseTemplateBindings('(:0'); })
|
||||
.toThrowError(new RegExp('expected identifier, keyword, or string'));
|
||||
expect(() => {
|
||||
parseTemplateBindings('(:0');
|
||||
}).toThrowError(new RegExp('expected identifier, keyword, or string'));
|
||||
|
||||
expect(() => { parseTemplateBindings('1234:0'); })
|
||||
.toThrowError(new RegExp('expected identifier, keyword, or string'));
|
||||
expect(() => {
|
||||
parseTemplateBindings('1234:0');
|
||||
}).toThrowError(new RegExp('expected identifier, keyword, or string'));
|
||||
});
|
||||
|
||||
it('should detect expressions as value', () => {
|
||||
var bindings = parseTemplateBindings("a:b");
|
||||
var bindings = parseTemplateBindings('a:b');
|
||||
expect(exprSources(bindings)).toEqual(['b']);
|
||||
|
||||
bindings = parseTemplateBindings("a:1+1");
|
||||
bindings = parseTemplateBindings('a:1+1');
|
||||
expect(exprSources(bindings)).toEqual(['1+1']);
|
||||
});
|
||||
|
||||
it('should detect names as value', () => {
|
||||
var bindings = parseTemplateBindings("a:#b");
|
||||
var bindings = parseTemplateBindings('a:#b');
|
||||
expect(keyValues(bindings)).toEqual(['a', '#b=\$implicit']);
|
||||
});
|
||||
|
||||
it('should allow space and colon as separators', () => {
|
||||
var bindings = parseTemplateBindings("a:b");
|
||||
var bindings = parseTemplateBindings('a:b');
|
||||
expect(keys(bindings)).toEqual(['a']);
|
||||
expect(exprSources(bindings)).toEqual(['b']);
|
||||
|
||||
bindings = parseTemplateBindings("a b");
|
||||
bindings = parseTemplateBindings('a b');
|
||||
expect(keys(bindings)).toEqual(['a']);
|
||||
expect(exprSources(bindings)).toEqual(['b']);
|
||||
});
|
||||
|
||||
it('should allow multiple pairs', () => {
|
||||
var bindings = parseTemplateBindings("a 1 b 2");
|
||||
var bindings = parseTemplateBindings('a 1 b 2');
|
||||
expect(keys(bindings)).toEqual(['a', 'aB']);
|
||||
expect(exprSources(bindings)).toEqual(['1 ', '2']);
|
||||
});
|
||||
|
||||
it('should store the sources in the result', () => {
|
||||
var bindings = parseTemplateBindings("a 1,b 2");
|
||||
var bindings = parseTemplateBindings('a 1,b 2');
|
||||
expect(bindings[0].expression.source).toEqual('1');
|
||||
expect(bindings[1].expression.source).toEqual('2');
|
||||
});
|
||||
|
||||
it('should store the passed-in location', () => {
|
||||
var bindings = parseTemplateBindings("a 1,b 2", 'location');
|
||||
var bindings = parseTemplateBindings('a 1,b 2', 'location');
|
||||
expect(bindings[0].expression.location).toEqual('location');
|
||||
});
|
||||
|
||||
it('should support var/# notation', () => {
|
||||
var bindings = parseTemplateBindings("var i");
|
||||
var bindings = parseTemplateBindings('var i');
|
||||
expect(keyValues(bindings)).toEqual(['#i=\$implicit']);
|
||||
|
||||
bindings = parseTemplateBindings("#i");
|
||||
bindings = parseTemplateBindings('#i');
|
||||
expect(keyValues(bindings)).toEqual(['#i=\$implicit']);
|
||||
|
||||
bindings = parseTemplateBindings("var a; var b");
|
||||
bindings = parseTemplateBindings('var a; var b');
|
||||
expect(keyValues(bindings)).toEqual(['#a=\$implicit', '#b=\$implicit']);
|
||||
|
||||
bindings = parseTemplateBindings("#a; #b;");
|
||||
bindings = parseTemplateBindings('#a; #b;');
|
||||
expect(keyValues(bindings)).toEqual(['#a=\$implicit', '#b=\$implicit']);
|
||||
|
||||
bindings = parseTemplateBindings("var i-a = k-a");
|
||||
bindings = parseTemplateBindings('var i-a = k-a');
|
||||
expect(keyValues(bindings)).toEqual(['#i-a=k-a']);
|
||||
|
||||
bindings = parseTemplateBindings("keyword var item; var i = k");
|
||||
bindings = parseTemplateBindings('keyword var item; var i = k');
|
||||
expect(keyValues(bindings)).toEqual(['keyword', '#item=\$implicit', '#i=k']);
|
||||
|
||||
bindings = parseTemplateBindings("keyword: #item; #i = k");
|
||||
bindings = parseTemplateBindings('keyword: #item; #i = k');
|
||||
expect(keyValues(bindings)).toEqual(['keyword', '#item=\$implicit', '#i=k']);
|
||||
|
||||
bindings = parseTemplateBindings("directive: var item in expr; var a = b", 'location');
|
||||
expect(keyValues(bindings))
|
||||
.toEqual(['directive', '#item=\$implicit', 'directiveIn=expr in location', '#a=b']);
|
||||
bindings = parseTemplateBindings('directive: var item in expr; var a = b', 'location');
|
||||
expect(keyValues(bindings)).toEqual([
|
||||
'directive', '#item=\$implicit', 'directiveIn=expr in location', '#a=b'
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse pipes', () => {
|
||||
@@ -409,14 +413,14 @@ export function main() {
|
||||
expect(new Unparser().unparse(ast)).toEqual(originalExp);
|
||||
});
|
||||
|
||||
it("should throw on empty interpolation expressions", () => {
|
||||
expect(() => parseInterpolation("{{}}"))
|
||||
it('should throw on empty interpolation expressions', () => {
|
||||
expect(() => parseInterpolation('{{}}'))
|
||||
.toThrowErrorWith(
|
||||
"Parser Error: Blank expressions are not allowed in interpolated strings");
|
||||
'Parser Error: Blank expressions are not allowed in interpolated strings');
|
||||
|
||||
expect(() => parseInterpolation("foo {{ }}"))
|
||||
expect(() => parseInterpolation('foo {{ }}'))
|
||||
.toThrowErrorWith(
|
||||
"Parser Error: Blank expressions are not allowed in interpolated strings");
|
||||
'Parser Error: Blank expressions are not allowed in interpolated strings');
|
||||
});
|
||||
|
||||
it('should parse conditional expression',
|
||||
@@ -427,19 +431,19 @@ export function main() {
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseSimpleBinding", () => {
|
||||
it("should parse a field access", () => {
|
||||
var p = parseSimpleBinding("name");
|
||||
expect(unparse(p)).toEqual("name");
|
||||
describe('parseSimpleBinding', () => {
|
||||
it('should parse a field access', () => {
|
||||
var p = parseSimpleBinding('name');
|
||||
expect(unparse(p)).toEqual('name');
|
||||
});
|
||||
|
||||
it("should parse a constant", () => {
|
||||
var p = parseSimpleBinding("[1, 2]");
|
||||
expect(unparse(p)).toEqual("[1, 2]");
|
||||
it('should parse a constant', () => {
|
||||
var p = parseSimpleBinding('[1, 2]');
|
||||
expect(unparse(p)).toEqual('[1, 2]');
|
||||
});
|
||||
|
||||
it("should throw when the given expression is not just a field name", () => {
|
||||
expect(() => parseSimpleBinding("name + 1"))
|
||||
it('should throw when the given expression is not just a field name', () => {
|
||||
expect(() => parseSimpleBinding('name + 1'))
|
||||
.toThrowErrorWith(
|
||||
'Host binding expression can only contain field access and constants');
|
||||
});
|
||||
@@ -452,7 +456,7 @@ export function main() {
|
||||
|
||||
describe('wrapLiteralPrimitive', () => {
|
||||
it('should wrap a literal primitive', () => {
|
||||
expect(unparse(createParser().wrapLiteralPrimitive("foo", null))).toEqual('"foo"');
|
||||
expect(unparse(createParser().wrapLiteralPrimitive('foo', null))).toEqual('"foo"');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,27 +1,4 @@
|
||||
import {
|
||||
AST,
|
||||
AstVisitor,
|
||||
PropertyRead,
|
||||
PropertyWrite,
|
||||
Binary,
|
||||
Chain,
|
||||
Conditional,
|
||||
EmptyExpr,
|
||||
BindingPipe,
|
||||
FunctionCall,
|
||||
ImplicitReceiver,
|
||||
Interpolation,
|
||||
KeyedRead,
|
||||
KeyedWrite,
|
||||
LiteralArray,
|
||||
LiteralMap,
|
||||
LiteralPrimitive,
|
||||
MethodCall,
|
||||
PrefixNot,
|
||||
Quote,
|
||||
SafePropertyRead,
|
||||
SafeMethodCall
|
||||
} from 'angular2/src/core/change_detection/parser/ast';
|
||||
import {AST, AstVisitor, PropertyRead, PropertyWrite, Binary, Chain, Conditional, EmptyExpr, BindingPipe, FunctionCall, ImplicitReceiver, Interpolation, KeyedRead, KeyedWrite, LiteralArray, LiteralMap, LiteralPrimitive, MethodCall, PrefixNot, Quote, SafePropertyRead, SafeMethodCall} from 'angular2/src/core/change_detection/parser/ast';
|
||||
|
||||
|
||||
import {StringWrapper, isPresent, isString} from 'angular2/src/facade/lang';
|
||||
|
||||
@@ -1,25 +1,15 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
inject
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject} from 'angular2/testing_internal';
|
||||
|
||||
import {ProtoRecordBuilder} from 'angular2/src/core/change_detection/proto_change_detector';
|
||||
import {BindingRecord} from 'angular2/src/core/change_detection/binding_record';
|
||||
import {Parser} from 'angular2/src/core/change_detection/parser/parser';
|
||||
|
||||
export function main() {
|
||||
describe("ProtoRecordBuilder", () => {
|
||||
describe('ProtoRecordBuilder', () => {
|
||||
it('should set argumentToPureFunction flag', inject([Parser], (p: Parser) => {
|
||||
var builder = new ProtoRecordBuilder();
|
||||
var ast = p.parseBinding("[1,2]", "location"); // collection literal is a pure function
|
||||
builder.add(BindingRecord.createForElementProperty(ast, 0, "property"), [], 0);
|
||||
var ast = p.parseBinding('[1,2]', 'location'); // collection literal is a pure function
|
||||
builder.add(BindingRecord.createForElementProperty(ast, 0, 'property'), [], 0);
|
||||
|
||||
var isPureFunc = builder.records.map(r => r.argumentToPureFunction);
|
||||
expect(isPureFunc).toEqual([true, true, false]);
|
||||
@@ -28,8 +18,8 @@ export function main() {
|
||||
it('should not set argumentToPureFunction flag when not needed',
|
||||
inject([Parser], (p: Parser) => {
|
||||
var builder = new ProtoRecordBuilder();
|
||||
var ast = p.parseBinding("f(1,2)", "location");
|
||||
builder.add(BindingRecord.createForElementProperty(ast, 0, "property"), [], 0);
|
||||
var ast = p.parseBinding('f(1,2)', 'location');
|
||||
builder.add(BindingRecord.createForElementProperty(ast, 0, 'property'), [], 0);
|
||||
|
||||
var isPureFunc = builder.records.map(r => r.argumentToPureFunction);
|
||||
expect(isPureFunc).toEqual([false, false, false]);
|
||||
|
||||
@@ -1,13 +1,4 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/testing_internal';
|
||||
import {isBlank} from 'angular2/src/facade/lang';
|
||||
|
||||
import {RecordType, ProtoRecord} from 'angular2/src/core/change_detection/proto_record';
|
||||
@@ -24,16 +15,17 @@ export function main() {
|
||||
} = {}) {
|
||||
if (isBlank(lastInBinding)) lastInBinding = false;
|
||||
if (isBlank(mode)) mode = RecordType.PropertyRead;
|
||||
if (isBlank(name)) name = "name";
|
||||
if (isBlank(name)) name = 'name';
|
||||
if (isBlank(directiveIndex)) directiveIndex = null;
|
||||
if (isBlank(argumentToPureFunction)) argumentToPureFunction = false;
|
||||
if (isBlank(referencedBySelf)) referencedBySelf = false;
|
||||
|
||||
return new ProtoRecord(mode, name, null, [], null, 0, directiveIndex, 0, null, lastInBinding,
|
||||
false, argumentToPureFunction, referencedBySelf, 0);
|
||||
return new ProtoRecord(
|
||||
mode, name, null, [], null, 0, directiveIndex, 0, null, lastInBinding, false,
|
||||
argumentToPureFunction, referencedBySelf, 0);
|
||||
}
|
||||
|
||||
describe("ProtoRecord", () => {
|
||||
describe('ProtoRecord', () => {
|
||||
describe('shouldBeChecked', () => {
|
||||
it('should be true for pure functions',
|
||||
() => { expect(r({mode: RecordType.CollectionLiteral}).shouldBeChecked()).toBeTruthy(); });
|
||||
|
||||
@@ -3,10 +3,12 @@ import {isBlank, CONST_EXPR} from 'angular2/src/facade/lang';
|
||||
export function iterableChangesAsString(
|
||||
{collection = CONST_EXPR([]), previous = CONST_EXPR([]), additions = CONST_EXPR([]),
|
||||
moves = CONST_EXPR([]), removals = CONST_EXPR([]), identityChanges = CONST_EXPR([])}) {
|
||||
return "collection: " + collection.join(', ') + "\n" + "previous: " + previous.join(', ') + "\n" +
|
||||
"additions: " + additions.join(', ') + "\n" + "moves: " + moves.join(', ') + "\n" +
|
||||
"removals: " + removals.join(', ') + "\n" + "identityChanges: " +
|
||||
identityChanges.join(', ') + "\n";
|
||||
return 'collection: ' + collection.join(', ') + '\n' +
|
||||
'previous: ' + previous.join(', ') + '\n' +
|
||||
'additions: ' + additions.join(', ') + '\n' +
|
||||
'moves: ' + moves.join(', ') + '\n' +
|
||||
'removals: ' + removals.join(', ') + '\n' +
|
||||
'identityChanges: ' + identityChanges.join(', ') + '\n';
|
||||
}
|
||||
|
||||
export function kvChangesAsString(
|
||||
@@ -19,7 +21,9 @@ export function kvChangesAsString(
|
||||
if (isBlank(changes)) changes = [];
|
||||
if (isBlank(removals)) removals = [];
|
||||
|
||||
return "map: " + map.join(', ') + "\n" + "previous: " + previous.join(', ') + "\n" +
|
||||
"additions: " + additions.join(', ') + "\n" + "changes: " + changes.join(', ') + "\n" +
|
||||
"removals: " + removals.join(', ') + "\n";
|
||||
return 'map: ' + map.join(', ') + '\n' +
|
||||
'previous: ' + previous.join(', ') + '\n' +
|
||||
'additions: ' + additions.join(', ') + '\n' +
|
||||
'changes: ' + changes.join(', ') + '\n' +
|
||||
'removals: ' + removals.join(', ') + '\n';
|
||||
}
|
||||
|
||||
@@ -1,18 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
xdescribe,
|
||||
describe,
|
||||
dispatchEvent,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
beforeEachProviders,
|
||||
it,
|
||||
xit,
|
||||
TestComponentBuilder
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, dispatchEvent, expect, iit, inject, beforeEachProviders, it, xit, TestComponentBuilder} from 'angular2/testing_internal';
|
||||
|
||||
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
|
||||
|
||||
@@ -187,74 +173,70 @@ export function main() {
|
||||
describe('debug element', function() {
|
||||
it('should list all child nodes',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.createAsync(ParentComp)
|
||||
.then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
tcb.createAsync(ParentComp).then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
|
||||
// The root component has 3 elements and 2 text node children.
|
||||
expect(fixture.debugElement.childNodes.length).toEqual(5);
|
||||
async.done();
|
||||
});
|
||||
// The root component has 3 elements and 2 text node children.
|
||||
expect(fixture.debugElement.childNodes.length).toEqual(5);
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should list all component child elements',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
|
||||
tcb.createAsync(ParentComp)
|
||||
.then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
tcb.createAsync(ParentComp).then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
|
||||
var childEls = fixture.debugElement.children;
|
||||
var childEls = fixture.debugElement.children;
|
||||
|
||||
// The root component has 3 elements in its view.
|
||||
expect(childEls.length).toEqual(3);
|
||||
expect(DOM.hasClass(childEls[0].nativeElement, 'parent')).toBe(true);
|
||||
expect(DOM.hasClass(childEls[1].nativeElement, 'parent')).toBe(true);
|
||||
expect(DOM.hasClass(childEls[2].nativeElement, 'child-comp-class')).toBe(true);
|
||||
// The root component has 3 elements in its view.
|
||||
expect(childEls.length).toEqual(3);
|
||||
expect(DOM.hasClass(childEls[0].nativeElement, 'parent')).toBe(true);
|
||||
expect(DOM.hasClass(childEls[1].nativeElement, 'parent')).toBe(true);
|
||||
expect(DOM.hasClass(childEls[2].nativeElement, 'child-comp-class')).toBe(true);
|
||||
|
||||
var nested = childEls[0].children;
|
||||
expect(nested.length).toEqual(1);
|
||||
expect(DOM.hasClass(nested[0].nativeElement, 'parentnested')).toBe(true);
|
||||
var nested = childEls[0].children;
|
||||
expect(nested.length).toEqual(1);
|
||||
expect(DOM.hasClass(nested[0].nativeElement, 'parentnested')).toBe(true);
|
||||
|
||||
var childComponent = childEls[2];
|
||||
var childComponent = childEls[2];
|
||||
|
||||
var childCompChildren = childComponent.children;
|
||||
expect(childCompChildren.length).toEqual(2);
|
||||
expect(DOM.hasClass(childCompChildren[0].nativeElement, 'child')).toBe(true);
|
||||
expect(DOM.hasClass(childCompChildren[1].nativeElement, 'child')).toBe(true);
|
||||
var childCompChildren = childComponent.children;
|
||||
expect(childCompChildren.length).toEqual(2);
|
||||
expect(DOM.hasClass(childCompChildren[0].nativeElement, 'child')).toBe(true);
|
||||
expect(DOM.hasClass(childCompChildren[1].nativeElement, 'child')).toBe(true);
|
||||
|
||||
var childNested = childCompChildren[0].children;
|
||||
expect(childNested.length).toEqual(1);
|
||||
expect(DOM.hasClass(childNested[0].nativeElement, 'childnested')).toBe(true);
|
||||
var childNested = childCompChildren[0].children;
|
||||
expect(childNested.length).toEqual(1);
|
||||
expect(DOM.hasClass(childNested[0].nativeElement, 'childnested')).toBe(true);
|
||||
|
||||
async.done();
|
||||
});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should list conditional component child elements',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.createAsync(ConditionalParentComp)
|
||||
.then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
tcb.createAsync(ConditionalParentComp).then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
|
||||
var childEls = fixture.debugElement.children;
|
||||
var childEls = fixture.debugElement.children;
|
||||
|
||||
// The root component has 2 elements in its view.
|
||||
expect(childEls.length).toEqual(2);
|
||||
expect(DOM.hasClass(childEls[0].nativeElement, 'parent')).toBe(true);
|
||||
expect(DOM.hasClass(childEls[1].nativeElement, 'cond-content-comp-class'))
|
||||
.toBe(true);
|
||||
// The root component has 2 elements in its view.
|
||||
expect(childEls.length).toEqual(2);
|
||||
expect(DOM.hasClass(childEls[0].nativeElement, 'parent')).toBe(true);
|
||||
expect(DOM.hasClass(childEls[1].nativeElement, 'cond-content-comp-class')).toBe(true);
|
||||
|
||||
var conditionalContentComp = childEls[1];
|
||||
var conditionalContentComp = childEls[1];
|
||||
|
||||
expect(conditionalContentComp.children.length).toEqual(0);
|
||||
expect(conditionalContentComp.children.length).toEqual(0);
|
||||
|
||||
conditionalContentComp.componentInstance.myBool = true;
|
||||
fixture.detectChanges();
|
||||
conditionalContentComp.componentInstance.myBool = true;
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(conditionalContentComp.children.length).toEqual(1);
|
||||
async.done();
|
||||
});
|
||||
expect(conditionalContentComp.children.length).toEqual(1);
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should list child elements within viewports',
|
||||
@@ -288,109 +270,103 @@ export function main() {
|
||||
|
||||
it('should query child elements by css',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.createAsync(ParentComp)
|
||||
.then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
tcb.createAsync(ParentComp).then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
|
||||
var childTestEls = fixture.debugElement.queryAll(By.css('child-comp'));
|
||||
var childTestEls = fixture.debugElement.queryAll(By.css('child-comp'));
|
||||
|
||||
expect(childTestEls.length).toBe(1);
|
||||
expect(DOM.hasClass(childTestEls[0].nativeElement, 'child-comp-class')).toBe(true);
|
||||
expect(childTestEls.length).toBe(1);
|
||||
expect(DOM.hasClass(childTestEls[0].nativeElement, 'child-comp-class')).toBe(true);
|
||||
|
||||
async.done();
|
||||
});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should query child elements by directive',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.createAsync(ParentComp)
|
||||
.then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
tcb.createAsync(ParentComp).then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
|
||||
var childTestEls = fixture.debugElement.queryAll(By.directive(MessageDir));
|
||||
var childTestEls = fixture.debugElement.queryAll(By.directive(MessageDir));
|
||||
|
||||
expect(childTestEls.length).toBe(4);
|
||||
expect(DOM.hasClass(childTestEls[0].nativeElement, 'parent')).toBe(true);
|
||||
expect(DOM.hasClass(childTestEls[1].nativeElement, 'parentnested')).toBe(true);
|
||||
expect(DOM.hasClass(childTestEls[2].nativeElement, 'child')).toBe(true);
|
||||
expect(DOM.hasClass(childTestEls[3].nativeElement, 'childnested')).toBe(true);
|
||||
expect(childTestEls.length).toBe(4);
|
||||
expect(DOM.hasClass(childTestEls[0].nativeElement, 'parent')).toBe(true);
|
||||
expect(DOM.hasClass(childTestEls[1].nativeElement, 'parentnested')).toBe(true);
|
||||
expect(DOM.hasClass(childTestEls[2].nativeElement, 'child')).toBe(true);
|
||||
expect(DOM.hasClass(childTestEls[3].nativeElement, 'childnested')).toBe(true);
|
||||
|
||||
async.done();
|
||||
});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should list providerTokens',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
|
||||
tcb.createAsync(ParentComp)
|
||||
.then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
tcb.createAsync(ParentComp).then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.debugElement.providerTokens).toContain(Logger);
|
||||
expect(fixture.debugElement.providerTokens).toContain(Logger);
|
||||
|
||||
async.done();
|
||||
});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should list locals',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.createAsync(LocalsComp)
|
||||
.then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
tcb.createAsync(LocalsComp).then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.debugElement.children[0].getLocal('alice')).toBeAnInstanceOf(MyDir);
|
||||
expect(fixture.debugElement.children[0].getLocal('alice')).toBeAnInstanceOf(MyDir);
|
||||
|
||||
async.done();
|
||||
});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should allow injecting from the element injector',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
|
||||
tcb.createAsync(ParentComp)
|
||||
.then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
tcb.createAsync(ParentComp).then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.debugElement.children[0].inject(Logger).log)
|
||||
.toEqual(['parent', 'nestedparent', 'child', 'nestedchild']);
|
||||
expect(fixture.debugElement.children[0].inject(Logger).log).toEqual([
|
||||
'parent', 'nestedparent', 'child', 'nestedchild'
|
||||
]);
|
||||
|
||||
async.done();
|
||||
});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should list event listeners',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
|
||||
tcb.createAsync(EventsComp)
|
||||
.then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
tcb.createAsync(EventsComp).then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.debugElement.children[0].listeners.length).toEqual(1);
|
||||
expect(fixture.debugElement.children[1].listeners.length).toEqual(1);
|
||||
expect(fixture.debugElement.children[0].listeners.length).toEqual(1);
|
||||
expect(fixture.debugElement.children[1].listeners.length).toEqual(1);
|
||||
|
||||
async.done();
|
||||
});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
|
||||
it('should trigger event handlers',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
|
||||
tcb.createAsync(EventsComp)
|
||||
.then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
tcb.createAsync(EventsComp).then((fixture) => {
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.debugElement.componentInstance.clicked).toBe(false);
|
||||
expect(fixture.debugElement.componentInstance.customed).toBe(false);
|
||||
expect(fixture.debugElement.componentInstance.clicked).toBe(false);
|
||||
expect(fixture.debugElement.componentInstance.customed).toBe(false);
|
||||
|
||||
fixture.debugElement.children[0].triggerEventHandler('click', <Event>{});
|
||||
expect(fixture.debugElement.componentInstance.clicked).toBe(true);
|
||||
fixture.debugElement.children[0].triggerEventHandler('click', <Event>{});
|
||||
expect(fixture.debugElement.componentInstance.clicked).toBe(true);
|
||||
|
||||
fixture.debugElement.children[1].triggerEventHandler('myevent', <Event>{});
|
||||
expect(fixture.debugElement.componentInstance.customed).toBe(true);
|
||||
fixture.debugElement.children[1].triggerEventHandler('myevent', <Event>{});
|
||||
expect(fixture.debugElement.componentInstance.customed).toBe(true);
|
||||
|
||||
async.done();
|
||||
});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,14 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal';
|
||||
|
||||
import {bind, provide} from 'angular2/core';
|
||||
|
||||
@@ -18,13 +8,15 @@ export function main() {
|
||||
describe('type errors', () => {
|
||||
|
||||
it('should throw when trying to create a class provider and not passing a class', () => {
|
||||
expect(() => { bind('foo').toClass(<any>0); })
|
||||
.toThrowError('Trying to create a class provider but "0" is not a class!');
|
||||
expect(() => {
|
||||
bind('foo').toClass(<any>0);
|
||||
}).toThrowError('Trying to create a class provider but "0" is not a class!');
|
||||
});
|
||||
|
||||
it('should throw when trying to create a factory provider and not passing a function', () => {
|
||||
expect(() => { bind('foo').toFactory(<any>0); })
|
||||
.toThrowError('Trying to create a factory provider but "0" is not a function!');
|
||||
expect(() => {
|
||||
bind('foo').toFactory(<any>0);
|
||||
}).toThrowError('Trying to create a factory provider but "0" is not a function!');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,19 +1,9 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal';
|
||||
import {forwardRef, resolveForwardRef} from 'angular2/src/core/di';
|
||||
import {Type} from 'angular2/src/facade/lang';
|
||||
|
||||
export function main() {
|
||||
describe("forwardRef", function() {
|
||||
describe('forwardRef', function() {
|
||||
it('should wrap and unwrap the reference', () => {
|
||||
var ref = forwardRef(() => String);
|
||||
expect(ref instanceof Type).toBe(true);
|
||||
|
||||
@@ -2,38 +2,18 @@ import {isBlank, stringify} from 'angular2/src/facade/lang';
|
||||
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
|
||||
import {describe, ddescribe, it, iit, expect, beforeEach} from 'angular2/testing_internal';
|
||||
import {SpyDependencyProvider} from '../spies';
|
||||
import {
|
||||
Injector,
|
||||
provide,
|
||||
ResolvedProvider,
|
||||
Key,
|
||||
forwardRef,
|
||||
Injectable,
|
||||
InjectMetadata,
|
||||
SelfMetadata,
|
||||
HostMetadata,
|
||||
SkipSelfMetadata,
|
||||
Optional,
|
||||
Inject,
|
||||
Provider
|
||||
} from 'angular2/core';
|
||||
import {Injector, provide, ResolvedProvider, Key, forwardRef, Injectable, InjectMetadata, SelfMetadata, HostMetadata, SkipSelfMetadata, Optional, Inject, Provider} from 'angular2/core';
|
||||
import {DependencyMetadata} from 'angular2/src/core/di/metadata';
|
||||
import {ResolvedProvider_} from 'angular2/src/core/di/provider';
|
||||
|
||||
import {
|
||||
InjectorInlineStrategy,
|
||||
InjectorDynamicStrategy,
|
||||
ProtoInjector,
|
||||
ProviderWithVisibility,
|
||||
Visibility
|
||||
} from 'angular2/src/core/di/injector';
|
||||
import {InjectorInlineStrategy, InjectorDynamicStrategy, ProtoInjector, ProviderWithVisibility, Visibility} from 'angular2/src/core/di/injector';
|
||||
|
||||
class CustomDependencyMetadata extends DependencyMetadata {}
|
||||
|
||||
class Engine {}
|
||||
|
||||
class BrokenEngine {
|
||||
constructor() { throw new BaseException("Broken Engine"); }
|
||||
constructor() { throw new BaseException('Broken Engine'); }
|
||||
}
|
||||
|
||||
class DashboardSoftware {}
|
||||
@@ -92,33 +72,28 @@ function factoryFn(a) {}
|
||||
|
||||
export function main() {
|
||||
var dynamicProviders = [
|
||||
provide('provider0', {useValue: 1}),
|
||||
provide('provider1', {useValue: 1}),
|
||||
provide('provider2', {useValue: 1}),
|
||||
provide('provider3', {useValue: 1}),
|
||||
provide('provider4', {useValue: 1}),
|
||||
provide('provider5', {useValue: 1}),
|
||||
provide('provider6', {useValue: 1}),
|
||||
provide('provider7', {useValue: 1}),
|
||||
provide('provider8', {useValue: 1}),
|
||||
provide('provider9', {useValue: 1}),
|
||||
provide('provider0', {useValue: 1}), provide('provider1', {useValue: 1}),
|
||||
provide('provider2', {useValue: 1}), provide('provider3', {useValue: 1}),
|
||||
provide('provider4', {useValue: 1}), provide('provider5', {useValue: 1}),
|
||||
provide('provider6', {useValue: 1}), provide('provider7', {useValue: 1}),
|
||||
provide('provider8', {useValue: 1}), provide('provider9', {useValue: 1}),
|
||||
provide('provider10', {useValue: 1})
|
||||
];
|
||||
|
||||
[{strategy: 'inline', providers: [], strategyClass: InjectorInlineStrategy},
|
||||
{
|
||||
strategy: 'dynamic',
|
||||
providers: dynamicProviders,
|
||||
strategyClass: InjectorDynamicStrategy
|
||||
}].forEach((context) => {
|
||||
[{strategy: 'inline', providers: [], strategyClass: InjectorInlineStrategy}, {
|
||||
strategy: 'dynamic',
|
||||
providers: dynamicProviders,
|
||||
strategyClass: InjectorDynamicStrategy
|
||||
}].forEach((context) => {
|
||||
function createInjector(providers: any[], parent: Injector = null, isHost: boolean = false) {
|
||||
return new Injector(ProtoInjector.fromResolvedProviders(
|
||||
Injector.resolve(providers.concat(context['providers']))),
|
||||
parent, isHost);
|
||||
return new Injector(
|
||||
ProtoInjector.fromResolvedProviders(
|
||||
Injector.resolve(providers.concat(context['providers']))),
|
||||
parent, isHost);
|
||||
}
|
||||
|
||||
describe(`injector ${context['strategy']}`, () => {
|
||||
it("should use the right strategy", () => {
|
||||
it('should use the right strategy', () => {
|
||||
var injector = createInjector([]);
|
||||
expect(injector.internalStrategy).toBeAnInstanceOf(context['strategyClass']);
|
||||
});
|
||||
@@ -149,17 +124,17 @@ export function main() {
|
||||
it('should throw when no type and not @Inject (class case)', () => {
|
||||
expect(() => createInjector([NoAnnotations]))
|
||||
.toThrowError(
|
||||
"Cannot resolve all parameters for 'NoAnnotations'(?). " +
|
||||
'Cannot resolve all parameters for \'NoAnnotations\'(?). ' +
|
||||
'Make sure that all the parameters are decorated with Inject or have valid type annotations ' +
|
||||
"and that 'NoAnnotations' is decorated with Injectable.");
|
||||
'and that \'NoAnnotations\' is decorated with Injectable.');
|
||||
});
|
||||
|
||||
it('should throw when no type and not @Inject (factory case)', () => {
|
||||
expect(() => createInjector([provide("someToken", {useFactory: factoryFn})]))
|
||||
expect(() => createInjector([provide('someToken', {useFactory: factoryFn})]))
|
||||
.toThrowError(
|
||||
"Cannot resolve all parameters for 'factoryFn'(?). " +
|
||||
'Cannot resolve all parameters for \'factoryFn\'(?). ' +
|
||||
'Make sure that all the parameters are decorated with Inject or have valid type annotations ' +
|
||||
"and that 'factoryFn' is decorated with Injectable.");
|
||||
'and that \'factoryFn\' is decorated with Injectable.');
|
||||
});
|
||||
|
||||
it('should cache instances', () => {
|
||||
@@ -172,10 +147,10 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should provide to a value', () => {
|
||||
var injector = createInjector([provide(Engine, {useValue: "fake engine"})]);
|
||||
var injector = createInjector([provide(Engine, {useValue: 'fake engine'})]);
|
||||
|
||||
var engine = injector.get(Engine);
|
||||
expect(engine).toEqual("fake engine");
|
||||
expect(engine).toEqual('fake engine');
|
||||
});
|
||||
|
||||
it('should provide to a factory', () => {
|
||||
@@ -193,42 +168,22 @@ export function main() {
|
||||
function factoryWithTooManyArgs() { return new Car(null); }
|
||||
|
||||
var injector = createInjector([
|
||||
Engine,
|
||||
provide(Car,
|
||||
{
|
||||
useFactory: factoryWithTooManyArgs,
|
||||
deps: [
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine,
|
||||
Engine
|
||||
]
|
||||
})
|
||||
Engine, provide(Car, {
|
||||
useFactory: factoryWithTooManyArgs,
|
||||
deps: [
|
||||
Engine, Engine, Engine, Engine, Engine, Engine, Engine,
|
||||
Engine, Engine, Engine, Engine, Engine, Engine, Engine,
|
||||
Engine, Engine, Engine, Engine, Engine, Engine, Engine
|
||||
]
|
||||
})
|
||||
]);
|
||||
|
||||
try {
|
||||
injector.get(Car);
|
||||
throw "Must throw";
|
||||
throw 'Must throw';
|
||||
} catch (e) {
|
||||
expect(e.message)
|
||||
.toContain(`Cannot instantiate 'Car' because it has more than 20 dependencies`);
|
||||
expect(e.message).toContain(
|
||||
`Cannot instantiate 'Car' because it has more than 20 dependencies`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -240,8 +195,7 @@ export function main() {
|
||||
|
||||
it('should provide to an alias', () => {
|
||||
var injector = createInjector([
|
||||
Engine,
|
||||
provide(SportsCar, {useClass: SportsCar}),
|
||||
Engine, provide(SportsCar, {useClass: SportsCar}),
|
||||
provide(Car, {useExisting: SportsCar})
|
||||
]);
|
||||
|
||||
@@ -253,8 +207,7 @@ export function main() {
|
||||
|
||||
it('should support multiProviders', () => {
|
||||
var injector = createInjector([
|
||||
Engine,
|
||||
new Provider(Car, {useClass: SportsCar, multi: true}),
|
||||
Engine, new Provider(Car, {useClass: SportsCar, multi: true}),
|
||||
new Provider(Car, {useClass: CarWithOptionalEngine, multi: true})
|
||||
]);
|
||||
|
||||
@@ -282,7 +235,7 @@ export function main() {
|
||||
it('should handle forwardRef in useExisting', () => {
|
||||
var injector = createInjector([
|
||||
provide('originalEngine', {useClass: forwardRef(() => Engine)}),
|
||||
provide('aliasedEngine', {useExisting:<any>forwardRef(() => 'originalEngine')})
|
||||
provide('aliasedEngine', {useExisting: <any>forwardRef(() => 'originalEngine')})
|
||||
]);
|
||||
expect(injector.get('aliasedEngine')).toBeAnInstanceOf(Engine);
|
||||
});
|
||||
@@ -303,14 +256,14 @@ export function main() {
|
||||
expect(car.engine).toEqual(null);
|
||||
});
|
||||
|
||||
it("should flatten passed-in providers", () => {
|
||||
it('should flatten passed-in providers', () => {
|
||||
var injector = createInjector([[[Engine, Car]]]);
|
||||
|
||||
var car = injector.get(Car);
|
||||
expect(car).toBeAnInstanceOf(Car);
|
||||
});
|
||||
|
||||
it("should use the last provider when there are multiple providers for same token", () => {
|
||||
it('should use the last provider when there are multiple providers for same token', () => {
|
||||
var injector = createInjector(
|
||||
[provide(Engine, {useClass: Engine}), provide(Engine, {useClass: TurboEngine})]);
|
||||
|
||||
@@ -324,7 +277,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should throw when given invalid providers', () => {
|
||||
expect(() => createInjector(<any>["blah"]))
|
||||
expect(() => createInjector(<any>['blah']))
|
||||
.toThrowError(
|
||||
'Invalid provider - only instances of Provider and Type are allowed, got: blah');
|
||||
});
|
||||
@@ -366,10 +319,10 @@ export function main() {
|
||||
|
||||
try {
|
||||
injector.get(Car);
|
||||
throw "Must throw";
|
||||
throw 'Must throw';
|
||||
} catch (e) {
|
||||
expect(e.message)
|
||||
.toContain(`Error during instantiation of Engine! (${stringify(Car)} -> Engine)`);
|
||||
expect(e.message).toContain(
|
||||
`Error during instantiation of Engine! (${stringify(Car)} -> Engine)`);
|
||||
expect(e.originalException instanceof BaseException).toBeTruthy();
|
||||
expect(e.causeKey.token).toEqual(Engine);
|
||||
}
|
||||
@@ -384,14 +337,14 @@ export function main() {
|
||||
var protoChild =
|
||||
new ProtoInjector([new ProviderWithVisibility(carProvider, Visibility.Public)]);
|
||||
|
||||
var parent = new Injector(protoParent, null, false, null, () => "parentContext");
|
||||
var child = new Injector(protoChild, parent, false, null, () => "childContext");
|
||||
var parent = new Injector(protoParent, null, false, null, () => 'parentContext');
|
||||
var child = new Injector(protoChild, parent, false, null, () => 'childContext');
|
||||
|
||||
try {
|
||||
child.get(Car);
|
||||
throw "Must throw";
|
||||
throw 'Must throw';
|
||||
} catch (e) {
|
||||
expect(e.context).toEqual("childContext");
|
||||
expect(e.context).toEqual('childContext');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -403,7 +356,7 @@ export function main() {
|
||||
provide(Engine, {useFactory: (() => isBroken ? new BrokenEngine() : new Engine())})
|
||||
]);
|
||||
|
||||
expect(() => injector.get(Car)).toThrowError(new RegExp("Error"));
|
||||
expect(() => injector.get(Car)).toThrowError(new RegExp('Error'));
|
||||
|
||||
isBroken = false;
|
||||
|
||||
@@ -419,7 +372,7 @@ export function main() {
|
||||
var e = new Engine();
|
||||
|
||||
var depProvider = <any>new SpyDependencyProvider();
|
||||
depProvider.spy("getDependency").andReturn(e);
|
||||
depProvider.spy('getDependency').andReturn(e);
|
||||
|
||||
var providers = Injector.resolve([Car]);
|
||||
var proto =
|
||||
@@ -427,14 +380,14 @@ export function main() {
|
||||
var injector = new Injector(proto, null, false, depProvider);
|
||||
|
||||
expect(injector.get(Car).engine).toEqual(e);
|
||||
expect(depProvider.spy("getDependency"))
|
||||
.toHaveBeenCalledWith(injector, providers[0],
|
||||
providers[0].resolvedFactories[0].dependencies[0]);
|
||||
expect(depProvider.spy('getDependency'))
|
||||
.toHaveBeenCalledWith(
|
||||
injector, providers[0], providers[0].resolvedFactories[0].dependencies[0]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("child", () => {
|
||||
describe('child', () => {
|
||||
it('should load instances from parent injector', () => {
|
||||
var parent = Injector.resolveAndCreate([Engine]);
|
||||
var child = parent.resolveAndCreateChild([]);
|
||||
@@ -445,7 +398,7 @@ export function main() {
|
||||
expect(engineFromChild).toBe(engineFromParent);
|
||||
});
|
||||
|
||||
it("should not use the child providers when resolving the dependencies of a parent provider",
|
||||
it('should not use the child providers when resolving the dependencies of a parent provider',
|
||||
() => {
|
||||
var parent = Injector.resolveAndCreate([Car, Engine]);
|
||||
var child = parent.resolveAndCreateChild([provide(Engine, {useClass: TurboEngine})]);
|
||||
@@ -465,7 +418,7 @@ export function main() {
|
||||
expect(engineFromChild).toBeAnInstanceOf(TurboEngine);
|
||||
});
|
||||
|
||||
it("should give access to parent", () => {
|
||||
it('should give access to parent', () => {
|
||||
var parent = Injector.resolveAndCreate([]);
|
||||
var child = parent.resolveAndCreateChild([]);
|
||||
expect(child.parent).toBe(parent);
|
||||
@@ -496,9 +449,9 @@ export function main() {
|
||||
});
|
||||
});
|
||||
|
||||
describe("depedency resolution", () => {
|
||||
describe("@Self()", () => {
|
||||
it("should return a dependency from self", () => {
|
||||
describe('depedency resolution', () => {
|
||||
describe('@Self()', () => {
|
||||
it('should return a dependency from self', () => {
|
||||
var inj = Injector.resolveAndCreate([
|
||||
Engine,
|
||||
provide(Car, {useFactory: (e) => new Car(e), deps: [[Engine, new SelfMetadata()]]})
|
||||
@@ -507,28 +460,26 @@ export function main() {
|
||||
expect(inj.get(Car)).toBeAnInstanceOf(Car);
|
||||
});
|
||||
|
||||
it("should throw when not requested provider on self", () => {
|
||||
it('should throw when not requested provider on self', () => {
|
||||
var parent = Injector.resolveAndCreate([Engine]);
|
||||
var child = parent.resolveAndCreateChild([
|
||||
provide(Car, {useFactory: (e) => new Car(e), deps: [[Engine, new SelfMetadata()]]})
|
||||
]);
|
||||
var child = parent.resolveAndCreateChild([provide(
|
||||
Car, {useFactory: (e) => new Car(e), deps: [[Engine, new SelfMetadata()]]})]);
|
||||
|
||||
expect(() => child.get(Car))
|
||||
.toThrowError(`No provider for Engine! (${stringify(Car)} -> ${stringify(Engine)})`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("@Host()", () => {
|
||||
it("should return a dependency from same host", () => {
|
||||
describe('@Host()', () => {
|
||||
it('should return a dependency from same host', () => {
|
||||
var parent = Injector.resolveAndCreate([Engine]);
|
||||
var child = parent.resolveAndCreateChild([
|
||||
provide(Car, {useFactory: (e) => new Car(e), deps: [[Engine, new HostMetadata()]]})
|
||||
]);
|
||||
var child = parent.resolveAndCreateChild([provide(
|
||||
Car, {useFactory: (e) => new Car(e), deps: [[Engine, new HostMetadata()]]})]);
|
||||
|
||||
expect(child.get(Car)).toBeAnInstanceOf(Car);
|
||||
});
|
||||
|
||||
it("should return a private dependency declared at the host", () => {
|
||||
it('should return a private dependency declared at the host', () => {
|
||||
var engine = Injector.resolve([Engine])[0];
|
||||
var protoParent =
|
||||
new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Private)]);
|
||||
@@ -541,7 +492,7 @@ export function main() {
|
||||
expect(child.get(Car)).toBeAnInstanceOf(Car);
|
||||
});
|
||||
|
||||
it("should not return a public dependency declared at the host", () => {
|
||||
it('should not return a public dependency declared at the host', () => {
|
||||
var engine = Injector.resolve([Engine])[0];
|
||||
var protoParent =
|
||||
new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Public)]);
|
||||
@@ -555,7 +506,7 @@ export function main() {
|
||||
.toThrowError(`No provider for Engine! (${stringify(Car)} -> ${stringify(Engine)})`);
|
||||
});
|
||||
|
||||
it("should not skip self", () => {
|
||||
it('should not skip self', () => {
|
||||
var parent = Injector.resolveAndCreate([Engine]);
|
||||
var child = parent.resolveAndCreateChild([
|
||||
provide(Engine, {useClass: TurboEngine}),
|
||||
@@ -566,8 +517,8 @@ export function main() {
|
||||
});
|
||||
});
|
||||
|
||||
describe("default", () => {
|
||||
it("should return a private dependency declared at the host", () => {
|
||||
describe('default', () => {
|
||||
it('should return a private dependency declared at the host', () => {
|
||||
var engine = Injector.resolve([Engine])[0];
|
||||
var protoParent =
|
||||
new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Private)]);
|
||||
@@ -576,15 +527,16 @@ export function main() {
|
||||
var child = createInjector(
|
||||
[
|
||||
provide(Engine, {useClass: BrokenEngine}),
|
||||
provide(Car,
|
||||
{useFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]})
|
||||
provide(
|
||||
Car,
|
||||
{useFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]})
|
||||
],
|
||||
parent, true); // boundary
|
||||
|
||||
expect(child.get(Car)).toBeAnInstanceOf(Car);
|
||||
});
|
||||
|
||||
it("should return a public dependency declared at the host", () => {
|
||||
it('should return a public dependency declared at the host', () => {
|
||||
var engine = Injector.resolve([Engine])[0];
|
||||
var protoParent =
|
||||
new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Public)]);
|
||||
@@ -593,15 +545,16 @@ export function main() {
|
||||
var child = createInjector(
|
||||
[
|
||||
provide(Engine, {useClass: BrokenEngine}),
|
||||
provide(Car,
|
||||
{useFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]})
|
||||
provide(
|
||||
Car,
|
||||
{useFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]})
|
||||
],
|
||||
parent, true); // boundary
|
||||
|
||||
expect(child.get(Car)).toBeAnInstanceOf(Car);
|
||||
});
|
||||
|
||||
it("should not return a private dependency declared NOT at the host", () => {
|
||||
it('should not return a private dependency declared NOT at the host', () => {
|
||||
var engine = Injector.resolve([Engine])[0];
|
||||
var protoParent =
|
||||
new ProtoInjector([new ProviderWithVisibility(engine, Visibility.Private)]);
|
||||
@@ -610,8 +563,9 @@ export function main() {
|
||||
var child = createInjector(
|
||||
[
|
||||
provide(Engine, {useClass: BrokenEngine}),
|
||||
provide(Car,
|
||||
{useFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]})
|
||||
provide(
|
||||
Car,
|
||||
{useFactory: (e) => new Car(e), deps: [[Engine, new SkipSelfMetadata()]]})
|
||||
],
|
||||
parent, false);
|
||||
|
||||
@@ -619,7 +573,7 @@ export function main() {
|
||||
.toThrowError(`No provider for Engine! (${stringify(Car)} -> ${stringify(Engine)})`);
|
||||
});
|
||||
|
||||
it("should not skip self", () => {
|
||||
it('should not skip self', () => {
|
||||
var parent = Injector.resolveAndCreate([Engine]);
|
||||
var child = parent.resolveAndCreateChild([
|
||||
provide(Engine, {useClass: TurboEngine}),
|
||||
@@ -640,7 +594,7 @@ export function main() {
|
||||
});
|
||||
});
|
||||
|
||||
it("should support multi providers", () => {
|
||||
it('should support multi providers', () => {
|
||||
var provider = Injector.resolve([
|
||||
new Provider(Engine, {useClass: BrokenEngine, multi: true}),
|
||||
new Provider(Engine, {useClass: TurboEngine, multi: true})
|
||||
@@ -651,7 +605,7 @@ export function main() {
|
||||
expect(provider.resolvedFactories.length).toEqual(2);
|
||||
});
|
||||
|
||||
it("should support multi providers with only one provider", () => {
|
||||
it('should support multi providers with only one provider', () => {
|
||||
var provider =
|
||||
Injector.resolve([new Provider(Engine, {useClass: BrokenEngine, multi: true})])[0];
|
||||
|
||||
@@ -660,22 +614,23 @@ export function main() {
|
||||
expect(provider.resolvedFactories.length).toEqual(1);
|
||||
});
|
||||
|
||||
it("should throw when mixing multi providers with regular providers", () => {
|
||||
it('should throw when mixing multi providers with regular providers', () => {
|
||||
expect(() => {
|
||||
Injector.resolve([new Provider(Engine, {useClass: BrokenEngine, multi: true}), Engine]);
|
||||
}).toThrowErrorWith("Cannot mix multi providers and regular providers");
|
||||
}).toThrowErrorWith('Cannot mix multi providers and regular providers');
|
||||
|
||||
expect(() => {
|
||||
Injector.resolve([Engine, new Provider(Engine, {useClass: BrokenEngine, multi: true})]);
|
||||
}).toThrowErrorWith("Cannot mix multi providers and regular providers");
|
||||
}).toThrowErrorWith('Cannot mix multi providers and regular providers');
|
||||
});
|
||||
|
||||
it('should resolve forward references', () => {
|
||||
var providers = Injector.resolve([
|
||||
forwardRef(() => Engine),
|
||||
[provide(forwardRef(() => BrokenEngine), {useClass: forwardRef(() => Engine)})],
|
||||
provide(forwardRef(() => String),
|
||||
{useFactory: () => 'OK', deps: [forwardRef(() => Engine)]})
|
||||
provide(
|
||||
forwardRef(() => String),
|
||||
{useFactory: () => 'OK', deps: [forwardRef(() => Engine)]})
|
||||
]);
|
||||
|
||||
var engineProvider = providers[0];
|
||||
@@ -688,35 +643,33 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should support overriding factory dependencies with dependency annotations', () => {
|
||||
var providers = Injector.resolve([
|
||||
provide("token",
|
||||
{
|
||||
useFactory: (e) => "result",
|
||||
deps: [[new InjectMetadata("dep"), new CustomDependencyMetadata()]]
|
||||
})
|
||||
]);
|
||||
var providers = Injector.resolve([provide('token', {
|
||||
useFactory: (e) => 'result',
|
||||
deps: [[new InjectMetadata('dep'), new CustomDependencyMetadata()]]
|
||||
})]);
|
||||
|
||||
var provider = providers[0];
|
||||
|
||||
expect(provider.resolvedFactories[0].dependencies[0].key.token).toEqual("dep");
|
||||
expect(provider.resolvedFactories[0].dependencies[0].properties)
|
||||
.toEqual([new CustomDependencyMetadata()]);
|
||||
expect(provider.resolvedFactories[0].dependencies[0].key.token).toEqual('dep');
|
||||
expect(provider.resolvedFactories[0].dependencies[0].properties).toEqual([
|
||||
new CustomDependencyMetadata()
|
||||
]);
|
||||
});
|
||||
|
||||
it('should allow declaring dependencies with flat arrays', () => {
|
||||
var resolved = Injector.resolve(
|
||||
[provide('token', {useFactory: e => e, deps: [new InjectMetadata("dep")]})]);
|
||||
[provide('token', {useFactory: e => e, deps: [new InjectMetadata('dep')]})]);
|
||||
var nestedResolved = Injector.resolve(
|
||||
[provide('token', {useFactory: e => e, deps: [[new InjectMetadata("dep")]]})]);
|
||||
[provide('token', {useFactory: e => e, deps: [[new InjectMetadata('dep')]]})]);
|
||||
expect(resolved[0].resolvedFactories[0].dependencies[0].key.token)
|
||||
.toEqual(nestedResolved[0].resolvedFactories[0].dependencies[0].key.token);
|
||||
});
|
||||
});
|
||||
|
||||
describe("displayName", () => {
|
||||
it("should work", () => {
|
||||
describe('displayName', () => {
|
||||
it('should work', () => {
|
||||
expect(Injector.resolveAndCreate([Engine, BrokenEngine]).displayName)
|
||||
.toEqual('Injector(providers: [ "Engine" , "BrokenEngine" ])');
|
||||
.toEqual('Injector(providers: [ \'Engine\' , \'BrokenEngine\' ])');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import {describe, iit, it, expect, beforeEach} from 'angular2/testing_internal';
|
||||
import {Key, KeyRegistry} from 'angular2/src/core/di/key';
|
||||
|
||||
export function main() {
|
||||
describe("key", function() {
|
||||
describe('key', function() {
|
||||
var registry: KeyRegistry;
|
||||
|
||||
beforeEach(function() { registry = new KeyRegistry(); });
|
||||
|
||||
@@ -1,58 +1,38 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xdescribe,
|
||||
xit,
|
||||
Log,
|
||||
TestComponentBuilder
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit, Log, TestComponentBuilder} from 'angular2/testing_internal';
|
||||
|
||||
import {
|
||||
OnChanges,
|
||||
OnInit,
|
||||
DoCheck,
|
||||
AfterContentInit,
|
||||
AfterContentChecked,
|
||||
AfterViewInit,
|
||||
AfterViewChecked
|
||||
} from 'angular2/core';
|
||||
import {OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked} from 'angular2/core';
|
||||
import {Directive, Component, ViewMetadata} from 'angular2/src/core/metadata';
|
||||
|
||||
export function main() {
|
||||
describe('directive lifecycle integration spec', () => {
|
||||
|
||||
it('should invoke lifecycle methods ngOnChanges > ngOnInit > ngDoCheck > ngAfterContentChecked',
|
||||
inject([TestComponentBuilder, Log, AsyncTestCompleter], (tcb: TestComponentBuilder, log: Log,
|
||||
async) => {
|
||||
tcb.overrideView(
|
||||
MyComp,
|
||||
new ViewMetadata(
|
||||
{template: '<div [field]="123" lifecycle></div>', directives: [LifecycleCmp]}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
tc.detectChanges();
|
||||
inject(
|
||||
[TestComponentBuilder, Log, AsyncTestCompleter],
|
||||
(tcb: TestComponentBuilder, log: Log, async) => {
|
||||
tcb.overrideView(MyComp, new ViewMetadata({
|
||||
template: '<div [field]="123" lifecycle></div>',
|
||||
directives: [LifecycleCmp]
|
||||
}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
tc.detectChanges();
|
||||
|
||||
expect(log.result())
|
||||
.toEqual(
|
||||
"ngOnChanges; ngOnInit; ngDoCheck; ngAfterContentInit; ngAfterContentChecked; child_ngDoCheck; " +
|
||||
"ngAfterViewInit; ngAfterViewChecked");
|
||||
expect(log.result())
|
||||
.toEqual(
|
||||
'ngOnChanges; ngOnInit; ngDoCheck; ngAfterContentInit; ngAfterContentChecked; child_ngDoCheck; ' +
|
||||
'ngAfterViewInit; ngAfterViewChecked');
|
||||
|
||||
log.clear();
|
||||
tc.detectChanges();
|
||||
log.clear();
|
||||
tc.detectChanges();
|
||||
|
||||
expect(log.result())
|
||||
.toEqual(
|
||||
"ngDoCheck; ngAfterContentChecked; child_ngDoCheck; ngAfterViewChecked");
|
||||
expect(log.result())
|
||||
.toEqual(
|
||||
'ngDoCheck; ngAfterContentChecked; child_ngDoCheck; ngAfterViewChecked');
|
||||
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -60,11 +40,11 @@ export function main() {
|
||||
@Directive({selector: '[lifecycle-dir]'})
|
||||
class LifecycleDir implements DoCheck {
|
||||
constructor(private _log: Log) {}
|
||||
ngDoCheck() { this._log.add("child_ngDoCheck"); }
|
||||
ngDoCheck() { this._log.add('child_ngDoCheck'); }
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: "[lifecycle]",
|
||||
selector: '[lifecycle]',
|
||||
inputs: ['field'],
|
||||
template: `<div lifecycle-dir></div>`,
|
||||
directives: [LifecycleDir]
|
||||
@@ -74,19 +54,19 @@ class LifecycleCmp implements OnChanges,
|
||||
field;
|
||||
constructor(private _log: Log) {}
|
||||
|
||||
ngOnChanges(_) { this._log.add("ngOnChanges"); }
|
||||
ngOnChanges(_) { this._log.add('ngOnChanges'); }
|
||||
|
||||
ngOnInit() { this._log.add("ngOnInit"); }
|
||||
ngOnInit() { this._log.add('ngOnInit'); }
|
||||
|
||||
ngDoCheck() { this._log.add("ngDoCheck"); }
|
||||
ngDoCheck() { this._log.add('ngDoCheck'); }
|
||||
|
||||
ngAfterContentInit() { this._log.add("ngAfterContentInit"); }
|
||||
ngAfterContentInit() { this._log.add('ngAfterContentInit'); }
|
||||
|
||||
ngAfterContentChecked() { this._log.add("ngAfterContentChecked"); }
|
||||
ngAfterContentChecked() { this._log.add('ngAfterContentChecked'); }
|
||||
|
||||
ngAfterViewInit() { this._log.add("ngAfterViewInit"); }
|
||||
ngAfterViewInit() { this._log.add('ngAfterViewInit'); }
|
||||
|
||||
ngAfterViewChecked() { this._log.add("ngAfterViewChecked"); }
|
||||
ngAfterViewChecked() { this._log.add('ngAfterViewChecked'); }
|
||||
}
|
||||
|
||||
@Component({selector: 'my-comp', directives: []})
|
||||
|
||||
@@ -1,18 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
beforeEachProviders,
|
||||
SpyObject,
|
||||
stringifyElement
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit, beforeEachProviders, SpyObject, stringifyElement} from 'angular2/testing_internal';
|
||||
|
||||
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
|
||||
|
||||
|
||||
@@ -1,15 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, describe, el, expect, iit, inject, it, xit} from 'angular2/testing_internal';
|
||||
|
||||
export function main() {
|
||||
describe('Shim', () => {
|
||||
|
||||
@@ -1,24 +1,12 @@
|
||||
import {
|
||||
describe,
|
||||
it,
|
||||
expect,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
iit,
|
||||
xit,
|
||||
el,
|
||||
SpyObject,
|
||||
AsyncTestCompleter,
|
||||
inject
|
||||
} from 'angular2/testing_internal';
|
||||
import {describe, it, expect, beforeEach, ddescribe, iit, xit, el, SpyObject, AsyncTestCompleter, inject} from 'angular2/testing_internal';
|
||||
|
||||
import {Observable, Subject, EventEmitter, PromiseWrapper} from 'angular2/src/facade/async';
|
||||
|
||||
export function main() {
|
||||
describe("Observable", () => {
|
||||
describe("#core", () => {
|
||||
describe('Observable', () => {
|
||||
describe('#core', () => {
|
||||
|
||||
it("should call next with values", inject([AsyncTestCompleter], (async) => {
|
||||
it('should call next with values', inject([AsyncTestCompleter], (async) => {
|
||||
|
||||
let o = new Observable(sink => { sink.next(1); });
|
||||
|
||||
@@ -29,7 +17,7 @@ export function main() {
|
||||
|
||||
}));
|
||||
|
||||
it("should call next and then complete", inject([AsyncTestCompleter], (async) => {
|
||||
it('should call next and then complete', inject([AsyncTestCompleter], (async) => {
|
||||
|
||||
let o = new Observable(sink => {
|
||||
sink.next(1);
|
||||
@@ -37,14 +25,16 @@ export function main() {
|
||||
});
|
||||
let nexted = false;
|
||||
|
||||
o.subscribe(v => { nexted = true; }, null, () => {
|
||||
expect(nexted).toBe(true);
|
||||
async.done();
|
||||
});
|
||||
o.subscribe(
|
||||
v => { nexted = true; }, null,
|
||||
() => {
|
||||
expect(nexted).toBe(true);
|
||||
async.done();
|
||||
});
|
||||
|
||||
}));
|
||||
|
||||
it("should call error with errors", inject([AsyncTestCompleter], (async) => {
|
||||
it('should call error with errors', inject([AsyncTestCompleter], (async) => {
|
||||
|
||||
let o = new Observable(sink => { sink.error('oh noes!'); });
|
||||
|
||||
|
||||
@@ -1,32 +1,11 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
TestComponentBuilder,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit
|
||||
} from 'angular2/testing_internal';
|
||||
import {
|
||||
bind,
|
||||
provide,
|
||||
forwardRef,
|
||||
resolveForwardRef,
|
||||
Component,
|
||||
Directive,
|
||||
Inject,
|
||||
Query,
|
||||
QueryList
|
||||
} from 'angular2/core';
|
||||
import {AsyncTestCompleter, TestComponentBuilder, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from 'angular2/testing_internal';
|
||||
import {bind, provide, forwardRef, resolveForwardRef, Component, Directive, Inject, Query, QueryList} from 'angular2/core';
|
||||
import {NgFor} from 'angular2/common';
|
||||
import {Type} from 'angular2/src/facade/lang';
|
||||
import {asNativeElements} from 'angular2/core';
|
||||
|
||||
export function main() {
|
||||
describe("forwardRef integration", function() {
|
||||
describe('forwardRef integration', function() {
|
||||
it('should instantiate components which are declared using forwardRef',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.createAsync(App).then((tc) => {
|
||||
@@ -56,8 +35,9 @@ class Door {
|
||||
locks: QueryList<Lock>;
|
||||
frame: Frame;
|
||||
|
||||
constructor(@Query(forwardRef(() => Lock)) locks: QueryList<Lock>,
|
||||
@Inject(forwardRef(() => Frame)) frame: Frame) {
|
||||
constructor(
|
||||
@Query(forwardRef(() => Lock)) locks: QueryList<Lock>,
|
||||
@Inject(forwardRef(() => Frame)) frame: Frame) {
|
||||
this.frame = frame;
|
||||
this.locks = locks;
|
||||
}
|
||||
|
||||
@@ -1,22 +1,9 @@
|
||||
import {
|
||||
ddescribe,
|
||||
describe,
|
||||
xdescribe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
AsyncTestCompleter,
|
||||
inject,
|
||||
beforeEachProviders
|
||||
} from 'angular2/testing_internal';
|
||||
import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal';
|
||||
|
||||
import {provide} from 'angular2/core';
|
||||
import {Compiler} from 'angular2/src/core/linker/compiler';
|
||||
import {reflector, ReflectionInfo} from 'angular2/src/core/reflection/reflection';
|
||||
import {Compiler_} from "angular2/src/core/linker/compiler";
|
||||
import {Compiler_} from 'angular2/src/core/linker/compiler';
|
||||
import {HostViewFactory} from 'angular2/src/core/linker/view';
|
||||
import {HostViewFactoryRef_} from 'angular2/src/core/linker/view_ref';
|
||||
|
||||
@@ -33,12 +20,11 @@ export function main() {
|
||||
|
||||
it('should read the template from an annotation',
|
||||
inject([AsyncTestCompleter, Compiler], (async, compiler: Compiler) => {
|
||||
compiler.compileInHost(SomeComponent)
|
||||
.then((hostViewFactoryRef: HostViewFactoryRef_) => {
|
||||
expect(hostViewFactoryRef.internalHostViewFactory).toBe(someHostViewFactory);
|
||||
async.done();
|
||||
return null;
|
||||
});
|
||||
compiler.compileInHost(SomeComponent).then((hostViewFactoryRef: HostViewFactoryRef_) => {
|
||||
expect(hostViewFactoryRef.internalHostViewFactory).toBe(someHostViewFactory);
|
||||
async.done();
|
||||
return null;
|
||||
});
|
||||
}));
|
||||
|
||||
it('should clear the cache', inject([Compiler], (compiler) => {
|
||||
|
||||
@@ -1,17 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
xdescribe,
|
||||
ddescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
SpyObject,
|
||||
proxy
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, xdescribe, ddescribe, describe, el, expect, iit, inject, it, SpyObject, proxy} from 'angular2/testing_internal';
|
||||
|
||||
import {hasLifecycleHook} from 'angular2/src/core/linker/directive_lifecycle_reflector';
|
||||
import {LifecycleHooks} from 'angular2/src/core/linker/interfaces';
|
||||
@@ -20,93 +7,93 @@ export function main() {
|
||||
describe('Create DirectiveMetadata', () => {
|
||||
describe('lifecycle', () => {
|
||||
|
||||
describe("ngOnChanges", () => {
|
||||
it("should be true when the directive has the ngOnChanges method", () => {
|
||||
describe('ngOnChanges', () => {
|
||||
it('should be true when the directive has the ngOnChanges method', () => {
|
||||
expect(hasLifecycleHook(LifecycleHooks.OnChanges, DirectiveWithOnChangesMethod))
|
||||
.toBe(true);
|
||||
});
|
||||
|
||||
it("should be false otherwise", () => {
|
||||
it('should be false otherwise', () => {
|
||||
expect(hasLifecycleHook(LifecycleHooks.OnChanges, DirectiveNoHooks)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ngOnDestroy", () => {
|
||||
it("should be true when the directive has the ngOnDestroy method", () => {
|
||||
describe('ngOnDestroy', () => {
|
||||
it('should be true when the directive has the ngOnDestroy method', () => {
|
||||
expect(hasLifecycleHook(LifecycleHooks.OnDestroy, DirectiveWithOnDestroyMethod))
|
||||
.toBe(true);
|
||||
});
|
||||
|
||||
it("should be false otherwise", () => {
|
||||
it('should be false otherwise', () => {
|
||||
expect(hasLifecycleHook(LifecycleHooks.OnDestroy, DirectiveNoHooks)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ngOnInit", () => {
|
||||
it("should be true when the directive has the ngOnInit method", () => {
|
||||
describe('ngOnInit', () => {
|
||||
it('should be true when the directive has the ngOnInit method', () => {
|
||||
expect(hasLifecycleHook(LifecycleHooks.OnInit, DirectiveWithOnInitMethod)).toBe(true);
|
||||
});
|
||||
|
||||
it("should be false otherwise", () => {
|
||||
it('should be false otherwise', () => {
|
||||
expect(hasLifecycleHook(LifecycleHooks.OnInit, DirectiveNoHooks)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ngDoCheck", () => {
|
||||
it("should be true when the directive has the ngDoCheck method", () => {
|
||||
describe('ngDoCheck', () => {
|
||||
it('should be true when the directive has the ngDoCheck method', () => {
|
||||
expect(hasLifecycleHook(LifecycleHooks.DoCheck, DirectiveWithOnCheckMethod)).toBe(true);
|
||||
});
|
||||
|
||||
it("should be false otherwise", () => {
|
||||
it('should be false otherwise', () => {
|
||||
expect(hasLifecycleHook(LifecycleHooks.DoCheck, DirectiveNoHooks)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ngAfterContentInit", () => {
|
||||
it("should be true when the directive has the ngAfterContentInit method", () => {
|
||||
expect(hasLifecycleHook(LifecycleHooks.AfterContentInit,
|
||||
DirectiveWithAfterContentInitMethod))
|
||||
describe('ngAfterContentInit', () => {
|
||||
it('should be true when the directive has the ngAfterContentInit method', () => {
|
||||
expect(hasLifecycleHook(
|
||||
LifecycleHooks.AfterContentInit, DirectiveWithAfterContentInitMethod))
|
||||
.toBe(true);
|
||||
});
|
||||
|
||||
it("should be false otherwise", () => {
|
||||
it('should be false otherwise', () => {
|
||||
expect(hasLifecycleHook(LifecycleHooks.AfterContentInit, DirectiveNoHooks)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ngAfterContentChecked", () => {
|
||||
it("should be true when the directive has the ngAfterContentChecked method", () => {
|
||||
expect(hasLifecycleHook(LifecycleHooks.AfterContentChecked,
|
||||
DirectiveWithAfterContentCheckedMethod))
|
||||
describe('ngAfterContentChecked', () => {
|
||||
it('should be true when the directive has the ngAfterContentChecked method', () => {
|
||||
expect(hasLifecycleHook(
|
||||
LifecycleHooks.AfterContentChecked, DirectiveWithAfterContentCheckedMethod))
|
||||
.toBe(true);
|
||||
});
|
||||
|
||||
it("should be false otherwise", () => {
|
||||
it('should be false otherwise', () => {
|
||||
expect(hasLifecycleHook(LifecycleHooks.AfterContentChecked, DirectiveNoHooks))
|
||||
.toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("ngAfterViewInit", () => {
|
||||
it("should be true when the directive has the ngAfterViewInit method", () => {
|
||||
describe('ngAfterViewInit', () => {
|
||||
it('should be true when the directive has the ngAfterViewInit method', () => {
|
||||
expect(hasLifecycleHook(LifecycleHooks.AfterViewInit, DirectiveWithAfterViewInitMethod))
|
||||
.toBe(true);
|
||||
});
|
||||
|
||||
it("should be false otherwise", () => {
|
||||
it('should be false otherwise', () => {
|
||||
expect(hasLifecycleHook(LifecycleHooks.AfterViewInit, DirectiveNoHooks)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ngAfterViewChecked", () => {
|
||||
it("should be true when the directive has the ngAfterViewChecked method", () => {
|
||||
expect(hasLifecycleHook(LifecycleHooks.AfterViewChecked,
|
||||
DirectiveWithAfterViewCheckedMethod))
|
||||
describe('ngAfterViewChecked', () => {
|
||||
it('should be true when the directive has the ngAfterViewChecked method', () => {
|
||||
expect(hasLifecycleHook(
|
||||
LifecycleHooks.AfterViewChecked, DirectiveWithAfterViewCheckedMethod))
|
||||
.toBe(true);
|
||||
});
|
||||
|
||||
it("should be false otherwise", () => {
|
||||
it('should be false otherwise', () => {
|
||||
expect(hasLifecycleHook(LifecycleHooks.AfterViewChecked, DirectiveNoHooks)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,21 +1,6 @@
|
||||
import {ddescribe, describe, it, iit, expect, beforeEach} from 'angular2/testing_internal';
|
||||
import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver';
|
||||
import {
|
||||
DirectiveMetadata,
|
||||
Directive,
|
||||
Input,
|
||||
Output,
|
||||
HostBinding,
|
||||
HostListener,
|
||||
ContentChildren,
|
||||
ContentChildrenMetadata,
|
||||
ViewChildren,
|
||||
ViewChildrenMetadata,
|
||||
ContentChild,
|
||||
ContentChildMetadata,
|
||||
ViewChild,
|
||||
ViewChildMetadata
|
||||
} from 'angular2/src/core/metadata';
|
||||
import {DirectiveMetadata, Directive, Input, Output, HostBinding, HostListener, ContentChildren, ContentChildrenMetadata, ViewChildren, ViewChildrenMetadata, ContentChild, ContentChildMetadata, ViewChild, ViewChildMetadata} from 'angular2/src/core/metadata';
|
||||
|
||||
@Directive({selector: 'someDirective'})
|
||||
class SomeDirective {
|
||||
@@ -28,14 +13,14 @@ class SomeChildDirective extends SomeDirective {
|
||||
@Directive({selector: 'someDirective', inputs: ['c']})
|
||||
class SomeDirectiveWithInputs {
|
||||
@Input() a;
|
||||
@Input("renamed") b;
|
||||
@Input('renamed') b;
|
||||
c;
|
||||
}
|
||||
|
||||
@Directive({selector: 'someDirective', outputs: ['c']})
|
||||
class SomeDirectiveWithOutputs {
|
||||
@Output() a;
|
||||
@Output("renamed") b;
|
||||
@Output('renamed') b;
|
||||
c;
|
||||
}
|
||||
|
||||
@@ -55,64 +40,59 @@ class SomeDirectiveWithEvents {
|
||||
|
||||
@Directive({selector: 'someDirective'})
|
||||
class SomeDirectiveWithSetterProps {
|
||||
@Input("renamed")
|
||||
set a(value) {
|
||||
}
|
||||
@Input('renamed')
|
||||
set a(value) {}
|
||||
}
|
||||
|
||||
@Directive({selector: 'someDirective'})
|
||||
class SomeDirectiveWithGetterOutputs {
|
||||
@Output("renamed")
|
||||
get a() {
|
||||
return null;
|
||||
}
|
||||
@Output('renamed')
|
||||
get a() { return null; }
|
||||
}
|
||||
|
||||
@Directive({selector: 'someDirective', host: {'[c]': 'c'}})
|
||||
class SomeDirectiveWithHostBindings {
|
||||
@HostBinding() a;
|
||||
@HostBinding("renamed") b;
|
||||
@HostBinding('renamed') b;
|
||||
c;
|
||||
}
|
||||
|
||||
@Directive({selector: 'someDirective', host: {'(c)': 'onC()'}})
|
||||
class SomeDirectiveWithHostListeners {
|
||||
@HostListener('a')
|
||||
onA() {
|
||||
}
|
||||
onA() {}
|
||||
@HostListener('b', ['$event.value'])
|
||||
onB(value) {
|
||||
}
|
||||
onB(value) {}
|
||||
}
|
||||
|
||||
@Directive({selector: 'someDirective', queries: {"cs": new ContentChildren("c")}})
|
||||
@Directive({selector: 'someDirective', queries: {'cs': new ContentChildren('c')}})
|
||||
class SomeDirectiveWithContentChildren {
|
||||
@ContentChildren("a") as: any;
|
||||
@ContentChildren('a') as: any;
|
||||
c;
|
||||
}
|
||||
|
||||
@Directive({selector: 'someDirective', queries: {"cs": new ViewChildren("c")}})
|
||||
@Directive({selector: 'someDirective', queries: {'cs': new ViewChildren('c')}})
|
||||
class SomeDirectiveWithViewChildren {
|
||||
@ViewChildren("a") as: any;
|
||||
@ViewChildren('a') as: any;
|
||||
c;
|
||||
}
|
||||
|
||||
@Directive({selector: 'someDirective', queries: {"c": new ContentChild("c")}})
|
||||
@Directive({selector: 'someDirective', queries: {'c': new ContentChild('c')}})
|
||||
class SomeDirectiveWithContentChild {
|
||||
@ContentChild("a") a: any;
|
||||
@ContentChild('a') a: any;
|
||||
c;
|
||||
}
|
||||
|
||||
@Directive({selector: 'someDirective', queries: {"c": new ViewChild("c")}})
|
||||
@Directive({selector: 'someDirective', queries: {'c': new ViewChild('c')}})
|
||||
class SomeDirectiveWithViewChild {
|
||||
@ViewChild("a") a: any;
|
||||
@ViewChild('a') a: any;
|
||||
c;
|
||||
}
|
||||
|
||||
class SomeDirectiveWithoutMetadata {}
|
||||
|
||||
export function main() {
|
||||
describe("DirectiveResolver", () => {
|
||||
describe('DirectiveResolver', () => {
|
||||
var resolver: DirectiveResolver;
|
||||
|
||||
beforeEach(() => { resolver = new DirectiveResolver(); });
|
||||
@@ -125,8 +105,9 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should throw if not matching metadata is found', () => {
|
||||
expect(() => { resolver.resolve(SomeDirectiveWithoutMetadata); })
|
||||
.toThrowError('No Directive annotation found on SomeDirectiveWithoutMetadata');
|
||||
expect(() => {
|
||||
resolver.resolve(SomeDirectiveWithoutMetadata);
|
||||
}).toThrowError('No Directive annotation found on SomeDirectiveWithoutMetadata');
|
||||
});
|
||||
|
||||
it('should not read parent class Directive metadata', function() {
|
||||
@@ -184,25 +165,25 @@ export function main() {
|
||||
it('should append ContentChildren', () => {
|
||||
var directiveMetadata = resolver.resolve(SomeDirectiveWithContentChildren);
|
||||
expect(directiveMetadata.queries)
|
||||
.toEqual({"cs": new ContentChildren("c"), "as": new ContentChildren("a")});
|
||||
.toEqual({'cs': new ContentChildren('c'), 'as': new ContentChildren('a')});
|
||||
});
|
||||
|
||||
it('should append ViewChildren', () => {
|
||||
var directiveMetadata = resolver.resolve(SomeDirectiveWithViewChildren);
|
||||
expect(directiveMetadata.queries)
|
||||
.toEqual({"cs": new ViewChildren("c"), "as": new ViewChildren("a")});
|
||||
.toEqual({'cs': new ViewChildren('c'), 'as': new ViewChildren('a')});
|
||||
});
|
||||
|
||||
it('should append ContentChild', () => {
|
||||
var directiveMetadata = resolver.resolve(SomeDirectiveWithContentChild);
|
||||
expect(directiveMetadata.queries)
|
||||
.toEqual({"c": new ContentChild("c"), "a": new ContentChild("a")});
|
||||
.toEqual({'c': new ContentChild('c'), 'a': new ContentChild('a')});
|
||||
});
|
||||
|
||||
it('should append ViewChild', () => {
|
||||
var directiveMetadata = resolver.resolve(SomeDirectiveWithViewChild);
|
||||
expect(directiveMetadata.queries)
|
||||
.toEqual({"c": new ViewChild("c"), "a": new ViewChild("a")});
|
||||
.toEqual({'c': new ViewChild('c'), 'a': new ViewChild('a')});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,20 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
xdescribe,
|
||||
describe,
|
||||
el,
|
||||
dispatchEvent,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
beforeEachProviders,
|
||||
it,
|
||||
xit,
|
||||
TestComponentBuilder,
|
||||
ComponentFixture
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, el, dispatchEvent, expect, iit, inject, beforeEachProviders, it, xit, TestComponentBuilder, ComponentFixture} from 'angular2/testing_internal';
|
||||
|
||||
import {OnDestroy} from 'angular2/core';
|
||||
import {Injector} from 'angular2/core';
|
||||
@@ -24,50 +8,48 @@ import {DynamicComponentLoader} from 'angular2/src/core/linker/dynamic_component
|
||||
import {ElementRef, ElementRef_} from 'angular2/src/core/linker/element_ref';
|
||||
import {DOCUMENT} from 'angular2/src/platform/dom/dom_tokens';
|
||||
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
|
||||
import {ComponentFixture_} from "angular2/src/testing/test_component_builder";
|
||||
import {ComponentFixture_} from 'angular2/src/testing/test_component_builder';
|
||||
import {BaseException} from 'angular2/src/facade/exceptions';
|
||||
import {PromiseWrapper} from 'angular2/src/facade/promise';
|
||||
import {stringify} from 'angular2/src/facade/lang';
|
||||
|
||||
export function main() {
|
||||
describe('DynamicComponentLoader', function() {
|
||||
describe("loading into a location", () => {
|
||||
describe('loading into a location', () => {
|
||||
it('should work',
|
||||
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(
|
||||
MyComp,
|
||||
new ViewMetadata(
|
||||
{template: '<location #loc></location>', directives: [Location]}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
loader.loadIntoLocation(DynamicallyLoaded, tc.elementRef, 'loc')
|
||||
.then(ref => {
|
||||
expect(tc.debugElement.nativeElement)
|
||||
.toHaveText("Location;DynamicallyLoaded;");
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
}));
|
||||
inject(
|
||||
[DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(
|
||||
MyComp, new ViewMetadata(
|
||||
{template: '<location #loc></location>', directives: [Location]}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
loader.loadIntoLocation(DynamicallyLoaded, tc.elementRef, 'loc').then(ref => {
|
||||
expect(tc.debugElement.nativeElement)
|
||||
.toHaveText('Location;DynamicallyLoaded;');
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
}));
|
||||
|
||||
it('should return a disposable component ref',
|
||||
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(
|
||||
MyComp,
|
||||
new ViewMetadata(
|
||||
{template: '<location #loc></location>', directives: [Location]}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
inject(
|
||||
[DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(
|
||||
MyComp, new ViewMetadata(
|
||||
{template: '<location #loc></location>', directives: [Location]}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
|
||||
loader.loadIntoLocation(DynamicallyLoaded, tc.elementRef, 'loc')
|
||||
.then(ref => {
|
||||
ref.dispose();
|
||||
expect(tc.debugElement.nativeElement).toHaveText("Location;");
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
}));
|
||||
loader.loadIntoLocation(DynamicallyLoaded, tc.elementRef, 'loc').then(ref => {
|
||||
ref.dispose();
|
||||
expect(tc.debugElement.nativeElement).toHaveText('Location;');
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
}));
|
||||
|
||||
it('should allow to dispose even if the location has been removed',
|
||||
inject(
|
||||
@@ -93,14 +75,14 @@ export function main() {
|
||||
loader.loadIntoLocation(DynamicallyLoaded, childElementRef, 'loc')
|
||||
.then(ref => {
|
||||
expect(tc.debugElement.nativeElement)
|
||||
.toHaveText("Location;DynamicallyLoaded;");
|
||||
.toHaveText('Location;DynamicallyLoaded;');
|
||||
|
||||
tc.debugElement.componentInstance.ctxBoolProp = false;
|
||||
tc.detectChanges();
|
||||
expect(tc.debugElement.nativeElement).toHaveText("");
|
||||
expect(tc.debugElement.nativeElement).toHaveText('');
|
||||
|
||||
ref.dispose();
|
||||
expect(tc.debugElement.nativeElement).toHaveText("");
|
||||
expect(tc.debugElement.nativeElement).toHaveText('');
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
@@ -117,85 +99,89 @@ export function main() {
|
||||
.then((tc) => {
|
||||
loader.loadIntoLocation(DynamicallyLoadedWithHostProps, tc.elementRef, 'loc')
|
||||
.then(ref => {
|
||||
ref.instance.id = "new value";
|
||||
ref.instance.id = 'new value';
|
||||
|
||||
tc.detectChanges();
|
||||
|
||||
var newlyInsertedElement =
|
||||
DOM.childNodes(tc.debugElement.nativeElement)[1];
|
||||
expect((<HTMLElement>newlyInsertedElement).id).toEqual("new value");
|
||||
expect((<HTMLElement>newlyInsertedElement).id).toEqual('new value');
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
}));
|
||||
|
||||
it('should leave the view tree in a consistent state if hydration fails',
|
||||
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MyComp, new ViewMetadata({
|
||||
template: '<div><location #loc></location></div>',
|
||||
directives: [Location]
|
||||
}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc: ComponentFixture) => {
|
||||
tc.debugElement
|
||||
inject(
|
||||
[DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MyComp, new ViewMetadata({
|
||||
template: '<div><location #loc></location></div>',
|
||||
directives: [Location]
|
||||
}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc: ComponentFixture) => {
|
||||
tc.debugElement
|
||||
|
||||
PromiseWrapper.catchError(
|
||||
loader.loadIntoLocation(DynamicallyLoadedThrows, tc.elementRef,
|
||||
'loc'),
|
||||
error => {
|
||||
expect(error.message).toContain("ThrownInConstructor");
|
||||
expect(() => tc.detectChanges()).not.toThrow();
|
||||
async.done();
|
||||
return null;
|
||||
});
|
||||
});
|
||||
}));
|
||||
PromiseWrapper.catchError(
|
||||
loader.loadIntoLocation(DynamicallyLoadedThrows, tc.elementRef, 'loc'),
|
||||
error => {
|
||||
expect(error.message).toContain('ThrownInConstructor');
|
||||
expect(() => tc.detectChanges()).not.toThrow();
|
||||
async.done();
|
||||
return null;
|
||||
});
|
||||
});
|
||||
}));
|
||||
|
||||
it('should throw if the variable does not exist',
|
||||
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(
|
||||
MyComp,
|
||||
new ViewMetadata(
|
||||
{template: '<location #loc></location>', directives: [Location]}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
expect(() => loader.loadIntoLocation(DynamicallyLoadedWithHostProps,
|
||||
tc.elementRef, 'someUnknownVariable'))
|
||||
.toThrowError('Could not find variable someUnknownVariable');
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
inject(
|
||||
[DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(
|
||||
MyComp, new ViewMetadata(
|
||||
{template: '<location #loc></location>', directives: [Location]}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
expect(
|
||||
() => loader.loadIntoLocation(
|
||||
DynamicallyLoadedWithHostProps, tc.elementRef, 'someUnknownVariable'))
|
||||
.toThrowError('Could not find variable someUnknownVariable');
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should allow to pass projectable nodes',
|
||||
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MyComp,
|
||||
new ViewMetadata({template: '<div #loc></div>', directives: []}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
loader.loadIntoLocation(DynamicallyLoadedWithNgContent, tc.elementRef,
|
||||
'loc', null, [[DOM.createTextNode('hello')]])
|
||||
.then(ref => {
|
||||
tc.detectChanges();
|
||||
expect(tc.nativeElement).toHaveText('dynamic(hello)');
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
}));
|
||||
inject(
|
||||
[DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(
|
||||
MyComp, new ViewMetadata({template: '<div #loc></div>', directives: []}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
loader
|
||||
.loadIntoLocation(
|
||||
DynamicallyLoadedWithNgContent, tc.elementRef, 'loc', null,
|
||||
[[DOM.createTextNode('hello')]])
|
||||
.then(ref => {
|
||||
tc.detectChanges();
|
||||
expect(tc.nativeElement).toHaveText('dynamic(hello)');
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
}));
|
||||
|
||||
it('should throw if not enough projectable nodes are passed in',
|
||||
inject(
|
||||
[DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MyComp,
|
||||
new ViewMetadata({template: '<div #loc></div>', directives: []}))
|
||||
tcb.overrideView(
|
||||
MyComp, new ViewMetadata({template: '<div #loc></div>', directives: []}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
PromiseWrapper.catchError(
|
||||
loader.loadIntoLocation(DynamicallyLoadedWithNgContent, tc.elementRef,
|
||||
'loc', null, []),
|
||||
loader.loadIntoLocation(
|
||||
DynamicallyLoadedWithNgContent, tc.elementRef, 'loc', null, []),
|
||||
(e) => {
|
||||
expect(e.message).toContain(
|
||||
`The component ${stringify(DynamicallyLoadedWithNgContent)} has 1 <ng-content> elements, but only 0 slots were provided`);
|
||||
@@ -207,152 +193,157 @@ export function main() {
|
||||
|
||||
});
|
||||
|
||||
describe("loading next to a location", () => {
|
||||
describe('loading next to a location', () => {
|
||||
it('should work',
|
||||
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MyComp, new ViewMetadata({
|
||||
template: '<div><location #loc></location></div>',
|
||||
directives: [Location]
|
||||
}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
loader.loadNextToLocation(DynamicallyLoaded, tc.elementRef)
|
||||
.then(ref => {
|
||||
expect(tc.debugElement.nativeElement).toHaveText("Location;");
|
||||
expect(DOM.nextSibling(tc.debugElement.nativeElement))
|
||||
.toHaveText('DynamicallyLoaded;');
|
||||
inject(
|
||||
[DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MyComp, new ViewMetadata({
|
||||
template: '<div><location #loc></location></div>',
|
||||
directives: [Location]
|
||||
}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
loader.loadNextToLocation(DynamicallyLoaded, tc.elementRef).then(ref => {
|
||||
expect(tc.debugElement.nativeElement).toHaveText('Location;');
|
||||
expect(DOM.nextSibling(tc.debugElement.nativeElement))
|
||||
.toHaveText('DynamicallyLoaded;');
|
||||
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
}));
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
}));
|
||||
|
||||
it('should return a disposable component ref',
|
||||
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MyComp, new ViewMetadata({
|
||||
template: '<div><location #loc></location></div>',
|
||||
directives: [Location]
|
||||
}))
|
||||
.
|
||||
inject(
|
||||
[DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MyComp, new ViewMetadata({
|
||||
template: '<div><location #loc></location></div>',
|
||||
directives: [Location]
|
||||
}))
|
||||
.
|
||||
|
||||
createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
loader.loadNextToLocation(DynamicallyLoaded, tc.elementRef)
|
||||
.then(ref => {
|
||||
loader.loadNextToLocation(DynamicallyLoaded2, tc.elementRef)
|
||||
.then(ref2 => {
|
||||
var firstSibling =
|
||||
DOM.nextSibling(tc.debugElement.nativeElement);
|
||||
var secondSibling = DOM.nextSibling(firstSibling);
|
||||
expect(tc.debugElement.nativeElement).toHaveText("Location;");
|
||||
expect(firstSibling).toHaveText("DynamicallyLoaded;");
|
||||
expect(secondSibling).toHaveText("DynamicallyLoaded2;");
|
||||
createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
loader.loadNextToLocation(DynamicallyLoaded, tc.elementRef).then(ref => {
|
||||
loader.loadNextToLocation(DynamicallyLoaded2, tc.elementRef).then(ref2 => {
|
||||
var firstSibling = DOM.nextSibling(tc.debugElement.nativeElement);
|
||||
var secondSibling = DOM.nextSibling(firstSibling);
|
||||
expect(tc.debugElement.nativeElement).toHaveText('Location;');
|
||||
expect(firstSibling).toHaveText('DynamicallyLoaded;');
|
||||
expect(secondSibling).toHaveText('DynamicallyLoaded2;');
|
||||
|
||||
ref2.dispose();
|
||||
ref2.dispose();
|
||||
|
||||
firstSibling = DOM.nextSibling(tc.debugElement.nativeElement);
|
||||
secondSibling = DOM.nextSibling(firstSibling);
|
||||
expect(secondSibling).toBeNull();
|
||||
firstSibling = DOM.nextSibling(tc.debugElement.nativeElement);
|
||||
secondSibling = DOM.nextSibling(firstSibling);
|
||||
expect(secondSibling).toBeNull();
|
||||
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
});
|
||||
}));
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
});
|
||||
}));
|
||||
|
||||
it('should update host properties',
|
||||
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MyComp, new ViewMetadata({
|
||||
template: '<div><location #loc></location></div>',
|
||||
directives: [Location]
|
||||
}))
|
||||
inject(
|
||||
[DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MyComp, new ViewMetadata({
|
||||
template: '<div><location #loc></location></div>',
|
||||
directives: [Location]
|
||||
}))
|
||||
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
|
||||
loader.loadNextToLocation(DynamicallyLoadedWithHostProps, tc.elementRef)
|
||||
.then(ref => {
|
||||
ref.instance.id = "new value";
|
||||
loader.loadNextToLocation(DynamicallyLoadedWithHostProps, tc.elementRef)
|
||||
.then(ref => {
|
||||
ref.instance.id = 'new value';
|
||||
|
||||
tc.detectChanges();
|
||||
tc.detectChanges();
|
||||
|
||||
var newlyInsertedElement =
|
||||
DOM.nextSibling(tc.debugElement.nativeElement);
|
||||
expect((<HTMLElement>newlyInsertedElement).id).toEqual("new value");
|
||||
var newlyInsertedElement =
|
||||
DOM.nextSibling(tc.debugElement.nativeElement);
|
||||
expect((<HTMLElement>newlyInsertedElement).id).toEqual('new value');
|
||||
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
}));
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
}));
|
||||
|
||||
it('should allow to pass projectable nodes',
|
||||
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MyComp, new ViewMetadata({template: '', directives: [Location]}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
loader.loadNextToLocation(DynamicallyLoadedWithNgContent, tc.elementRef,
|
||||
null, [[DOM.createTextNode('hello')]])
|
||||
.then(ref => {
|
||||
tc.detectChanges();
|
||||
var newlyInsertedElement =
|
||||
DOM.nextSibling(tc.debugElement.nativeElement);
|
||||
expect(newlyInsertedElement).toHaveText('dynamic(hello)');
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
}));
|
||||
inject(
|
||||
[DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
|
||||
(loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MyComp, new ViewMetadata({template: '', directives: [Location]}))
|
||||
.createAsync(MyComp)
|
||||
.then((tc) => {
|
||||
loader
|
||||
.loadNextToLocation(
|
||||
DynamicallyLoadedWithNgContent, tc.elementRef, null,
|
||||
[[DOM.createTextNode('hello')]])
|
||||
.then(ref => {
|
||||
tc.detectChanges();
|
||||
var newlyInsertedElement =
|
||||
DOM.nextSibling(tc.debugElement.nativeElement);
|
||||
expect(newlyInsertedElement).toHaveText('dynamic(hello)');
|
||||
async.done();
|
||||
});
|
||||
});
|
||||
}));
|
||||
|
||||
});
|
||||
|
||||
describe('loadAsRoot', () => {
|
||||
it('should allow to create, update and destroy components',
|
||||
inject([AsyncTestCompleter, DynamicComponentLoader, DOCUMENT, Injector],
|
||||
(async: AsyncTestCompleter, loader: DynamicComponentLoader, doc,
|
||||
injector: Injector) => {
|
||||
var rootEl = createRootElement(doc, 'child-cmp');
|
||||
DOM.appendChild(doc.body, rootEl);
|
||||
loader.loadAsRoot(ChildComp, null, injector)
|
||||
.then((componentRef) => {
|
||||
var el = new ComponentFixture_(componentRef);
|
||||
inject(
|
||||
[AsyncTestCompleter, DynamicComponentLoader, DOCUMENT, Injector],
|
||||
(async: AsyncTestCompleter, loader: DynamicComponentLoader, doc,
|
||||
injector: Injector) => {
|
||||
var rootEl = createRootElement(doc, 'child-cmp');
|
||||
DOM.appendChild(doc.body, rootEl);
|
||||
loader.loadAsRoot(ChildComp, null, injector).then((componentRef) => {
|
||||
var el = new ComponentFixture_(componentRef);
|
||||
|
||||
expect(rootEl.parentNode).toBe(doc.body);
|
||||
expect(rootEl.parentNode).toBe(doc.body);
|
||||
|
||||
el.detectChanges();
|
||||
el.detectChanges();
|
||||
|
||||
expect(rootEl).toHaveText('hello');
|
||||
expect(rootEl).toHaveText('hello');
|
||||
|
||||
componentRef.instance.ctxProp = 'new';
|
||||
componentRef.instance.ctxProp = 'new';
|
||||
|
||||
el.detectChanges();
|
||||
el.detectChanges();
|
||||
|
||||
expect(rootEl).toHaveText('new');
|
||||
expect(rootEl).toHaveText('new');
|
||||
|
||||
componentRef.dispose();
|
||||
componentRef.dispose();
|
||||
|
||||
expect(rootEl.parentNode).toBeFalsy();
|
||||
expect(rootEl.parentNode).toBeFalsy();
|
||||
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should allow to pass projectable nodes',
|
||||
inject([AsyncTestCompleter, DynamicComponentLoader, DOCUMENT, Injector],
|
||||
(async: AsyncTestCompleter, loader: DynamicComponentLoader, doc,
|
||||
injector: Injector) => {
|
||||
var rootEl = createRootElement(doc, 'dummy');
|
||||
DOM.appendChild(doc.body, rootEl);
|
||||
loader.loadAsRoot(DynamicallyLoadedWithNgContent, null, injector, null,
|
||||
[[DOM.createTextNode('hello')]])
|
||||
.then((_) => {
|
||||
expect(rootEl).toHaveText('dynamic(hello)');
|
||||
inject(
|
||||
[AsyncTestCompleter, DynamicComponentLoader, DOCUMENT, Injector],
|
||||
(async: AsyncTestCompleter, loader: DynamicComponentLoader, doc,
|
||||
injector: Injector) => {
|
||||
var rootEl = createRootElement(doc, 'dummy');
|
||||
DOM.appendChild(doc.body, rootEl);
|
||||
loader
|
||||
.loadAsRoot(
|
||||
DynamicallyLoadedWithNgContent, null, injector, null,
|
||||
[[DOM.createTextNode('hello')]])
|
||||
.then((_) => {
|
||||
expect(rootEl).toHaveText('dynamic(hello)');
|
||||
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
});
|
||||
|
||||
@@ -381,7 +372,7 @@ class DynamicallyCreatedComponentService {}
|
||||
@Component({
|
||||
selector: 'hello-cmp',
|
||||
viewProviders: [DynamicallyCreatedComponentService],
|
||||
template: "{{greeting}}"
|
||||
template: '{{greeting}}'
|
||||
})
|
||||
class DynamicallyCreatedCmp implements OnDestroy {
|
||||
greeting: string;
|
||||
@@ -389,41 +380,41 @@ class DynamicallyCreatedCmp implements OnDestroy {
|
||||
destroyed: boolean = false;
|
||||
|
||||
constructor(a: DynamicallyCreatedComponentService) {
|
||||
this.greeting = "hello";
|
||||
this.greeting = 'hello';
|
||||
this.dynamicallyCreatedComponentService = a;
|
||||
}
|
||||
|
||||
ngOnDestroy() { this.destroyed = true; }
|
||||
}
|
||||
|
||||
@Component({selector: 'dummy', template: "DynamicallyLoaded;"})
|
||||
@Component({selector: 'dummy', template: 'DynamicallyLoaded;'})
|
||||
class DynamicallyLoaded {
|
||||
}
|
||||
|
||||
@Component({selector: 'dummy', template: "DynamicallyLoaded;"})
|
||||
@Component({selector: 'dummy', template: 'DynamicallyLoaded;'})
|
||||
class DynamicallyLoadedThrows {
|
||||
constructor() { throw new BaseException("ThrownInConstructor"); }
|
||||
constructor() { throw new BaseException('ThrownInConstructor'); }
|
||||
}
|
||||
|
||||
@Component({selector: 'dummy', template: "DynamicallyLoaded2;"})
|
||||
@Component({selector: 'dummy', template: 'DynamicallyLoaded2;'})
|
||||
class DynamicallyLoaded2 {
|
||||
}
|
||||
|
||||
@Component({selector: 'dummy', host: {'[id]': 'id'}, template: "DynamicallyLoadedWithHostProps;"})
|
||||
@Component({selector: 'dummy', host: {'[id]': 'id'}, template: 'DynamicallyLoadedWithHostProps;'})
|
||||
class DynamicallyLoadedWithHostProps {
|
||||
id: string;
|
||||
|
||||
constructor() { this.id = "default"; }
|
||||
constructor() { this.id = 'default'; }
|
||||
}
|
||||
|
||||
@Component({selector: 'dummy', template: "dynamic(<ng-content></ng-content>)"})
|
||||
@Component({selector: 'dummy', template: 'dynamic(<ng-content></ng-content>)'})
|
||||
class DynamicallyLoadedWithNgContent {
|
||||
id: string;
|
||||
|
||||
constructor() { this.id = "default"; }
|
||||
constructor() { this.id = 'default'; }
|
||||
}
|
||||
|
||||
@Component({selector: 'location', template: "Location;"})
|
||||
@Component({selector: 'location', template: 'Location;'})
|
||||
class Location {
|
||||
elementRef: ElementRef;
|
||||
|
||||
|
||||
@@ -48,8 +48,8 @@ import {ElementRef} from 'angular2/src/core/linker/element_ref';
|
||||
import {DynamicChangeDetector, ChangeDetectorRef, Parser, Lexer} from 'angular2/src/core/change_detection/change_detection';
|
||||
import {ChangeDetectorRef_} from 'angular2/src/core/change_detection/change_detector_ref';
|
||||
import {QueryList} from 'angular2/src/core/linker/query_list';
|
||||
import {AppView, AppProtoView} from "angular2/src/core/linker/view";
|
||||
import {ViewType} from "angular2/src/core/linker/view_type";
|
||||
import {AppView, AppProtoView} from 'angular2/src/core/linker/view';
|
||||
import {ViewType} from 'angular2/src/core/linker/view_type';
|
||||
|
||||
@Directive({selector: ''})
|
||||
class SimpleDirective {}
|
||||
@@ -101,18 +101,18 @@ class NeedsDirectiveFromHostShadowDom {
|
||||
@Directive({selector: ''})
|
||||
class NeedsService {
|
||||
service: any;
|
||||
constructor(@Inject("service") service) { this.service = service; }
|
||||
constructor(@Inject('service') service) { this.service = service; }
|
||||
}
|
||||
|
||||
@Directive({selector: ''})
|
||||
class NeedsServiceFromHost {
|
||||
service: any;
|
||||
constructor(@Host() @Inject("service") service) { this.service = service; }
|
||||
constructor(@Host() @Inject('service') service) { this.service = service; }
|
||||
}
|
||||
|
||||
class HasEventEmitter {
|
||||
emitter;
|
||||
constructor() { this.emitter = "emitter"; }
|
||||
constructor() { this.emitter = 'emitter'; }
|
||||
}
|
||||
|
||||
@Directive({selector: ''})
|
||||
@@ -149,7 +149,7 @@ class NeedsViewQuery {
|
||||
@Directive({selector: ''})
|
||||
class NeedsQueryByVarBindings {
|
||||
query: QueryList<any>;
|
||||
constructor(@Query("one,two") query: QueryList<any>) { this.query = query; }
|
||||
constructor(@Query('one,two') query: QueryList<any>) { this.query = query; }
|
||||
}
|
||||
|
||||
@Directive({selector: ''})
|
||||
@@ -334,11 +334,11 @@ export function main() {
|
||||
}));
|
||||
}
|
||||
|
||||
describe("ProtoAppElement", () => {
|
||||
describe('ProtoAppElement', () => {
|
||||
init();
|
||||
|
||||
describe('inline strategy', () => {
|
||||
it("should allow for direct access using getProviderAtIndex", () => {
|
||||
it('should allow for direct access using getProviderAtIndex', () => {
|
||||
var proto = protoAppElement(0, [SimpleDirective]);
|
||||
|
||||
expect(proto.getProviderAtIndex(0)).toBeAnInstanceOf(DirectiveProvider);
|
||||
@@ -348,7 +348,7 @@ export function main() {
|
||||
});
|
||||
|
||||
describe('dynamic strategy', () => {
|
||||
it("should allow for direct access using getProviderAtIndex", () => {
|
||||
it('should allow for direct access using getProviderAtIndex', () => {
|
||||
var proto = protoAppElement(0, dynamicStrategyDirectives);
|
||||
|
||||
expect(proto.getProviderAtIndex(0)).toBeAnInstanceOf(DirectiveProvider);
|
||||
@@ -359,8 +359,8 @@ export function main() {
|
||||
});
|
||||
});
|
||||
|
||||
describe(".create", () => {
|
||||
it("should collect providers from all directives", () => {
|
||||
describe('.create', () => {
|
||||
it('should collect providers from all directives', () => {
|
||||
mockDirectiveMeta.set(SimpleDirective, new DirectiveMetadata({providers: [provide('injectable1', {useValue: 'injectable1'})]}));
|
||||
mockDirectiveMeta.set(SomeOtherDirective, new DirectiveMetadata({
|
||||
providers: [provide('injectable2', {useValue: 'injectable2'})]
|
||||
@@ -372,21 +372,21 @@ export function main() {
|
||||
|
||||
expect(pel.getProviderAtIndex(0).key.token).toBe(SimpleDirective);
|
||||
expect(pel.getProviderAtIndex(1).key.token).toBe(SomeOtherDirective);
|
||||
expect(pel.getProviderAtIndex(2).key.token).toEqual("injectable1");
|
||||
expect(pel.getProviderAtIndex(3).key.token).toEqual("injectable2");
|
||||
expect(pel.getProviderAtIndex(2).key.token).toEqual('injectable1');
|
||||
expect(pel.getProviderAtIndex(3).key.token).toEqual('injectable2');
|
||||
});
|
||||
|
||||
it("should collect view providers from the component", () => {
|
||||
it('should collect view providers from the component', () => {
|
||||
mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({
|
||||
viewProviders: [provide('injectable1', {useValue: 'injectable1'})]
|
||||
}));
|
||||
var pel = protoAppElement(0, [SimpleDirective]);
|
||||
|
||||
expect(pel.getProviderAtIndex(0).key.token).toBe(SimpleDirective);
|
||||
expect(pel.getProviderAtIndex(1).key.token).toEqual("injectable1");
|
||||
expect(pel.getProviderAtIndex(1).key.token).toEqual('injectable1');
|
||||
});
|
||||
|
||||
it("should flatten nested arrays in viewProviders and providers", () => {
|
||||
it('should flatten nested arrays in viewProviders and providers', () => {
|
||||
mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({
|
||||
viewProviders: [[[provide('view', {useValue: 'view'})]]],
|
||||
providers: [[[provide('host', {useValue: 'host'})]]]
|
||||
@@ -394,8 +394,8 @@ export function main() {
|
||||
var pel = protoAppElement(0, [SimpleDirective]);
|
||||
|
||||
expect(pel.getProviderAtIndex(0).key.token).toBe(SimpleDirective);
|
||||
expect(pel.getProviderAtIndex(1).key.token).toEqual("view");
|
||||
expect(pel.getProviderAtIndex(2).key.token).toEqual("host");
|
||||
expect(pel.getProviderAtIndex(1).key.token).toEqual('view');
|
||||
expect(pel.getProviderAtIndex(2).key.token).toEqual('host');
|
||||
});
|
||||
|
||||
it('should support an arbitrary number of providers', () => {
|
||||
@@ -406,7 +406,7 @@ export function main() {
|
||||
});
|
||||
});
|
||||
|
||||
describe("AppElement", () => {
|
||||
describe('AppElement', () => {
|
||||
init();
|
||||
|
||||
[{ strategy: 'inline', directives: [] }, { strategy: 'dynamic',
|
||||
@@ -415,14 +415,14 @@ export function main() {
|
||||
var extraDirectives = context['directives'];
|
||||
describe(`${context['strategy']} strategy`, () => {
|
||||
|
||||
describe("injection", () => {
|
||||
it("should instantiate directives that have no dependencies", () => {
|
||||
describe('injection', () => {
|
||||
it('should instantiate directives that have no dependencies', () => {
|
||||
var directives = ListWrapper.concat([SimpleDirective], extraDirectives);
|
||||
var el = appElement(null, directives);
|
||||
expect(el.get(SimpleDirective)).toBeAnInstanceOf(SimpleDirective);
|
||||
});
|
||||
|
||||
it("should instantiate directives that depend on an arbitrary number of directives", () => {
|
||||
it('should instantiate directives that depend on an arbitrary number of directives', () => {
|
||||
var directives = ListWrapper.concat([SimpleDirective, NeedsDirective], extraDirectives);
|
||||
var el = appElement(null, directives);
|
||||
|
||||
@@ -432,7 +432,7 @@ export function main() {
|
||||
expect(d.dependency).toBeAnInstanceOf(SimpleDirective);
|
||||
});
|
||||
|
||||
it("should instantiate providers that have dependencies with set visibility",
|
||||
it('should instantiate providers that have dependencies with set visibility',
|
||||
function() {
|
||||
mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({
|
||||
providers: [provide('injectable1', {useValue: 'injectable1'})]
|
||||
@@ -452,7 +452,7 @@ export function main() {
|
||||
expect(childInj.get('injectable2')).toEqual('injectable1-injectable2');
|
||||
});
|
||||
|
||||
it("should instantiate providers that have dependencies", () => {
|
||||
it('should instantiate providers that have dependencies', () => {
|
||||
var providers = [
|
||||
provide('injectable1', {useValue: 'injectable1'}),
|
||||
provide('injectable2', {useFactory:
|
||||
@@ -466,7 +466,7 @@ export function main() {
|
||||
expect(el.get('injectable2')).toEqual('injectable1-injectable2');
|
||||
});
|
||||
|
||||
it("should instantiate viewProviders that have dependencies", () => {
|
||||
it('should instantiate viewProviders that have dependencies', () => {
|
||||
var viewProviders = [
|
||||
provide('injectable1', {useValue: 'injectable1'}),
|
||||
provide('injectable2', {useFactory:
|
||||
@@ -481,7 +481,7 @@ export function main() {
|
||||
expect(el.get('injectable2')).toEqual('injectable1-injectable2');
|
||||
});
|
||||
|
||||
it("should instantiate components that depend on viewProviders providers", () => {
|
||||
it('should instantiate components that depend on viewProviders providers', () => {
|
||||
mockDirectiveMeta.set(NeedsService, new ComponentMetadata({
|
||||
viewProviders: [provide('service', {useValue: 'service'})]
|
||||
}));
|
||||
@@ -490,7 +490,7 @@ export function main() {
|
||||
expect(el.get(NeedsService).service).toEqual('service');
|
||||
});
|
||||
|
||||
it("should instantiate providers lazily", () => {
|
||||
it('should instantiate providers lazily', () => {
|
||||
var created = false;
|
||||
mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({
|
||||
providers: [provide('service', {useFactory: () => created = true})]
|
||||
@@ -506,7 +506,7 @@ export function main() {
|
||||
expect(created).toBe(true);
|
||||
});
|
||||
|
||||
it("should instantiate view providers lazily", () => {
|
||||
it('should instantiate view providers lazily', () => {
|
||||
var created = false;
|
||||
mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({
|
||||
viewProviders: [provide('service', {useFactory: () => created = true})]
|
||||
@@ -522,18 +522,18 @@ export function main() {
|
||||
expect(created).toBe(true);
|
||||
});
|
||||
|
||||
it("should not instantiate other directives that depend on viewProviders providers",
|
||||
it('should not instantiate other directives that depend on viewProviders providers',
|
||||
() => {
|
||||
mockDirectiveMeta.set(SimpleDirective,
|
||||
new ComponentMetadata({
|
||||
viewProviders: [provide("service", {useValue: "service"})]
|
||||
viewProviders: [provide('service', {useValue: 'service'})]
|
||||
}));
|
||||
expect(() => { appElement(null, ListWrapper.concat([SimpleDirective, NeedsService], extraDirectives)); })
|
||||
.toThrowError(containsRegexp(
|
||||
`No provider for service! (${stringify(NeedsService) } -> service)`));
|
||||
});
|
||||
|
||||
it("should instantiate directives that depend on providers of other directives", () => {
|
||||
it('should instantiate directives that depend on providers of other directives', () => {
|
||||
mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({
|
||||
providers: [provide('service', {useValue: 'hostService'})]})
|
||||
);
|
||||
@@ -544,7 +544,7 @@ export function main() {
|
||||
expect(shadowInj.get(NeedsService).service).toEqual('hostService');
|
||||
});
|
||||
|
||||
it("should instantiate directives that depend on view providers of a component", () => {
|
||||
it('should instantiate directives that depend on view providers of a component', () => {
|
||||
mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({
|
||||
viewProviders: [provide('service', {useValue: 'hostService'})]})
|
||||
);
|
||||
@@ -555,7 +555,7 @@ export function main() {
|
||||
expect(shadowInj.get(NeedsService).service).toEqual('hostService');
|
||||
});
|
||||
|
||||
it("should instantiate directives in a root embedded view that depend on view providers of a component", () => {
|
||||
it('should instantiate directives in a root embedded view that depend on view providers of a component', () => {
|
||||
mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata({
|
||||
viewProviders: [provide('service', {useValue: 'hostService'})]})
|
||||
);
|
||||
@@ -570,9 +570,9 @@ export function main() {
|
||||
expect(rootEmbeddedEl.get(NeedsService).service).toEqual('hostService');
|
||||
});
|
||||
|
||||
it("should instantiate directives that depend on imperatively created injector (bootstrap)", () => {
|
||||
it('should instantiate directives that depend on imperatively created injector (bootstrap)', () => {
|
||||
var rootInjector = Injector.resolveAndCreate([
|
||||
provide("service", {useValue: 'appService'})
|
||||
provide('service', {useValue: 'appService'})
|
||||
]);
|
||||
var view = createView(ViewType.HOST, null, null, rootInjector);
|
||||
expect(appElement(null, [NeedsService], view).get(NeedsService).service).toEqual('appService');
|
||||
@@ -580,9 +580,9 @@ export function main() {
|
||||
expect(() => appElement(null, [NeedsServiceFromHost], view)).toThrowError();
|
||||
});
|
||||
|
||||
it("should instantiate directives that depend on imperatively created providers (root injector)", () => {
|
||||
it('should instantiate directives that depend on imperatively created providers (root injector)', () => {
|
||||
var imperativelyCreatedProviders = Injector.resolve([
|
||||
provide("service", {useValue: 'appService'})
|
||||
provide('service', {useValue: 'appService'})
|
||||
]);
|
||||
var containerAppElement = appElement(null, []);
|
||||
var view = createView(ViewType.HOST, containerAppElement, imperativelyCreatedProviders, null);
|
||||
@@ -590,8 +590,8 @@ export function main() {
|
||||
expect(appElement(null, [NeedsServiceFromHost], view).get(NeedsServiceFromHost).service).toEqual('appService');
|
||||
});
|
||||
|
||||
it("should not instantiate a directive in a view that has a host dependency on providers"+
|
||||
" of the component", () => {
|
||||
it('should not instantiate a directive in a view that has a host dependency on providers'+
|
||||
' of the component', () => {
|
||||
mockDirectiveMeta.set(SomeOtherDirective, new DirectiveMetadata({
|
||||
providers: [provide('service', {useValue: 'hostService'})]})
|
||||
);
|
||||
@@ -600,11 +600,11 @@ export function main() {
|
||||
ListWrapper.concat([SomeOtherDirective], extraDirectives),
|
||||
ListWrapper.concat([NeedsServiceFromHost], extraDirectives)
|
||||
);
|
||||
}).toThrowError(new RegExp("No provider for service!"));
|
||||
}).toThrowError(new RegExp('No provider for service!'));
|
||||
});
|
||||
|
||||
it("should not instantiate a directive in a view that has a host dependency on providers"+
|
||||
" of a decorator directive", () => {
|
||||
it('should not instantiate a directive in a view that has a host dependency on providers'+
|
||||
' of a decorator directive', () => {
|
||||
mockDirectiveMeta.set(SomeOtherDirective, new DirectiveMetadata({
|
||||
providers: [provide('service', {useValue: 'hostService'})]}));
|
||||
expect(() => {
|
||||
@@ -612,10 +612,10 @@ export function main() {
|
||||
ListWrapper.concat([SimpleDirective, SomeOtherDirective], extraDirectives),
|
||||
ListWrapper.concat([NeedsServiceFromHost], extraDirectives)
|
||||
);
|
||||
}).toThrowError(new RegExp("No provider for service!"));
|
||||
}).toThrowError(new RegExp('No provider for service!'));
|
||||
});
|
||||
|
||||
it("should get directives", () => {
|
||||
it('should get directives', () => {
|
||||
var child = hostShadowElement(
|
||||
ListWrapper.concat([SomeOtherDirective, SimpleDirective], extraDirectives),
|
||||
[NeedsDirectiveFromHostShadowDom]);
|
||||
@@ -626,7 +626,7 @@ export function main() {
|
||||
expect(d.dependency).toBeAnInstanceOf(SimpleDirective);
|
||||
});
|
||||
|
||||
it("should get directives from the host", () => {
|
||||
it('should get directives from the host', () => {
|
||||
var child = parentChildElements(ListWrapper.concat([SimpleDirective], extraDirectives),
|
||||
[NeeedsDirectiveFromHost]);
|
||||
|
||||
@@ -636,19 +636,19 @@ export function main() {
|
||||
expect(d.dependency).toBeAnInstanceOf(SimpleDirective);
|
||||
});
|
||||
|
||||
it("should throw when a dependency cannot be resolved", () => {
|
||||
it('should throw when a dependency cannot be resolved', () => {
|
||||
expect(() => appElement(null, ListWrapper.concat([NeeedsDirectiveFromHost], extraDirectives)))
|
||||
.toThrowError(containsRegexp(
|
||||
`No provider for ${stringify(SimpleDirective) }! (${stringify(NeeedsDirectiveFromHost) } -> ${stringify(SimpleDirective) })`));
|
||||
});
|
||||
|
||||
it("should inject null when an optional dependency cannot be resolved", () => {
|
||||
it('should inject null when an optional dependency cannot be resolved', () => {
|
||||
var el = appElement(null, ListWrapper.concat([OptionallyNeedsDirective], extraDirectives));
|
||||
var d = el.get(OptionallyNeedsDirective);
|
||||
expect(d.dependency).toEqual(null);
|
||||
});
|
||||
|
||||
it("should allow for direct access using getDirectiveAtIndex", () => {
|
||||
it('should allow for direct access using getDirectiveAtIndex', () => {
|
||||
var providers =
|
||||
ListWrapper.concat([SimpleDirective], extraDirectives);
|
||||
|
||||
@@ -662,7 +662,7 @@ export function main() {
|
||||
.toThrowError(`Index ${firsIndexOut} is out-of-bounds.`);
|
||||
});
|
||||
|
||||
it("should instantiate directives that depend on the containing component", () => {
|
||||
it('should instantiate directives that depend on the containing component', () => {
|
||||
mockDirectiveMeta.set(SimpleDirective, new ComponentMetadata());
|
||||
var shadow = hostShadowElement(ListWrapper.concat([SimpleDirective], extraDirectives),
|
||||
[NeeedsDirectiveFromHost]);
|
||||
@@ -672,7 +672,7 @@ export function main() {
|
||||
expect(d.dependency).toBeAnInstanceOf(SimpleDirective);
|
||||
});
|
||||
|
||||
it("should not instantiate directives that depend on other directives in the containing component's ElementInjector",
|
||||
it('should not instantiate directives that depend on other directives in the containing component\'s ElementInjector',
|
||||
() => {
|
||||
mockDirectiveMeta.set(SomeOtherDirective, new ComponentMetadata());
|
||||
expect(() =>
|
||||
@@ -708,13 +708,13 @@ export function main() {
|
||||
});
|
||||
});
|
||||
|
||||
describe("refs", () => {
|
||||
it("should inject ElementRef", () => {
|
||||
describe('refs', () => {
|
||||
it('should inject ElementRef', () => {
|
||||
var el = appElement(null, ListWrapper.concat([NeedsElementRef], extraDirectives));
|
||||
expect(el.get(NeedsElementRef).elementRef).toBe(el.ref);
|
||||
});
|
||||
|
||||
it("should inject ChangeDetectorRef of the component's view into the component via a proxy", () => {
|
||||
it('should inject ChangeDetectorRef of the component\'s view into the component via a proxy', () => {
|
||||
mockDirectiveMeta.set(ComponentNeedsChangeDetectorRef, new ComponentMetadata());
|
||||
var host = appElement(null, ListWrapper.concat([ComponentNeedsChangeDetectorRef], extraDirectives));
|
||||
var view = createView(ViewType.COMPONENT, host);
|
||||
@@ -723,7 +723,7 @@ export function main() {
|
||||
expect((<any>view.changeDetector).spy('markPathToRootAsCheckOnce')).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should inject ChangeDetectorRef of the containing component into directives", () => {
|
||||
it('should inject ChangeDetectorRef of the containing component into directives', () => {
|
||||
mockDirectiveMeta.set(DirectiveNeedsChangeDetectorRef, new DirectiveMetadata());
|
||||
var view = createView(ViewType.HOST);
|
||||
var el = appElement(null, ListWrapper.concat([DirectiveNeedsChangeDetectorRef], extraDirectives), view);
|
||||
@@ -735,12 +735,12 @@ export function main() {
|
||||
expect(el.get(NeedsViewContainer).viewContainer).toBeAnInstanceOf(ViewContainerRef_);
|
||||
});
|
||||
|
||||
it("should inject TemplateRef", () => {
|
||||
it('should inject TemplateRef', () => {
|
||||
var el = appElement(null, ListWrapper.concat([NeedsTemplateRef], extraDirectives), null, dummyViewFactory);
|
||||
expect(el.get(NeedsTemplateRef).templateRef.elementRef).toBe(el.ref);
|
||||
});
|
||||
|
||||
it("should throw if there is no TemplateRef", () => {
|
||||
it('should throw if there is no TemplateRef', () => {
|
||||
expect(() => appElement(null, ListWrapper.concat([NeedsTemplateRef], extraDirectives)))
|
||||
.toThrowError(
|
||||
`No provider for TemplateRef! (${stringify(NeedsTemplateRef) } -> TemplateRef)`);
|
||||
@@ -795,7 +795,7 @@ export function main() {
|
||||
var dirs:Type[] = [NeedsQueryByVarBindings];
|
||||
|
||||
var dirVariableBindings:{[key:string]:number} = {
|
||||
"one": null // element
|
||||
'one': null // element
|
||||
};
|
||||
|
||||
var el = appElement(null, dirs.concat(extraDirectives), null, null, null, dirVariableBindings);
|
||||
@@ -810,8 +810,8 @@ export function main() {
|
||||
var dirs:Type[] = [NeedsQueryByVarBindings, NeedsDirective, SimpleDirective];
|
||||
|
||||
var dirVariableBindings:{[key:string]:number} = {
|
||||
"one": 2, // 2 is the index of SimpleDirective
|
||||
"two": 1 // 1 is the index of NeedsDirective
|
||||
'one': 2, // 2 is the index of SimpleDirective
|
||||
'two': 1 // 1 is the index of NeedsDirective
|
||||
};
|
||||
|
||||
var el = appElement(null, dirs.concat(extraDirectives), null, null, null, dirVariableBindings);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,42 +1,9 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
xdescribe,
|
||||
describe,
|
||||
el,
|
||||
dispatchEvent,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
beforeEachProviders,
|
||||
it,
|
||||
xit,
|
||||
containsRegexp,
|
||||
stringifyElement,
|
||||
TestComponentBuilder,
|
||||
ComponentFixture,
|
||||
fakeAsync,
|
||||
tick
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, el, dispatchEvent, expect, iit, inject, beforeEachProviders, it, xit, containsRegexp, stringifyElement, TestComponentBuilder, ComponentFixture, fakeAsync, tick} from 'angular2/testing_internal';
|
||||
|
||||
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
|
||||
|
||||
import {
|
||||
bind,
|
||||
provide,
|
||||
forwardRef,
|
||||
Component,
|
||||
Directive,
|
||||
ElementRef,
|
||||
TemplateRef,
|
||||
ViewContainerRef,
|
||||
ViewEncapsulation,
|
||||
ViewMetadata
|
||||
} from 'angular2/core';
|
||||
import {
|
||||
By,
|
||||
} from 'angular2/platform/common_dom';
|
||||
import {bind, provide, forwardRef, Component, Directive, ElementRef, TemplateRef, ViewContainerRef, ViewEncapsulation, ViewMetadata} from 'angular2/core';
|
||||
import {By,} from 'angular2/platform/common_dom';
|
||||
import {getAllDebugNodes} from 'angular2/src/core/debug/debug_node';
|
||||
|
||||
export function main() {
|
||||
@@ -45,8 +12,8 @@ export function main() {
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MainComp, new ViewMetadata({
|
||||
template: '<simple>' +
|
||||
'<div>A</div>' +
|
||||
'</simple>',
|
||||
'<div>A</div>' +
|
||||
'</simple>',
|
||||
directives: [Simple]
|
||||
}))
|
||||
.createAsync(MainComp)
|
||||
@@ -60,8 +27,8 @@ export function main() {
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MainComp, new ViewMetadata({
|
||||
template: '{{\'START(\'}}<simple>' +
|
||||
'{{text}}' +
|
||||
'</simple>{{\')END\'}}',
|
||||
'{{text}}' +
|
||||
'</simple>{{\')END\'}}',
|
||||
directives: [Simple]
|
||||
}))
|
||||
.createAsync(MainComp)
|
||||
@@ -137,8 +104,8 @@ export function main() {
|
||||
|
||||
it('should not show the light dom even if there is no content tag',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MainComp,
|
||||
new ViewMetadata({template: '<empty>A</empty>', directives: [Empty]}))
|
||||
tcb.overrideView(
|
||||
MainComp, new ViewMetadata({template: '<empty>A</empty>', directives: [Empty]}))
|
||||
.createAsync(MainComp)
|
||||
.then((main) => {
|
||||
|
||||
@@ -151,10 +118,10 @@ export function main() {
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MainComp, new ViewMetadata({
|
||||
template: '<multiple-content-tags>' +
|
||||
'<div>B</div>' +
|
||||
'<div>C</div>' +
|
||||
'<div class="left">A</div>' +
|
||||
'</multiple-content-tags>',
|
||||
'<div>B</div>' +
|
||||
'<div>C</div>' +
|
||||
'<div class="left">A</div>' +
|
||||
'</multiple-content-tags>',
|
||||
directives: [MultipleContentTagsComponent]
|
||||
}))
|
||||
.createAsync(MainComp)
|
||||
@@ -169,9 +136,9 @@ export function main() {
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MainComp, new ViewMetadata({
|
||||
template: '<multiple-content-tags>' +
|
||||
'<div>B<div class="left">A</div></div>' +
|
||||
'<div>C</div>' +
|
||||
'</multiple-content-tags>',
|
||||
'<div>B<div class="left">A</div></div>' +
|
||||
'<div>C</div>' +
|
||||
'</multiple-content-tags>',
|
||||
directives: [MultipleContentTagsComponent]
|
||||
}))
|
||||
.createAsync(MainComp)
|
||||
@@ -182,13 +149,13 @@ export function main() {
|
||||
});
|
||||
}));
|
||||
|
||||
it("should redistribute direct child viewcontainers when the light dom changes",
|
||||
it('should redistribute direct child viewcontainers when the light dom changes',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MainComp, new ViewMetadata({
|
||||
template: '<multiple-content-tags>' +
|
||||
'<template manual class="left"><div>A1</div></template>' +
|
||||
'<div>B</div>' +
|
||||
'</multiple-content-tags>',
|
||||
'<template manual class="left"><div>A1</div></template>' +
|
||||
'<div>B</div>' +
|
||||
'</multiple-content-tags>',
|
||||
directives: [MultipleContentTagsComponent, ManualViewportDirective]
|
||||
}))
|
||||
.createAsync(MainComp)
|
||||
@@ -210,13 +177,13 @@ export function main() {
|
||||
});
|
||||
}));
|
||||
|
||||
it("should support nested components",
|
||||
it('should support nested components',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MainComp, new ViewMetadata({
|
||||
template: '<outer-with-indirect-nested>' +
|
||||
'<div>A</div>' +
|
||||
'<div>B</div>' +
|
||||
'</outer-with-indirect-nested>',
|
||||
'<div>A</div>' +
|
||||
'<div>B</div>' +
|
||||
'</outer-with-indirect-nested>',
|
||||
directives: [OuterWithIndirectNestedComponent]
|
||||
}))
|
||||
.createAsync(MainComp)
|
||||
@@ -227,14 +194,14 @@ export function main() {
|
||||
});
|
||||
}));
|
||||
|
||||
it("should support nesting with content being direct child of a nested component",
|
||||
it('should support nesting with content being direct child of a nested component',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MainComp, new ViewMetadata({
|
||||
template: '<outer>' +
|
||||
'<template manual class="left"><div>A</div></template>' +
|
||||
'<div>B</div>' +
|
||||
'<div>C</div>' +
|
||||
'</outer>',
|
||||
'<template manual class="left"><div>A</div></template>' +
|
||||
'<div>B</div>' +
|
||||
'<div>C</div>' +
|
||||
'</outer>',
|
||||
directives: [OuterComponent, ManualViewportDirective],
|
||||
}))
|
||||
.createAsync(MainComp)
|
||||
@@ -256,10 +223,10 @@ export function main() {
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MainComp, new ViewMetadata({
|
||||
template: '<conditional-content>' +
|
||||
'<div class="left">A</div>' +
|
||||
'<div>B</div>' +
|
||||
'<div>C</div>' +
|
||||
'</conditional-content>',
|
||||
'<div class="left">A</div>' +
|
||||
'<div>B</div>' +
|
||||
'<div>C</div>' +
|
||||
'</conditional-content>',
|
||||
directives: [ConditionalContentComponent]
|
||||
}))
|
||||
.createAsync(MainComp)
|
||||
@@ -326,9 +293,9 @@ export function main() {
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MainComp, new ViewMetadata({
|
||||
template: '<empty>' +
|
||||
' <template manual><div>A</div></template>' +
|
||||
'</empty>' +
|
||||
'START(<div project></div>)END',
|
||||
' <template manual><div>A</div></template>' +
|
||||
'</empty>' +
|
||||
'START(<div project></div>)END',
|
||||
directives: [Empty, ProjectDirective, ManualViewportDirective],
|
||||
}))
|
||||
.createAsync(MainComp)
|
||||
@@ -359,7 +326,7 @@ export function main() {
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MainComp, new ViewMetadata({
|
||||
template: '<simple><template manual><div>A</div></template></simple>' +
|
||||
'START(<div project></div>)END',
|
||||
'START(<div project></div>)END',
|
||||
directives: [Simple, ProjectDirective, ManualViewportDirective],
|
||||
}))
|
||||
.createAsync(MainComp)
|
||||
@@ -384,10 +351,10 @@ export function main() {
|
||||
tcb.overrideView(
|
||||
MainComp, new ViewMetadata({
|
||||
template: '<conditional-content>' +
|
||||
'<div class="left">A</div>' +
|
||||
'<div>B</div>' +
|
||||
'</conditional-content>' +
|
||||
'START(<div project></div>)END',
|
||||
'<div class="left">A</div>' +
|
||||
'<div>B</div>' +
|
||||
'</conditional-content>' +
|
||||
'START(<div project></div>)END',
|
||||
directives:
|
||||
[ConditionalContentComponent, ProjectDirective, ManualViewportDirective]
|
||||
}))
|
||||
@@ -419,8 +386,8 @@ export function main() {
|
||||
// the presence of ng-content elements!
|
||||
it('should still allow to implement a recursive trees',
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MainComp,
|
||||
new ViewMetadata({template: '<tree></tree>', directives: [Tree]}))
|
||||
tcb.overrideView(
|
||||
MainComp, new ViewMetadata({template: '<tree></tree>', directives: [Tree]}))
|
||||
.createAsync(MainComp)
|
||||
.then((main) => {
|
||||
|
||||
@@ -441,7 +408,7 @@ export function main() {
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MainComp, new ViewMetadata({
|
||||
template: '<simple-native1><div>A</div></simple-native1>' +
|
||||
'<simple-native2><div>B</div></simple-native2>',
|
||||
'<simple-native2><div>B</div></simple-native2>',
|
||||
directives: [SimpleNative1, SimpleNative2]
|
||||
}))
|
||||
.createAsync(MainComp)
|
||||
@@ -510,8 +477,9 @@ export function main() {
|
||||
.then((main) => {
|
||||
main.detectChanges();
|
||||
expect(DOM.getInnerHTML(main.debugElement.nativeElement))
|
||||
.toEqual('<cmp-a><cmp-b><cmp-d><d>cmp-d</d></cmp-d></cmp-b>' +
|
||||
'<cmp-c><c>cmp-c</c></cmp-c></cmp-a>');
|
||||
.toEqual(
|
||||
'<cmp-a><cmp-b><cmp-d><d>cmp-d</d></cmp-d></cmp-b>' +
|
||||
'<cmp-c><c>cmp-c</c></cmp-c></cmp-a>');
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
@@ -526,8 +494,9 @@ export function main() {
|
||||
.then((main) => {
|
||||
main.detectChanges();
|
||||
expect(DOM.getInnerHTML(main.debugElement.nativeElement))
|
||||
.toEqual('<cmp-a1>a1<cmp-b11>b11</cmp-b11><cmp-b12>b12</cmp-b12></cmp-a1>' +
|
||||
'<cmp-a2>a2<cmp-b21>b21</cmp-b21><cmp-b22>b22</cmp-b22></cmp-a2>');
|
||||
.toEqual(
|
||||
'<cmp-a1>a1<cmp-b11>b11</cmp-b11><cmp-b12>b12</cmp-b12></cmp-a1>' +
|
||||
'<cmp-a2>a2<cmp-b21>b21</cmp-b21><cmp-b22>b22</cmp-b22></cmp-a2>');
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
@@ -536,11 +505,11 @@ export function main() {
|
||||
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
|
||||
tcb.overrideView(MainComp, new ViewMetadata({
|
||||
template: '<conditional-content>' +
|
||||
'<div class="left">A</div>' +
|
||||
'<template manual class="left">B</template>' +
|
||||
'<div class="left">C</div>' +
|
||||
'<div>D</div>' +
|
||||
'</conditional-content>',
|
||||
'<div class="left">A</div>' +
|
||||
'<template manual class="left">B</template>' +
|
||||
'<div class="left">C</div>' +
|
||||
'<div>D</div>' +
|
||||
'</conditional-content>',
|
||||
directives: [ConditionalContentComponent, ManualViewportDirective]
|
||||
}))
|
||||
.createAsync(MainComp)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,15 +1,4 @@
|
||||
import {
|
||||
describe,
|
||||
it,
|
||||
expect,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
iit,
|
||||
xit,
|
||||
el,
|
||||
fakeAsync,
|
||||
tick
|
||||
} from 'angular2/testing_internal';
|
||||
import {describe, it, expect, beforeEach, ddescribe, iit, xit, el, fakeAsync, tick} from 'angular2/testing_internal';
|
||||
import {MapWrapper, ListWrapper, iterateListLike} from 'angular2/src/facade/collection';
|
||||
import {IS_DART, StringWrapper} from 'angular2/src/facade/lang';
|
||||
import {ObservableWrapper} from 'angular2/src/facade/async';
|
||||
@@ -60,22 +49,22 @@ export function main() {
|
||||
if (!IS_DART) {
|
||||
it('should support filter', () => {
|
||||
queryList.reset(['one', 'two']);
|
||||
expect((<_JsQueryList>queryList).filter((x) => x == "one")).toEqual(['one']);
|
||||
expect((<_JsQueryList>queryList).filter((x) => x == 'one')).toEqual(['one']);
|
||||
});
|
||||
|
||||
it('should support reduce', () => {
|
||||
queryList.reset(["one", "two"]);
|
||||
expect((<_JsQueryList>queryList).reduce((a, x) => a + x, "start:")).toEqual("start:onetwo");
|
||||
queryList.reset(['one', 'two']);
|
||||
expect((<_JsQueryList>queryList).reduce((a, x) => a + x, 'start:')).toEqual('start:onetwo');
|
||||
});
|
||||
|
||||
it('should support toArray', () => {
|
||||
queryList.reset(["one", "two"]);
|
||||
expect((<_JsQueryList>queryList).reduce((a, x) => a + x, "start:")).toEqual("start:onetwo");
|
||||
queryList.reset(['one', 'two']);
|
||||
expect((<_JsQueryList>queryList).reduce((a, x) => a + x, 'start:')).toEqual('start:onetwo');
|
||||
});
|
||||
|
||||
it('should support toArray', () => {
|
||||
queryList.reset(["one", "two"]);
|
||||
expect((<_JsQueryList>queryList).toArray()).toEqual(["one", "two"]);
|
||||
queryList.reset(['one', 'two']);
|
||||
expect((<_JsQueryList>queryList).toArray()).toEqual(['one', 'two']);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -113,7 +102,7 @@ export function main() {
|
||||
var recorded;
|
||||
ObservableWrapper.subscribe(queryList.changes, (v: any) => { recorded = v; });
|
||||
|
||||
queryList.reset(["one"]);
|
||||
queryList.reset(['one']);
|
||||
queryList.notifyOnChanges();
|
||||
tick();
|
||||
|
||||
|
||||
@@ -7,29 +7,29 @@ class SomePipe {}
|
||||
|
||||
@Component({
|
||||
selector: 'sample',
|
||||
template: "some template",
|
||||
template: 'some template',
|
||||
directives: [SomeDir],
|
||||
pipes: [SomePipe],
|
||||
styles: ["some styles"]
|
||||
styles: ['some styles']
|
||||
})
|
||||
class ComponentWithView {
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'sample',
|
||||
template: "some template",
|
||||
template: 'some template',
|
||||
directives: [SomeDir],
|
||||
pipes: [SomePipe],
|
||||
styles: ["some styles"]
|
||||
styles: ['some styles']
|
||||
})
|
||||
class ComponentWithTemplate {
|
||||
}
|
||||
|
||||
@Component({selector: 'sample', template: "some template"})
|
||||
@Component({selector: 'sample', template: 'some template'})
|
||||
class ComponentWithViewTemplate {
|
||||
}
|
||||
|
||||
@Component({selector: 'sample', templateUrl: "some template url", template: "some template"})
|
||||
@Component({selector: 'sample', templateUrl: 'some template url', template: 'some template'})
|
||||
class ComponentWithViewTemplateUrl {
|
||||
}
|
||||
|
||||
@@ -41,31 +41,30 @@ class ComponentWithoutView {
|
||||
class SimpleClass {}
|
||||
|
||||
export function main() {
|
||||
describe("ViewResolver", () => {
|
||||
describe('ViewResolver', () => {
|
||||
var resolver: ViewResolver;
|
||||
|
||||
beforeEach(() => { resolver = new ViewResolver(); });
|
||||
|
||||
it('should read out the View metadata from the Component metadata', () => {
|
||||
var viewMetadata = resolver.resolve(ComponentWithTemplate);
|
||||
expect(viewMetadata)
|
||||
.toEqual(new ViewMetadata({
|
||||
template: "some template",
|
||||
directives: [SomeDir],
|
||||
pipes: [SomePipe],
|
||||
styles: ["some styles"]
|
||||
}));
|
||||
expect(viewMetadata).toEqual(new ViewMetadata({
|
||||
template: 'some template',
|
||||
directives: [SomeDir],
|
||||
pipes: [SomePipe],
|
||||
styles: ['some styles']
|
||||
}));
|
||||
});
|
||||
|
||||
it('should throw when Component has no View decorator and no template is set', () => {
|
||||
expect(() => resolver.resolve(ComponentWithoutView))
|
||||
.toThrowErrorWith(
|
||||
"Component 'ComponentWithoutView' must have either 'template' or 'templateUrl' set");
|
||||
'Component \'ComponentWithoutView\' must have either \'template\' or \'templateUrl\' set');
|
||||
});
|
||||
|
||||
it('should throw when simple class has no View decorator and no template is set', () => {
|
||||
expect(() => resolver.resolve(SimpleClass))
|
||||
.toThrowErrorWith("Could not compile 'SimpleClass' because it is not a component.");
|
||||
.toThrowErrorWith('Could not compile \'SimpleClass\' because it is not a component.');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,14 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal';
|
||||
|
||||
import {Component, Directive} from 'angular2/core';
|
||||
import {reflector} from 'angular2/src/core/reflection/reflection';
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
makeDecorator,
|
||||
makeParamDecorator,
|
||||
makePropDecorator
|
||||
} from 'angular2/src/core/util/decorators';
|
||||
import {makeDecorator, makeParamDecorator, makePropDecorator} from 'angular2/src/core/util/decorators';
|
||||
|
||||
export class ClassDecoratorMeta {
|
||||
constructor(public value) {}
|
||||
|
||||
@@ -1,24 +1,8 @@
|
||||
import {
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
ddescribe,
|
||||
expect,
|
||||
beforeEach,
|
||||
browserDetection
|
||||
} from 'angular2/testing_internal';
|
||||
import {describe, it, iit, ddescribe, expect, beforeEach, browserDetection} from 'angular2/testing_internal';
|
||||
import {OnInit} from 'angular2/core';
|
||||
import {Reflector, ReflectionInfo} from 'angular2/src/core/reflection/reflection';
|
||||
import {ReflectionCapabilities} from 'angular2/src/core/reflection/reflection_capabilities';
|
||||
import {
|
||||
ClassDecorator,
|
||||
ParamDecorator,
|
||||
PropDecorator,
|
||||
classDecorator,
|
||||
paramDecorator,
|
||||
propDecorator,
|
||||
HasGetterAndSetterDecorators
|
||||
} from './reflector_common';
|
||||
import {ClassDecorator, ParamDecorator, PropDecorator, classDecorator, paramDecorator, propDecorator, HasGetterAndSetterDecorators} from './reflector_common';
|
||||
import {IS_DART} from 'angular2/src/facade/lang';
|
||||
|
||||
class AType {
|
||||
@@ -29,14 +13,13 @@ class AType {
|
||||
|
||||
@ClassDecorator('class')
|
||||
class ClassWithDecorators {
|
||||
@PropDecorator("p1") @PropDecorator("p2") a;
|
||||
@PropDecorator('p1') @PropDecorator('p2') a;
|
||||
b;
|
||||
|
||||
@PropDecorator("p3")
|
||||
set c(value) {
|
||||
}
|
||||
@PropDecorator('p3')
|
||||
set c(value) {}
|
||||
|
||||
constructor(@ParamDecorator("a") a: AType, @ParamDecorator("b") b: AType) {
|
||||
constructor(@ParamDecorator('a') a: AType, @ParamDecorator('b') b: AType) {
|
||||
this.a = a;
|
||||
this.b = b;
|
||||
}
|
||||
@@ -85,19 +68,19 @@ export function main() {
|
||||
|
||||
beforeEach(() => { reflector = new Reflector(new ReflectionCapabilities()); });
|
||||
|
||||
describe("usage tracking", () => {
|
||||
describe('usage tracking', () => {
|
||||
beforeEach(() => { reflector = new Reflector(null); });
|
||||
|
||||
it("should be disabled by default", () => {
|
||||
it('should be disabled by default', () => {
|
||||
expect(() => reflector.listUnusedKeys()).toThrowError('Usage tracking is disabled');
|
||||
});
|
||||
|
||||
it("should report unused keys", () => {
|
||||
it('should report unused keys', () => {
|
||||
reflector.trackUsage();
|
||||
expect(reflector.listUnusedKeys()).toEqual([]);
|
||||
|
||||
reflector.registerType(AType, new ReflectionInfo(null, null, () => "AType"));
|
||||
reflector.registerType(TestObj, new ReflectionInfo(null, null, () => "TestObj"));
|
||||
reflector.registerType(AType, new ReflectionInfo(null, null, () => 'AType'));
|
||||
reflector.registerType(TestObj, new ReflectionInfo(null, null, () => 'TestObj'));
|
||||
expect(reflector.listUnusedKeys()).toEqual([AType, TestObj]);
|
||||
|
||||
reflector.factory(AType);
|
||||
@@ -108,8 +91,8 @@ export function main() {
|
||||
});
|
||||
});
|
||||
|
||||
describe("factory", () => {
|
||||
it("should create a factory for the given type", () => {
|
||||
describe('factory', () => {
|
||||
it('should create a factory for the given type', () => {
|
||||
var obj = reflector.factory(TestObj)(1, 2);
|
||||
|
||||
expect(obj.a).toEqual(1);
|
||||
@@ -119,7 +102,7 @@ export function main() {
|
||||
// Makes Edge to disconnect when running the full unit test campaign
|
||||
// TODO: remove when issue is solved: https://github.com/angular/angular/issues/4756
|
||||
if (!browserDetection.isEdge) {
|
||||
it("should check args from no to max", () => {
|
||||
it('should check args from no to max', () => {
|
||||
var f = t => reflector.factory(t);
|
||||
var checkArgs = (obj, args) => expect(obj.args).toEqual(args);
|
||||
|
||||
@@ -149,141 +132,141 @@ export function main() {
|
||||
});
|
||||
}
|
||||
|
||||
it("should throw when more than 20 arguments",
|
||||
it('should throw when more than 20 arguments',
|
||||
() => { expect(() => reflector.factory(TestObjWith21Args)).toThrowError(); });
|
||||
|
||||
it("should return a registered factory if available", () => {
|
||||
reflector.registerType(TestObj, new ReflectionInfo(null, null, () => "fake"));
|
||||
expect(reflector.factory(TestObj)()).toEqual("fake");
|
||||
it('should return a registered factory if available', () => {
|
||||
reflector.registerType(TestObj, new ReflectionInfo(null, null, () => 'fake'));
|
||||
expect(reflector.factory(TestObj)()).toEqual('fake');
|
||||
});
|
||||
});
|
||||
|
||||
describe("parameters", () => {
|
||||
it("should return an array of parameters for a type", () => {
|
||||
describe('parameters', () => {
|
||||
it('should return an array of parameters for a type', () => {
|
||||
var p = reflector.parameters(ClassWithDecorators);
|
||||
expect(p).toEqual([[AType, paramDecorator('a')], [AType, paramDecorator('b')]]);
|
||||
});
|
||||
|
||||
it("should work for a class without annotations", () => {
|
||||
it('should work for a class without annotations', () => {
|
||||
var p = reflector.parameters(ClassWithoutDecorators);
|
||||
expect(p.length).toEqual(2);
|
||||
});
|
||||
|
||||
it("should return registered parameters if available", () => {
|
||||
it('should return registered parameters if available', () => {
|
||||
reflector.registerType(TestObj, new ReflectionInfo(null, [[1], [2]]));
|
||||
expect(reflector.parameters(TestObj)).toEqual([[1], [2]]);
|
||||
});
|
||||
|
||||
it("should return an empty list when no parameters field in the stored type info", () => {
|
||||
it('should return an empty list when no parameters field in the stored type info', () => {
|
||||
reflector.registerType(TestObj, new ReflectionInfo());
|
||||
expect(reflector.parameters(TestObj)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("propMetadata", () => {
|
||||
it("should return a string map of prop metadata for the given class", () => {
|
||||
describe('propMetadata', () => {
|
||||
it('should return a string map of prop metadata for the given class', () => {
|
||||
var p = reflector.propMetadata(ClassWithDecorators);
|
||||
expect(p["a"]).toEqual([propDecorator("p1"), propDecorator("p2")]);
|
||||
expect(p["c"]).toEqual([propDecorator("p3")]);
|
||||
expect(p['a']).toEqual([propDecorator('p1'), propDecorator('p2')]);
|
||||
expect(p['c']).toEqual([propDecorator('p3')]);
|
||||
});
|
||||
|
||||
it("should return registered meta if available", () => {
|
||||
reflector.registerType(TestObj, new ReflectionInfo(null, null, null, null, {"a": [1, 2]}));
|
||||
expect(reflector.propMetadata(TestObj)).toEqual({"a": [1, 2]});
|
||||
it('should return registered meta if available', () => {
|
||||
reflector.registerType(TestObj, new ReflectionInfo(null, null, null, null, {'a': [1, 2]}));
|
||||
expect(reflector.propMetadata(TestObj)).toEqual({'a': [1, 2]});
|
||||
});
|
||||
|
||||
if (IS_DART) {
|
||||
it("should merge metadata from getters and setters", () => {
|
||||
it('should merge metadata from getters and setters', () => {
|
||||
var p = reflector.propMetadata(HasGetterAndSetterDecorators);
|
||||
expect(p["a"]).toEqual([propDecorator("get"), propDecorator("set")]);
|
||||
expect(p['a']).toEqual([propDecorator('get'), propDecorator('set')]);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe("annotations", () => {
|
||||
it("should return an array of annotations for a type", () => {
|
||||
describe('annotations', () => {
|
||||
it('should return an array of annotations for a type', () => {
|
||||
var p = reflector.annotations(ClassWithDecorators);
|
||||
expect(p).toEqual([classDecorator('class')]);
|
||||
});
|
||||
|
||||
it("should return registered annotations if available", () => {
|
||||
it('should return registered annotations if available', () => {
|
||||
reflector.registerType(TestObj, new ReflectionInfo([1, 2]));
|
||||
expect(reflector.annotations(TestObj)).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it("should work for a class without annotations", () => {
|
||||
it('should work for a class without annotations', () => {
|
||||
var p = reflector.annotations(ClassWithoutDecorators);
|
||||
expect(p).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
if (IS_DART) {
|
||||
describe("interfaces", () => {
|
||||
it("should return an array of interfaces for a type", () => {
|
||||
describe('interfaces', () => {
|
||||
it('should return an array of interfaces for a type', () => {
|
||||
var p = reflector.interfaces(ClassImplementingInterface);
|
||||
expect(p).toEqual([Interface, Interface2]);
|
||||
});
|
||||
|
||||
it("should return an empty array otherwise", () => {
|
||||
it('should return an empty array otherwise', () => {
|
||||
var p = reflector.interfaces(ClassWithDecorators);
|
||||
expect(p).toEqual([]);
|
||||
});
|
||||
|
||||
it("should throw for undeclared lifecycle interfaces",
|
||||
it('should throw for undeclared lifecycle interfaces',
|
||||
() => { expect(() => reflector.interfaces(ClassDoesNotDeclareOnInit)).toThrowError(); });
|
||||
|
||||
it("should throw for class inheriting a lifecycle impl and not declaring the interface",
|
||||
it('should throw for class inheriting a lifecycle impl and not declaring the interface',
|
||||
() => {
|
||||
expect(() => reflector.interfaces(SubClassDoesNotDeclareOnInit)).toThrowError();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
describe("getter", () => {
|
||||
it("returns a function reading a property", () => {
|
||||
describe('getter', () => {
|
||||
it('returns a function reading a property', () => {
|
||||
var getA = reflector.getter('a');
|
||||
expect(getA(new TestObj(1, 2))).toEqual(1);
|
||||
});
|
||||
|
||||
it("should return a registered getter if available", () => {
|
||||
reflector.registerGetters({"abc": (obj) => "fake"});
|
||||
expect(reflector.getter("abc")("anything")).toEqual("fake");
|
||||
it('should return a registered getter if available', () => {
|
||||
reflector.registerGetters({'abc': (obj) => 'fake'});
|
||||
expect(reflector.getter('abc')('anything')).toEqual('fake');
|
||||
});
|
||||
});
|
||||
|
||||
describe("setter", () => {
|
||||
it("returns a function setting a property", () => {
|
||||
describe('setter', () => {
|
||||
it('returns a function setting a property', () => {
|
||||
var setA = reflector.setter('a');
|
||||
var obj = new TestObj(1, 2);
|
||||
setA(obj, 100);
|
||||
expect(obj.a).toEqual(100);
|
||||
});
|
||||
|
||||
it("should return a registered setter if available", () => {
|
||||
it('should return a registered setter if available', () => {
|
||||
var updateMe;
|
||||
reflector.registerSetters({"abc": (obj, value) => { updateMe = value; }});
|
||||
reflector.setter("abc")("anything", "fake");
|
||||
reflector.registerSetters({'abc': (obj, value) => { updateMe = value; }});
|
||||
reflector.setter('abc')('anything', 'fake');
|
||||
|
||||
expect(updateMe).toEqual("fake");
|
||||
expect(updateMe).toEqual('fake');
|
||||
});
|
||||
});
|
||||
|
||||
describe("method", () => {
|
||||
it("returns a function invoking a method", () => {
|
||||
describe('method', () => {
|
||||
it('returns a function invoking a method', () => {
|
||||
var func = reflector.method('identity');
|
||||
var obj = new TestObj(1, 2);
|
||||
expect(func(obj, ['value'])).toEqual('value');
|
||||
});
|
||||
|
||||
it("should return a registered method if available", () => {
|
||||
reflector.registerMethods({"abc": (obj, args) => args});
|
||||
expect(reflector.method("abc")("anything", ["fake"])).toEqual(['fake']);
|
||||
it('should return a registered method if available', () => {
|
||||
reflector.registerMethods({'abc': (obj, args) => args});
|
||||
expect(reflector.method('abc')('anything', ['fake'])).toEqual(['fake']);
|
||||
});
|
||||
});
|
||||
|
||||
if (IS_DART) {
|
||||
describe("importUri", () => {
|
||||
it("should return the importUri for a type", () => {
|
||||
describe('importUri', () => {
|
||||
it('should return the importUri for a type', () => {
|
||||
expect(reflector.importUri(TestObjWith00Args)
|
||||
.endsWith('test/core/reflection/reflector_spec.dart'))
|
||||
.toBe(true);
|
||||
@@ -354,82 +337,89 @@ class TestObjWith09Args {
|
||||
|
||||
class TestObjWith10Args {
|
||||
args: any[];
|
||||
constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
|
||||
a10: any) {
|
||||
constructor(
|
||||
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any) {
|
||||
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10];
|
||||
}
|
||||
}
|
||||
|
||||
class TestObjWith11Args {
|
||||
args: any[];
|
||||
constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
|
||||
a10: any, a11: any) {
|
||||
constructor(
|
||||
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
|
||||
a11: any) {
|
||||
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11];
|
||||
}
|
||||
}
|
||||
|
||||
class TestObjWith12Args {
|
||||
args: any[];
|
||||
constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
|
||||
a10: any, a11: any, a12: any) {
|
||||
constructor(
|
||||
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
|
||||
a11: any, a12: any) {
|
||||
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12];
|
||||
}
|
||||
}
|
||||
|
||||
class TestObjWith13Args {
|
||||
args: any[];
|
||||
constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
|
||||
a10: any, a11: any, a12: any, a13: any) {
|
||||
constructor(
|
||||
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
|
||||
a11: any, a12: any, a13: any) {
|
||||
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13];
|
||||
}
|
||||
}
|
||||
|
||||
class TestObjWith14Args {
|
||||
args: any[];
|
||||
constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
|
||||
a10: any, a11: any, a12: any, a13: any, a14: any) {
|
||||
constructor(
|
||||
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
|
||||
a11: any, a12: any, a13: any, a14: any) {
|
||||
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14];
|
||||
}
|
||||
}
|
||||
|
||||
class TestObjWith15Args {
|
||||
args: any[];
|
||||
constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
|
||||
a10: any, a11: any, a12: any, a13: any, a14: any, a15: any) {
|
||||
constructor(
|
||||
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
|
||||
a11: any, a12: any, a13: any, a14: any, a15: any) {
|
||||
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15];
|
||||
}
|
||||
}
|
||||
|
||||
class TestObjWith16Args {
|
||||
args: any[];
|
||||
constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
|
||||
a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any) {
|
||||
constructor(
|
||||
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
|
||||
a11: any, a12: any, a13: any, a14: any, a15: any, a16: any) {
|
||||
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16];
|
||||
}
|
||||
}
|
||||
|
||||
class TestObjWith17Args {
|
||||
args: any[];
|
||||
constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
|
||||
a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any) {
|
||||
constructor(
|
||||
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
|
||||
a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any) {
|
||||
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17];
|
||||
}
|
||||
}
|
||||
|
||||
class TestObjWith18Args {
|
||||
args: any[];
|
||||
constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
|
||||
a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any,
|
||||
a18: any) {
|
||||
constructor(
|
||||
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
|
||||
a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, a18: any) {
|
||||
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18];
|
||||
}
|
||||
}
|
||||
|
||||
class TestObjWith19Args {
|
||||
args: any[];
|
||||
constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
|
||||
a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any,
|
||||
a18: any, a19: any) {
|
||||
constructor(
|
||||
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
|
||||
a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, a18: any, a19: any) {
|
||||
this.args =
|
||||
[a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19];
|
||||
}
|
||||
@@ -437,9 +427,10 @@ class TestObjWith19Args {
|
||||
|
||||
class TestObjWith20Args {
|
||||
args: any[];
|
||||
constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
|
||||
a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any,
|
||||
a18: any, a19: any, a20: any) {
|
||||
constructor(
|
||||
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
|
||||
a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, a18: any, a19: any,
|
||||
a20: any) {
|
||||
this.args =
|
||||
[a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20];
|
||||
}
|
||||
@@ -447,31 +438,13 @@ class TestObjWith20Args {
|
||||
|
||||
class TestObjWith21Args {
|
||||
args: any[];
|
||||
constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
|
||||
a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any,
|
||||
a18: any, a19: any, a20: any, a21: any) {
|
||||
constructor(
|
||||
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
|
||||
a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, a18: any, a19: any,
|
||||
a20: any, a21: any) {
|
||||
this.args = [
|
||||
a1,
|
||||
a2,
|
||||
a3,
|
||||
a4,
|
||||
a5,
|
||||
a6,
|
||||
a7,
|
||||
a8,
|
||||
a9,
|
||||
a10,
|
||||
a11,
|
||||
a12,
|
||||
a13,
|
||||
a14,
|
||||
a15,
|
||||
a16,
|
||||
a17,
|
||||
a18,
|
||||
a19,
|
||||
a20,
|
||||
a21
|
||||
a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11,
|
||||
a12, a13, a14, a15, a16, a17, a18, a19, a20, a21
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
import {
|
||||
ChangeDetector,
|
||||
ChangeDetectorRef,
|
||||
ProtoChangeDetector,
|
||||
DynamicChangeDetector
|
||||
} from 'angular2/src/core/change_detection/change_detection';
|
||||
import {ChangeDetector, ChangeDetectorRef, ProtoChangeDetector, DynamicChangeDetector} from 'angular2/src/core/change_detection/change_detection';
|
||||
|
||||
import {Renderer} from 'angular2/src/core/render/api';
|
||||
import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver';
|
||||
|
||||
@@ -1,17 +1,5 @@
|
||||
import {Injectable} from 'angular2/src/core/di';
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
inject,
|
||||
describe,
|
||||
ddescribe,
|
||||
it,
|
||||
iit,
|
||||
xit,
|
||||
xdescribe,
|
||||
expect,
|
||||
beforeEach,
|
||||
SpyObject
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, inject, describe, ddescribe, it, iit, xit, xdescribe, expect, beforeEach, SpyObject} from 'angular2/testing_internal';
|
||||
import {Testability} from 'angular2/src/core/testability/testability';
|
||||
import {NgZone} from 'angular2/src/core/zone/ng_zone';
|
||||
import {normalizeBlank, scheduleMicroTask} from 'angular2/src/facade/lang';
|
||||
|
||||
@@ -1,14 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from 'angular2/testing_internal';
|
||||
|
||||
import {makeDecorator, makeParamDecorator, Class} from 'angular2/src/core/util/decorators';
|
||||
import {global} from 'angular2/src/facade/lang';
|
||||
@@ -67,19 +57,16 @@ export function main() {
|
||||
describe('Class', () => {
|
||||
it('should create a class', () => {
|
||||
var i0, i1;
|
||||
var MyClass =
|
||||
(<any>TestDecorator('test-works'))
|
||||
.Class(<any>{
|
||||
extends: Class(<any>{
|
||||
constructor: function() {},
|
||||
extendWorks: function() { return 'extend ' + this.arg; }
|
||||
}),
|
||||
constructor: [String, function(arg) { this.arg = arg; }],
|
||||
methodA:
|
||||
[i0 = new Inject(String), [i1 = Inject(String), Number], function(a, b) {}],
|
||||
works: function() { return this.arg; },
|
||||
prototype: 'IGNORE'
|
||||
});
|
||||
var MyClass = (<any>TestDecorator('test-works')).Class(<any>{
|
||||
extends: Class(<any>{
|
||||
constructor: function() {},
|
||||
extendWorks: function() { return 'extend ' + this.arg; }
|
||||
}),
|
||||
constructor: [String, function(arg) { this.arg = arg; }],
|
||||
methodA: [i0 = new Inject(String), [i1 = Inject(String), Number], function(a, b) {}],
|
||||
works: function() { return this.arg; },
|
||||
prototype: 'IGNORE'
|
||||
});
|
||||
var obj: any = new MyClass('WORKS');
|
||||
expect(obj.arg).toEqual('WORKS');
|
||||
expect(obj.works()).toEqual('WORKS');
|
||||
@@ -98,38 +85,39 @@ export function main() {
|
||||
it('should ensure that last constructor is required', () => {
|
||||
expect(() => { (<Function>Class)({}); })
|
||||
.toThrowError(
|
||||
"Only Function or Array is supported in Class definition for key 'constructor' is 'undefined'");
|
||||
'Only Function or Array is supported in Class definition for key \'constructor\' is \'undefined\'');
|
||||
});
|
||||
|
||||
|
||||
it('should ensure that we dont accidently patch native objects', () => {
|
||||
expect(() => { (<Function>Class)({constructor: Object}); })
|
||||
.toThrowError("Can not use native Object as constructor");
|
||||
expect(() => {
|
||||
(<Function>Class)({constructor: Object});
|
||||
}).toThrowError('Can not use native Object as constructor');
|
||||
});
|
||||
|
||||
|
||||
it('should ensure that last position is function', () => {
|
||||
expect(() => {Class({constructor: []})})
|
||||
.toThrowError(
|
||||
"Last position of Class method array must be Function in key constructor was 'undefined'");
|
||||
'Last position of Class method array must be Function in key constructor was \'undefined\'');
|
||||
});
|
||||
|
||||
it('should ensure that annotation count matches parameters count', () => {
|
||||
expect(() => {Class({constructor: [String, function MyType() {}]})})
|
||||
.toThrowError(
|
||||
"Number of annotations (1) does not match number of arguments (0) in the function: MyType");
|
||||
'Number of annotations (1) does not match number of arguments (0) in the function: MyType');
|
||||
});
|
||||
|
||||
it('should ensure that only Function|Arrays are supported', () => {
|
||||
expect(() => { Class(<any>{constructor: function() {}, method: 'non_function'}); })
|
||||
.toThrowError(
|
||||
"Only Function or Array is supported in Class definition for key 'method' is 'non_function'");
|
||||
'Only Function or Array is supported in Class definition for key \'method\' is \'non_function\'');
|
||||
});
|
||||
|
||||
it('should ensure that extends is a Function', () => {
|
||||
expect(() => {(<Function>Class)({extends: 'non_type', constructor: function() {}})})
|
||||
.toThrowError(
|
||||
"Class definition 'extends' property must be a constructor function was: non_type");
|
||||
'Class definition \'extends\' property must be a constructor function was: non_type');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,24 +1,6 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xdescribe,
|
||||
xit,
|
||||
Log,
|
||||
browserDetection
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit, Log, browserDetection} from 'angular2/testing_internal';
|
||||
|
||||
import {
|
||||
PromiseCompleter,
|
||||
PromiseWrapper,
|
||||
TimerWrapper,
|
||||
ObservableWrapper
|
||||
} from 'angular2/src/facade/async';
|
||||
import {PromiseCompleter, PromiseWrapper, TimerWrapper, ObservableWrapper} from 'angular2/src/facade/async';
|
||||
import {BaseException} from 'angular2/src/facade/exceptions';
|
||||
import {IS_DART, scheduleMicroTask, isPresent} from 'angular2/src/facade/lang';
|
||||
|
||||
@@ -68,7 +50,7 @@ function runNgZoneNoLog(fn: () => any) {
|
||||
}
|
||||
|
||||
export function main() {
|
||||
describe("NgZone", () => {
|
||||
describe('NgZone', () => {
|
||||
|
||||
function createZone(enableLongStackTrace) {
|
||||
return new NgZone({enableLongStackTrace: enableLongStackTrace});
|
||||
@@ -121,7 +103,7 @@ export function main() {
|
||||
scheduleMicroTask(() => {
|
||||
scheduleMicroTask(() => {
|
||||
c.resolve(null);
|
||||
throw new BaseException("ddd");
|
||||
throw new BaseException('ddd');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -246,8 +228,9 @@ function commonTests() {
|
||||
|
||||
macroTask(() => {
|
||||
expect(_log.result())
|
||||
.toEqual('onUnstable; run; onMicrotaskEmpty; onMicrotaskEmpty 1; ' +
|
||||
'onMicrotaskEmpty; onMicrotaskEmpty 2; onStable');
|
||||
.toEqual(
|
||||
'onUnstable; run; onMicrotaskEmpty; onMicrotaskEmpty 1; ' +
|
||||
'onMicrotaskEmpty; onMicrotaskEmpty 2; onStable');
|
||||
async.done();
|
||||
}, resultTimer);
|
||||
}), testTimeout);
|
||||
@@ -314,8 +297,9 @@ function commonTests() {
|
||||
|
||||
macroTask(() => {
|
||||
expect(_log.result())
|
||||
.toEqual('onUnstable; run; onMicrotaskEmpty; onMyMicrotaskEmpty; ' +
|
||||
'onMicrotaskEmpty; onMyMicrotaskEmpty; onStable');
|
||||
.toEqual(
|
||||
'onUnstable; run; onMicrotaskEmpty; onMyMicrotaskEmpty; ' +
|
||||
'onMicrotaskEmpty; onMyMicrotaskEmpty; onStable');
|
||||
async.done();
|
||||
}, resultTimer);
|
||||
}), testTimeout);
|
||||
@@ -677,8 +661,9 @@ function commonTests() {
|
||||
|
||||
macroTask(() => {
|
||||
expect(_log.result())
|
||||
.toEqual('onUnstable; zone run; onMicrotaskEmpty; onStable; ' +
|
||||
'onUnstable; promise then; onMicrotaskEmpty; onStable');
|
||||
.toEqual(
|
||||
'onUnstable; zone run; onMicrotaskEmpty; onStable; ' +
|
||||
'onUnstable; promise then; onMicrotaskEmpty; onStable');
|
||||
async.done();
|
||||
}, resultTimer);
|
||||
}), testTimeout);
|
||||
|
||||
@@ -1,15 +1,4 @@
|
||||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xdescribe,
|
||||
xit
|
||||
} from 'angular2/testing_internal';
|
||||
import {AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from 'angular2/testing_internal';
|
||||
|
||||
import {assertionsEnabled, IS_DART} from 'angular2/src/facade/lang';
|
||||
|
||||
@@ -24,7 +13,7 @@ export function main() {
|
||||
try {
|
||||
var s: string = <any>42;
|
||||
expect(s).toEqual(42); // without it, dart analyzer will complain that `s` is not used.
|
||||
throw "should not be reached";
|
||||
throw 'should not be reached';
|
||||
} catch (e) {
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,25 +1,6 @@
|
||||
import {
|
||||
describe,
|
||||
it,
|
||||
expect,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
iit,
|
||||
xit,
|
||||
el,
|
||||
SpyObject,
|
||||
AsyncTestCompleter,
|
||||
inject,
|
||||
browserDetection
|
||||
} from 'angular2/testing_internal';
|
||||
import {describe, it, expect, beforeEach, ddescribe, iit, xit, el, SpyObject, AsyncTestCompleter, inject, browserDetection} from 'angular2/testing_internal';
|
||||
|
||||
import {
|
||||
ObservableWrapper,
|
||||
Observable,
|
||||
Subject,
|
||||
EventEmitter,
|
||||
PromiseWrapper
|
||||
} from 'angular2/src/facade/async';
|
||||
import {ObservableWrapper, Observable, Subject, EventEmitter, PromiseWrapper} from 'angular2/src/facade/async';
|
||||
|
||||
export function main() {
|
||||
describe('EventEmitter', () => {
|
||||
@@ -27,7 +8,7 @@ export function main() {
|
||||
|
||||
beforeEach(() => { emitter = new EventEmitter(); });
|
||||
|
||||
it("should call the next callback", inject([AsyncTestCompleter], (async) => {
|
||||
it('should call the next callback', inject([AsyncTestCompleter], (async) => {
|
||||
ObservableWrapper.subscribe(emitter, (value) => {
|
||||
expect(value).toEqual(99);
|
||||
async.done();
|
||||
@@ -36,26 +17,26 @@ export function main() {
|
||||
ObservableWrapper.callEmit(emitter, 99);
|
||||
}));
|
||||
|
||||
it("should call the throw callback", inject([AsyncTestCompleter], (async) => {
|
||||
it('should call the throw callback', inject([AsyncTestCompleter], (async) => {
|
||||
ObservableWrapper.subscribe(emitter, (_) => {}, (error) => {
|
||||
expect(error).toEqual("Boom");
|
||||
expect(error).toEqual('Boom');
|
||||
async.done();
|
||||
});
|
||||
ObservableWrapper.callError(emitter, "Boom");
|
||||
ObservableWrapper.callError(emitter, 'Boom');
|
||||
}));
|
||||
|
||||
it("should work when no throw callback is provided", inject([AsyncTestCompleter], (async) => {
|
||||
it('should work when no throw callback is provided', inject([AsyncTestCompleter], (async) => {
|
||||
ObservableWrapper.subscribe(emitter, (_) => {}, (_) => { async.done(); });
|
||||
ObservableWrapper.callError(emitter, "Boom");
|
||||
ObservableWrapper.callError(emitter, 'Boom');
|
||||
}));
|
||||
|
||||
it("should call the return callback", inject([AsyncTestCompleter], (async) => {
|
||||
it('should call the return callback', inject([AsyncTestCompleter], (async) => {
|
||||
ObservableWrapper.subscribe(emitter, (_) => {}, (_) => {}, () => { async.done(); });
|
||||
|
||||
ObservableWrapper.callComplete(emitter);
|
||||
}));
|
||||
|
||||
it("should subscribe to the wrapper asynchronously", () => {
|
||||
it('should subscribe to the wrapper asynchronously', () => {
|
||||
var called = false;
|
||||
ObservableWrapper.subscribe(emitter, (value) => { called = true; });
|
||||
|
||||
@@ -66,18 +47,19 @@ export function main() {
|
||||
// Makes Edge to disconnect when running the full unit test campaign
|
||||
// TODO: remove when issue is solved: https://github.com/angular/angular/issues/4756
|
||||
if (!browserDetection.isEdge) {
|
||||
it("delivers next and error events asynchronously", inject([AsyncTestCompleter], (async) => {
|
||||
it('delivers next and error events asynchronously', inject([AsyncTestCompleter], (async) => {
|
||||
let log = [];
|
||||
ObservableWrapper.subscribe(emitter,
|
||||
(x) => {
|
||||
log.push(x);
|
||||
expect(log).toEqual([1, 3, 5, 2]);
|
||||
},
|
||||
(err) => {
|
||||
log.push(err);
|
||||
expect(log).toEqual([1, 3, 5, 2, 4]);
|
||||
async.done();
|
||||
});
|
||||
ObservableWrapper.subscribe(
|
||||
emitter,
|
||||
(x) => {
|
||||
log.push(x);
|
||||
expect(log).toEqual([1, 3, 5, 2]);
|
||||
},
|
||||
(err) => {
|
||||
log.push(err);
|
||||
expect(log).toEqual([1, 3, 5, 2, 4]);
|
||||
async.done();
|
||||
});
|
||||
log.push(1);
|
||||
ObservableWrapper.callEmit(emitter, 2);
|
||||
log.push(3);
|
||||
@@ -85,19 +67,21 @@ export function main() {
|
||||
log.push(5);
|
||||
}));
|
||||
|
||||
it("delivers next and complete events asynchronously",
|
||||
it('delivers next and complete events asynchronously',
|
||||
inject([AsyncTestCompleter], (async) => {
|
||||
let log = [];
|
||||
ObservableWrapper.subscribe(emitter,
|
||||
(x) => {
|
||||
log.push(x);
|
||||
expect(log).toEqual([1, 3, 5, 2]);
|
||||
},
|
||||
null, () => {
|
||||
log.push(4);
|
||||
expect(log).toEqual([1, 3, 5, 2, 4]);
|
||||
async.done();
|
||||
});
|
||||
ObservableWrapper.subscribe(
|
||||
emitter,
|
||||
(x) => {
|
||||
log.push(x);
|
||||
expect(log).toEqual([1, 3, 5, 2]);
|
||||
},
|
||||
null,
|
||||
() => {
|
||||
log.push(4);
|
||||
expect(log).toEqual([1, 3, 5, 2, 4]);
|
||||
async.done();
|
||||
});
|
||||
log.push(1);
|
||||
ObservableWrapper.callEmit(emitter, 2);
|
||||
log.push(3);
|
||||
@@ -129,7 +113,7 @@ export function main() {
|
||||
// should call dispose on the subscription on return
|
||||
});
|
||||
|
||||
describe("ObservableWrapper", () => {
|
||||
describe('ObservableWrapper', () => {
|
||||
|
||||
it('should correctly check isObservable for EventEmitter', () => {
|
||||
var e = new EventEmitter(false);
|
||||
@@ -153,9 +137,9 @@ export function main() {
|
||||
});
|
||||
|
||||
// See ECMAScript 6 Spec 25.4.4.1
|
||||
describe("PromiseWrapper", () => {
|
||||
describe("#all", () => {
|
||||
it("should combine lists of Promises", inject([AsyncTestCompleter], (async) => {
|
||||
describe('PromiseWrapper', () => {
|
||||
describe('#all', () => {
|
||||
it('should combine lists of Promises', inject([AsyncTestCompleter], (async) => {
|
||||
var one = PromiseWrapper.completer();
|
||||
var two = PromiseWrapper.completer();
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user