style(lint): re-format modules/@angular

This commit is contained in:
Alex Eagle
2016-06-08 16:38:52 -07:00
parent bbed364e7b
commit f39c9c9e75
589 changed files with 21829 additions and 24259 deletions

View File

@ -1,34 +1,15 @@
import {
AsyncTestCompleter,
beforeEach,
ddescribe,
xdescribe,
describe,
expect,
iit,
inject,
it,
xit,
beforeEachProviders
} from '@angular/core/testing/testing_internal';
import {trigger, style, animate, group, sequence, transition, AnimationMetadata} from '@angular/core';
import {AnimationMetadata, animate, group, sequence, style, transition, trigger} from '@angular/core';
import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {AnimationCompiler, CompiledAnimation} from '../../src/animation/animation_compiler';
import {
CompileTemplateMetadata,
CompileDirectiveMetadata,
CompileTypeMetadata
} from '../../src/compile_metadata';
import {CompileDirectiveMetadata, CompileTemplateMetadata, CompileTypeMetadata} from '../../src/compile_metadata';
import {CompileMetadataResolver} from '../../src/metadata_resolver';
export function main() {
describe('RuntimeAnimationCompiler', () => {
var resolver: any /** TODO #9100 */;
beforeEach(inject([CompileMetadataResolver], (res: CompileMetadataResolver) => {
resolver = res;
}));
beforeEach(
inject([CompileMetadataResolver], (res: CompileMetadataResolver) => { resolver = res; }));
var compiler = new AnimationCompiler();
@ -37,18 +18,12 @@ export function main() {
};
var compile = (seq: AnimationMetadata) => {
var entry = trigger('myAnimation', [
transition('state1 => state2', seq)
]);
var entry = trigger('myAnimation', [transition('state1 => state2', seq)]);
var compiledAnimationEntry = resolver.getAnimationEntryMetadata(entry);
var component = CompileDirectiveMetadata.create({
type: new CompileTypeMetadata({
name: 'something'
}),
template: new CompileTemplateMetadata({
animations: [compiledAnimationEntry]
})
type: new CompileTypeMetadata({name: 'something'}),
template: new CompileTemplateMetadata({animations: [compiledAnimationEntry]})
});
return compileAnimations(component);
@ -56,12 +31,9 @@ export function main() {
it('should throw an exception containing all the inner animation parser errors', () => {
var animation = sequence([
style({"color": "red"}),
animate(1000, style({"font-size": "100px"})),
style({"color": "blue"}),
animate(1000, style(":missing_state")),
style({"color": "gold"}),
animate(1000, style("broken_state"))
style({'color': 'red'}), animate(1000, style({'font-size': '100px'})),
style({'color': 'blue'}), animate(1000, style(':missing_state')), style({'color': 'gold'}),
animate(1000, style('broken_state'))
]);
var capturedErrorMessage: string;
@ -72,8 +44,7 @@ export function main() {
}
expect(capturedErrorMessage)
.toMatchPattern(
/Unable to apply styles due to missing a state: "missing_state"/g);
.toMatchPattern(/Unable to apply styles due to missing a state: "missing_state"/g);
expect(capturedErrorMessage)
.toMatchPattern(/Animation states via styles must be prefixed with a ":"/);

View File

@ -1,64 +1,26 @@
import {
AsyncTestCompleter,
beforeEach,
ddescribe,
xdescribe,
describe,
expect,
iit,
inject,
it,
xit,
beforeEachProviders
} from '@angular/core/testing/testing_internal';
import {parseAnimationEntry} from '../../src/animation/animation_parser';
import {CompileMetadataResolver} from '../../src/metadata_resolver';
import {
style,
animate,
group,
sequence,
trigger,
keyframes,
transition,
state,
AnimationMetadata,
AnimationWithStepsMetadata,
AnimationStyleMetadata,
AnimationAnimateMetadata,
AnimationGroupMetadata,
AnimationSequenceMetadata
} from '@angular/core';
import {
AnimationAst,
AnimationStateTransitionAst,
AnimationEntryAst,
AnimationKeyframeAst,
AnimationStylesAst,
AnimationSequenceAst,
AnimationGroupAst,
AnimationStepAst
} from '../../src/animation/animation_ast';
import {AnimationAnimateMetadata, AnimationGroupMetadata, AnimationMetadata, AnimationSequenceMetadata, AnimationStyleMetadata, AnimationWithStepsMetadata, animate, group, keyframes, sequence, state, style, transition, trigger} from '@angular/core';
import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {FILL_STYLE_FLAG, flattenStyles} from '../../core_private';
import {AnimationAst, AnimationEntryAst, AnimationGroupAst, AnimationKeyframeAst, AnimationSequenceAst, AnimationStateTransitionAst, AnimationStepAst, AnimationStylesAst} from '../../src/animation/animation_ast';
import {parseAnimationEntry} from '../../src/animation/animation_parser';
import {StringMapWrapper} from '../../src/facade/collection';
import {CompileMetadataResolver} from '../../src/metadata_resolver';
export function main() {
describe('parseAnimationEntry', () => {
var combineStyles = (styles: AnimationStylesAst): {[key: string]: string | number} => {
var flatStyles: {[key: string]: string | number} = {};
styles.styles.forEach(entry => StringMapWrapper.forEach(entry, (val: any /** TODO #9100 */, prop: any /** TODO #9100 */) => { flatStyles[prop] = val; }));
styles.styles.forEach(
entry => StringMapWrapper.forEach(
entry, (val: any /** TODO #9100 */, prop: any /** TODO #9100 */) => {
flatStyles[prop] = val;
}));
return flatStyles;
};
var collectKeyframeStyles = (keyframe: AnimationKeyframeAst): {[key: string]: string | number} => {
return combineStyles(keyframe.styles);
};
var collectKeyframeStyles = (keyframe: AnimationKeyframeAst):
{[key: string]: string | number} => { return combineStyles(keyframe.styles); };
var collectStepStyles = (step: AnimationStepAst): Array<{[key: string]: string | number}> => {
var keyframes = step.keyframes;
@ -71,21 +33,17 @@ export function main() {
};
var resolver: any /** TODO #9100 */;
beforeEach(inject([CompileMetadataResolver], (res: CompileMetadataResolver) => {
resolver = res;
}));
beforeEach(
inject([CompileMetadataResolver], (res: CompileMetadataResolver) => { resolver = res; }));
var parseAnimation = (data: AnimationMetadata[]) => {
var entry = trigger('myAnimation', [
transition('state1 => state2', sequence(data))
]);
var entry = trigger('myAnimation', [transition('state1 => state2', sequence(data))]);
var compiledAnimationEntry = resolver.getAnimationEntryMetadata(entry);
return parseAnimationEntry(compiledAnimationEntry);
};
var getAnimationAstFromEntryAst = (ast: AnimationEntryAst) => {
return ast.stateTransitions[0].animation;
}
var getAnimationAstFromEntryAst =
(ast: AnimationEntryAst) => { return ast.stateTransitions[0].animation; }
var parseAnimationAst = (data: AnimationMetadata[]) => {
return getAnimationAstFromEntryAst(parseAnimation(data).ast);
@ -95,29 +53,27 @@ export function main() {
it('should merge repeated style steps into a single style ast step entry', () => {
var ast = parseAnimationAst([
style({"color": 'black'}),
style({"background": 'red'}),
style({"opacity": 0}),
animate(1000, style({"color": 'white', "background": 'black', "opacity": 1}))
style({'color': 'black'}), style({'background': 'red'}), style({'opacity': 0}),
animate(1000, style({'color': 'white', 'background': 'black', 'opacity': 1}))
]);
expect(ast.steps.length).toEqual(1);
var step = <AnimationStepAst>ast.steps[0];
expect(step.startingStyles.styles[0])
.toEqual({"color": 'black', "background": 'red', "opacity": 0});
.toEqual({'color': 'black', 'background': 'red', 'opacity': 0});
expect(step.keyframes[0].styles.styles[0])
.toEqual({"color": 'black', "background": 'red', "opacity": 0});
.toEqual({'color': 'black', 'background': 'red', 'opacity': 0});
expect(step.keyframes[1].styles.styles[0])
.toEqual({"color": 'white', "background": 'black', "opacity": 1});
.toEqual({'color': 'white', 'background': 'black', 'opacity': 1});
});
it('should animate only the styles requested within an animation step', () => {
var ast = parseAnimationAst([
style({"color": 'black', "background": 'blue'}),
animate(1000, style({"background": 'orange'}))
style({'color': 'black', 'background': 'blue'}),
animate(1000, style({'background': 'orange'}))
]);
expect(ast.steps.length).toEqual(1);
@ -125,18 +81,19 @@ export function main() {
var animateStep = <AnimationStepAst>ast.steps[0];
var fromKeyframe = animateStep.keyframes[0].styles.styles[0];
var toKeyframe = animateStep.keyframes[1].styles.styles[0];
expect(fromKeyframe).toEqual({"background": 'blue'});
expect(toKeyframe).toEqual({"background": 'orange'});
expect(fromKeyframe).toEqual({'background': 'blue'});
expect(toKeyframe).toEqual({'background': 'orange'});
});
it('should populate the starting and duration times propertly', () => {
var ast = parseAnimationAst([
style({"color": 'black', "opacity": 1}),
animate(1000, style({"color": 'red'})),
animate(4000, style({"color": 'yellow'})),
sequence([animate(1000, style({"color": 'blue'})), animate(1000, style({"color": 'grey'}))]),
group([animate(500, style({"color": 'pink'})), animate(1000, style({"opacity": '0.5'}))]),
animate(300, style({"color": 'black'})),
style({'color': 'black', 'opacity': 1}),
animate(1000, style({'color': 'red'})),
animate(4000, style({'color': 'yellow'})),
sequence(
[animate(1000, style({'color': 'blue'})), animate(1000, style({'color': 'grey'}))]),
group([animate(500, style({'color': 'pink'})), animate(1000, style({'opacity': '0.5'}))]),
animate(300, style({'color': 'black'})),
]);
expect(ast.steps.length).toEqual(5);
@ -181,13 +138,15 @@ export function main() {
it('should apply the correct animate() styles when parallel animations are active and use the same properties',
() => {
var details = parseAnimation([
style({"opacity": 0, "color": 'red'}),
group([
style({'opacity': 0, 'color': 'red'}), group([
sequence([
animate(2000, style({"color": "black"})),
animate(2000, style({"opacity": 0.5})),
animate(2000, style({'color': 'black'})),
animate(2000, style({'opacity': 0.5})),
]),
sequence([animate(2000, style({"opacity": 0.8})), animate(2000, style({"color": "blue"}))])
sequence([
animate(2000, style({'opacity': 0.8})),
animate(2000, style({'color': 'blue'}))
])
])
]);
@ -201,22 +160,22 @@ export function main() {
var sq2 = <AnimationSequenceAst>g1.steps[1];
var sq1a1 = <AnimationStepAst>sq1.steps[0];
expect(collectStepStyles(sq1a1)).toEqual([{"color": 'red'}, {"color": 'black'}]);
expect(collectStepStyles(sq1a1)).toEqual([{'color': 'red'}, {'color': 'black'}]);
var sq1a2 = <AnimationStepAst>sq1.steps[1];
expect(collectStepStyles(sq1a2)).toEqual([{"opacity": 0.8}, {"opacity": 0.5}]);
expect(collectStepStyles(sq1a2)).toEqual([{'opacity': 0.8}, {'opacity': 0.5}]);
var sq2a1 = <AnimationStepAst>sq2.steps[0];
expect(collectStepStyles(sq2a1)).toEqual([{"opacity": 0}, {"opacity": 0.8}]);
expect(collectStepStyles(sq2a1)).toEqual([{'opacity': 0}, {'opacity': 0.8}]);
var sq2a2 = <AnimationStepAst>sq2.steps[1];
expect(collectStepStyles(sq2a2)).toEqual([{"color": "black"}, {"color": "blue"}]);
expect(collectStepStyles(sq2a2)).toEqual([{'color': 'black'}, {'color': 'blue'}]);
});
it('should throw errors when animations animate a CSS property at the same time', () => {
var animation1 = parseAnimation([
style({"opacity": 0}),
group([animate(1000, style({"opacity": 1})), animate(2000, style({"opacity": 0.5}))])
style({'opacity': 0}),
group([animate(1000, style({'opacity': 1})), animate(2000, style({'opacity': 0.5}))])
]);
var errors1 = animation1.errors;
@ -226,11 +185,9 @@ export function main() {
'The animated CSS property "opacity" unexpectedly changes between steps "0ms" and "2000ms" at "1000ms"');
var animation2 = parseAnimation([
style({"color": "red"}),
group([
animate(5000, style({"color": "blue"})),
animate(2500, style({"color": "black"}))
])
style({'color': 'red'}),
group(
[animate(5000, style({'color': 'blue'})), animate(2500, style({'color': 'black'}))])
]);
var errors2 = animation2.errors;
@ -242,30 +199,23 @@ export function main() {
it('should return an error when an animation style contains an invalid timing value', () => {
var errors = parseAnimationAndGetErrors(
[style({"opacity": 0}), animate('one second', style({"opacity": 1}))]);
[style({'opacity': 0}), animate('one second', style({'opacity': 1}))]);
expect(errors[0].msg).toContainError(`The provided timing value "one second" is invalid.`);
});
it('should collect and return any errors collected when parsing the metadata', () => {
var errors = parseAnimationAndGetErrors([
style({"opacity": 0}),
animate('one second', style({"opacity": 1})),
style({"opacity": 0}),
animate('one second', null),
style({"background": 'red'})
style({'opacity': 0}), animate('one second', style({'opacity': 1})), style({'opacity': 0}),
animate('one second', null), style({'background': 'red'})
]);
expect(errors.length).toBeGreaterThan(1);
});
it('should normalize a series of keyframe styles into a list of offset steps', () => {
var ast = parseAnimationAst([
animate(1000, keyframes([
style({"width": 0}),
style({"width": 25}),
style({"width": 50}),
style({"width": 75})
]))
]);
var ast = parseAnimationAst([animate(1000, keyframes([
style({'width': 0}), style({'width': 25}),
style({'width': 50}), style({'width': 75})
]))]);
var step = <AnimationStepAst>ast.steps[0];
expect(step.keyframes.length).toEqual(4);
@ -277,14 +227,11 @@ export function main() {
});
it('should use an existing collection of offset steps if provided', () => {
var ast = parseAnimationAst([
animate(1000, keyframes([
style({"height": 0, "offset": 0}),
style({"height": 25, "offset": 0.6}),
style({"height": 50, "offset": 0.7}),
style({"height": 75, "offset": 1})
]))
]);
var ast = parseAnimationAst(
[animate(1000, keyframes([
style({'height': 0, 'offset': 0}), style({'height': 25, 'offset': 0.6}),
style({'height': 50, 'offset': 0.7}), style({'height': 75, 'offset': 1})
]))]);
var step = <AnimationStepAst>ast.steps[0];
expect(step.keyframes.length).toEqual(4);
@ -296,14 +243,11 @@ export function main() {
});
it('should sort the provided collection of steps that contain offsets', () => {
var ast = parseAnimationAst([
animate(1000, keyframes([
style({"opacity": 0, "offset": 0.9}),
style({"opacity": .25, "offset": 0}),
style({"opacity": .50, "offset": 1}),
style({"opacity": .75, "offset": 0.91})
]))
]);
var ast = parseAnimationAst([animate(
1000, keyframes([
style({'opacity': 0, 'offset': 0.9}), style({'opacity': .25, 'offset': 0}),
style({'opacity': .50, 'offset': 1}), style({'opacity': .75, 'offset': 0.91})
]))]);
var step = <AnimationStepAst>ast.steps[0];
expect(step.keyframes.length).toEqual(4);
@ -322,13 +266,11 @@ export function main() {
});
it('should throw an error if a partial amount of keyframes contain an offset', () => {
var errors = parseAnimationAndGetErrors([
animate(1000, keyframes([
style({"z-index": 0, "offset": 0}),
style({"z-index": 1}),
style({"z-index": 2, "offset": 1})
]))
]);
var errors = parseAnimationAndGetErrors(
[animate(1000, keyframes([
style({'z-index': 0, 'offset': 0}), style({'z-index': 1}),
style({'z-index': 2, 'offset': 1})
]))]);
expect(errors.length).toEqual(1);
var error = errors[0];
@ -336,106 +278,107 @@ export function main() {
expect(error.msg).toMatchPattern(/Not all style\(\) entries contain an offset/);
});
it('should use an existing style used earlier in the animation sequence if not defined in the first keyframe', () => {
var ast = parseAnimationAst([
animate(1000, keyframes([
style({"color": "red"}),
style({"background": "blue", "color": "white"})
]))
]);
it('should use an existing style used earlier in the animation sequence if not defined in the first keyframe',
() => {
var ast = parseAnimationAst([animate(
1000,
keyframes(
[style({'color': 'red'}), style({'background': 'blue', 'color': 'white'})]))]);
var keyframesStep = <AnimationStepAst>ast.steps[0];
var kf1 = keyframesStep.keyframes[0];
var kf2 = keyframesStep.keyframes[1];
var keyframesStep = <AnimationStepAst>ast.steps[0];
var kf1 = keyframesStep.keyframes[0];
var kf2 = keyframesStep.keyframes[1];
expect(flattenStyles(kf1.styles.styles)).toEqual({
"color": "red",
"background": FILL_STYLE_FLAG
});
});
expect(flattenStyles(kf1.styles.styles))
.toEqual({'color': 'red', 'background': FILL_STYLE_FLAG});
});
it('should copy over any missing styles to the final keyframe if not already defined', () => {
var ast = parseAnimationAst([
animate(1000, keyframes([
style({"color": "white", "border-color":"white"}),
style({"color": "red", "background": "blue"}),
style({"background": "blue" })
]))
]);
var ast = parseAnimationAst([animate(
1000, keyframes([
style({'color': 'white', 'border-color': 'white'}),
style({'color': 'red', 'background': 'blue'}), style({'background': 'blue'})
]))]);
var keyframesStep = <AnimationStepAst>ast.steps[0];
var kf1 = keyframesStep.keyframes[0];
var kf2 = keyframesStep.keyframes[1];
var kf3 = keyframesStep.keyframes[2];
expect(flattenStyles(kf3.styles.styles)).toEqual({
"background": "blue",
"color": "red",
"border-color": "white"
});
expect(flattenStyles(kf3.styles.styles))
.toEqual({'background': 'blue', 'color': 'red', 'border-color': 'white'});
});
it('should create an initial keyframe if not detected and place all keyframes styles there', () => {
var ast = parseAnimationAst([
animate(1000, keyframes([
style({"color": "white", "background": "black", "offset": 0.5}),
style({"color": "orange", "background": "red", "font-size": "100px", "offset": 1})
]))
]);
it('should create an initial keyframe if not detected and place all keyframes styles there',
() => {
var ast = parseAnimationAst(
[animate(1000, keyframes([
style({'color': 'white', 'background': 'black', 'offset': 0.5}), style({
'color': 'orange',
'background': 'red',
'font-size': '100px',
'offset': 1
})
]))]);
var keyframesStep = <AnimationStepAst>ast.steps[0];
expect(keyframesStep.keyframes.length).toEqual(3);
var kf1 = keyframesStep.keyframes[0];
var kf2 = keyframesStep.keyframes[1];
var kf3 = keyframesStep.keyframes[2];
var keyframesStep = <AnimationStepAst>ast.steps[0];
expect(keyframesStep.keyframes.length).toEqual(3);
var kf1 = keyframesStep.keyframes[0];
var kf2 = keyframesStep.keyframes[1];
var kf3 = keyframesStep.keyframes[2];
expect(kf1.offset).toEqual(0);
expect(flattenStyles(kf1.styles.styles)).toEqual({
"font-size": FILL_STYLE_FLAG,
"background": FILL_STYLE_FLAG,
"color": FILL_STYLE_FLAG
});
});
expect(kf1.offset).toEqual(0);
expect(flattenStyles(kf1.styles.styles)).toEqual({
'font-size': FILL_STYLE_FLAG,
'background': FILL_STYLE_FLAG,
'color': FILL_STYLE_FLAG
});
});
it('should create an destination keyframe if not detected and place all keyframes styles there', () => {
var ast = parseAnimationAst([
animate(1000, keyframes([
style({"color": "white", "background": "black", "transform": "rotate(360deg)", "offset": 0}),
style({"color": "orange", "background": "red", "font-size": "100px", "offset": 0.5})
]))
]);
it('should create an destination keyframe if not detected and place all keyframes styles there',
() => {
var ast = parseAnimationAst([animate(1000, keyframes([
style({
'color': 'white',
'background': 'black',
'transform': 'rotate(360deg)',
'offset': 0
}),
style({
'color': 'orange',
'background': 'red',
'font-size': '100px',
'offset': 0.5
})
]))]);
var keyframesStep = <AnimationStepAst>ast.steps[0];
expect(keyframesStep.keyframes.length).toEqual(3);
var kf1 = keyframesStep.keyframes[0];
var kf2 = keyframesStep.keyframes[1];
var kf3 = keyframesStep.keyframes[2];
var keyframesStep = <AnimationStepAst>ast.steps[0];
expect(keyframesStep.keyframes.length).toEqual(3);
var kf1 = keyframesStep.keyframes[0];
var kf2 = keyframesStep.keyframes[1];
var kf3 = keyframesStep.keyframes[2];
expect(kf3.offset).toEqual(1);
expect(flattenStyles(kf3.styles.styles)).toEqual({
"color": "orange",
"background": "red",
"transform": "rotate(360deg)",
"font-size": "100px"
});
});
expect(kf3.offset).toEqual(1);
expect(flattenStyles(kf3.styles.styles)).toEqual({
'color': 'orange',
'background': 'red',
'transform': 'rotate(360deg)',
'font-size': '100px'
});
});
describe('easing / duration / delay', () => {
it('should parse simple string-based values', () => {
var ast = parseAnimationAst([
animate("1s .5s ease-out", style({ "opacity": 1 }))
]);
var ast = parseAnimationAst([animate('1s .5s ease-out', style({'opacity': 1}))]);
var step = <AnimationStepAst>ast.steps[0];
expect(step.duration).toEqual(1000);
expect(step.delay).toEqual(500);
expect(step.easing).toEqual("ease-out");
expect(step.easing).toEqual('ease-out');
});
it('should parse a numeric duration value', () => {
var ast = parseAnimationAst([
animate(666, style({ "opacity": 1 }))
]);
var ast = parseAnimationAst([animate(666, style({'opacity': 1}))]);
var step = <AnimationStepAst>ast.steps[0];
expect(step.duration).toEqual(666);
@ -444,25 +387,22 @@ export function main() {
});
it('should parse an easing value without a delay', () => {
var ast = parseAnimationAst([
animate("5s linear", style({ "opacity": 1 }))
]);
var ast = parseAnimationAst([animate('5s linear', style({'opacity': 1}))]);
var step = <AnimationStepAst>ast.steps[0];
expect(step.duration).toEqual(5000);
expect(step.delay).toEqual(0);
expect(step.easing).toEqual("linear");
expect(step.easing).toEqual('linear');
});
it('should parse a complex easing value', () => {
var ast = parseAnimationAst([
animate("30ms cubic-bezier(0, 0,0, .69)", style({ "opacity": 1 }))
]);
var ast =
parseAnimationAst([animate('30ms cubic-bezier(0, 0,0, .69)', style({'opacity': 1}))]);
var step = <AnimationStepAst>ast.steps[0];
expect(step.duration).toEqual(30);
expect(step.delay).toEqual(0);
expect(step.easing).toEqual("cubic-bezier(0, 0,0, .69)");
expect(step.easing).toEqual('cubic-bezier(0, 0,0, .69)');
});
});
});

View File

@ -1,38 +1,12 @@
import {
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {
CompileDirectiveMetadata,
CompileTypeMetadata,
CompileTemplateMetadata,
CompileProviderMetadata,
CompileDiDependencyMetadata,
CompileQueryMetadata,
CompileIdentifierMetadata,
CompileFactoryMetadata,
CompileTokenMetadata,
CompileAnimationEntryMetadata,
CompileAnimationStyleMetadata,
CompileAnimationAnimateMetadata,
CompileAnimationSequenceMetadata,
CompileAnimationStateTransitionMetadata,
CompileAnimationKeyframesSequenceMetadata,
CompileAnimationGroupMetadata
} from '@angular/compiler/src/compile_metadata';
import {CompileDirectiveMetadata, CompileTypeMetadata, CompileTemplateMetadata, CompileProviderMetadata, CompileDiDependencyMetadata, CompileQueryMetadata, CompileIdentifierMetadata, CompileFactoryMetadata, CompileTokenMetadata, CompileAnimationEntryMetadata, CompileAnimationStyleMetadata, CompileAnimationAnimateMetadata, CompileAnimationSequenceMetadata, CompileAnimationStateTransitionMetadata, CompileAnimationKeyframesSequenceMetadata, CompileAnimationGroupMetadata} from '@angular/compiler/src/compile_metadata';
import {ViewEncapsulation} from '@angular/core/src/metadata/view';
import {ChangeDetectionStrategy} from '@angular/core/src/change_detection';
import {LifecycleHooks} from '@angular/core/src/metadata/lifecycle_hooks';
export function main() {
describe('CompileMetadata', () => {
describe('CompileMetadata', () => {
var fullTypeMeta: CompileTypeMetadata;
var fullTemplateMeta: CompileTemplateMetadata;
var fullDirectiveMeta: CompileDirectiveMetadata;
@ -67,17 +41,14 @@ export function main() {
templateUrl: 'someTemplateUrl',
styles: ['someStyle'],
styleUrls: ['someStyleUrl'],
animations: [
new CompileAnimationEntryMetadata('animation', [
new CompileAnimationStateTransitionMetadata('* => *',
new CompileAnimationSequenceMetadata([
new CompileAnimationStyleMetadata(0, [{ 'opacity': 0 }]),
new CompileAnimationAnimateMetadata(1000,
new CompileAnimationStyleMetadata(0, [{ 'opacity': 1 }]))
])
)
])
],
animations: [new CompileAnimationEntryMetadata(
'animation',
[new CompileAnimationStateTransitionMetadata(
'* => *', new CompileAnimationSequenceMetadata([
new CompileAnimationStyleMetadata(0, [{'opacity': 0}]),
new CompileAnimationAnimateMetadata(
1000, new CompileAnimationStyleMetadata(0, [{'opacity': 1}]))
]))])],
ngContentSelectors: ['*']
});
fullDirectiveMeta = CompileDirectiveMetadata.create({
@ -90,47 +61,39 @@ export function main() {
outputs: ['someEvent'],
host: {'(event1)': 'handler1', '[prop1]': 'expr1', 'attr1': 'attrValue2'},
lifecycleHooks: [LifecycleHooks.OnChanges],
providers: [
new CompileProviderMetadata({
token: new CompileTokenMetadata({value: 'token'}),
multi: true,
useClass: fullTypeMeta,
useExisting: new CompileTokenMetadata({
identifier: new CompileIdentifierMetadata({name: 'someName'}),
identifierIsInstance: true
}),
useFactory: new CompileFactoryMetadata({name: 'someName', diDeps: [diDep]}),
useValue: 'someValue',
})
],
viewProviders: [
new CompileProviderMetadata({
token: new CompileTokenMetadata({value: 'token'}),
useClass: fullTypeMeta,
useExisting: new CompileTokenMetadata(
{identifier: new CompileIdentifierMetadata({name: 'someName'})}),
useFactory: new CompileFactoryMetadata({name: 'someName', diDeps: [diDep]}),
useValue: 'someValue'
})
],
queries: [
new CompileQueryMetadata({
selectors: [new CompileTokenMetadata({value: 'selector'})],
descendants: true,
first: false,
propertyName: 'prop',
read: new CompileTokenMetadata({value: 'readToken'})
})
],
viewQueries: [
new CompileQueryMetadata({
selectors: [new CompileTokenMetadata({value: 'selector'})],
descendants: true,
first: false,
propertyName: 'prop',
read: new CompileTokenMetadata({value: 'readToken'})
})
]
providers: [new CompileProviderMetadata({
token: new CompileTokenMetadata({value: 'token'}),
multi: true,
useClass: fullTypeMeta,
useExisting: new CompileTokenMetadata({
identifier: new CompileIdentifierMetadata({name: 'someName'}),
identifierIsInstance: true
}),
useFactory: new CompileFactoryMetadata({name: 'someName', diDeps: [diDep]}),
useValue: 'someValue',
})],
viewProviders: [new CompileProviderMetadata({
token: new CompileTokenMetadata({value: 'token'}),
useClass: fullTypeMeta,
useExisting: new CompileTokenMetadata(
{identifier: new CompileIdentifierMetadata({name: 'someName'})}),
useFactory: new CompileFactoryMetadata({name: 'someName', diDeps: [diDep]}),
useValue: 'someValue'
})],
queries: [new CompileQueryMetadata({
selectors: [new CompileTokenMetadata({value: 'selector'})],
descendants: true,
first: false,
propertyName: 'prop',
read: new CompileTokenMetadata({value: 'readToken'})
})],
viewQueries: [new CompileQueryMetadata({
selectors: [new CompileTokenMetadata({value: 'selector'})],
descendants: true,
first: false,
propertyName: 'prop',
read: new CompileTokenMetadata({value: 'readToken'})
})]
});
});
@ -186,7 +149,7 @@ export function main() {
describe('CompileAnimationStyleMetadata', () => {
it('should serialize with full data', () => {
let full = new CompileAnimationStyleMetadata(0, [{ "opacity": 0, "color": "red" }]);
let full = new CompileAnimationStyleMetadata(0, [{'opacity': 0, 'color': 'red'}]);
expect(CompileAnimationStyleMetadata.fromJson(full.toJson())).toEqual(full);
});
@ -198,8 +161,8 @@ export function main() {
describe('CompileAnimationAnimateMetadata', () => {
it('should serialize with full data', () => {
let full = new CompileAnimationAnimateMetadata("1s linear",
new CompileAnimationStyleMetadata(0, [{ "opacity": 0.5, "color": "blue" }]))
let full = new CompileAnimationAnimateMetadata(
'1s linear', new CompileAnimationStyleMetadata(0, [{'opacity': 0.5, 'color': 'blue'}]))
expect(CompileAnimationAnimateMetadata.fromJson(full.toJson())).toEqual(full);
});
@ -212,9 +175,9 @@ export function main() {
describe('CompileAnimationSequenceMetadata', () => {
it('should serialize with full data', () => {
let full = new CompileAnimationSequenceMetadata([
new CompileAnimationStyleMetadata(0, [{ "opacity": 0.5, "width": 100 }]),
new CompileAnimationAnimateMetadata(1000,
new CompileAnimationStyleMetadata(0, [{ "opacity": 1, "width": 0 }]))
new CompileAnimationStyleMetadata(0, [{'opacity': 0.5, 'width': 100}]),
new CompileAnimationAnimateMetadata(
1000, new CompileAnimationStyleMetadata(0, [{'opacity': 1, 'width': 0}]))
]);
expect(CompileAnimationSequenceMetadata.fromJson(full.toJson())).toEqual(full);
});
@ -228,9 +191,10 @@ export function main() {
describe('CompileAnimationGroupMetadata', () => {
it('should serialize with full data', () => {
let full = new CompileAnimationGroupMetadata([
new CompileAnimationStyleMetadata(0, [{ "width": 100, "border": "1px solid red" }]),
new CompileAnimationAnimateMetadata(1000,
new CompileAnimationStyleMetadata(0, [{ "width": 900, "border": "10px solid blue" }]))
new CompileAnimationStyleMetadata(0, [{'width': 100, 'border': '1px solid red'}]),
new CompileAnimationAnimateMetadata(
1000, new CompileAnimationStyleMetadata(
0, [{'width': 900, 'border': '10px solid blue'}]))
]);
expect(CompileAnimationGroupMetadata.fromJson(full.toJson())).toEqual(full);
});
@ -244,9 +208,9 @@ export function main() {
describe('CompileAnimationKeyframesSequenceMetadata', () => {
it('should serialize with full data', () => {
let full = new CompileAnimationKeyframesSequenceMetadata([
new CompileAnimationStyleMetadata(0, [{ "width": 0 }]),
new CompileAnimationStyleMetadata(0.5, [{ "width": 100 }]),
new CompileAnimationStyleMetadata(1, [{ "width": 200 }]),
new CompileAnimationStyleMetadata(0, [{'width': 0}]),
new CompileAnimationStyleMetadata(0.5, [{'width': 100}]),
new CompileAnimationStyleMetadata(1, [{'width': 200}]),
]);
expect(CompileAnimationKeyframesSequenceMetadata.fromJson(full.toJson())).toEqual(full);
});
@ -259,15 +223,13 @@ export function main() {
describe('CompileAnimationEntryMetadata', () => {
it('should serialize with full data', () => {
let full = new CompileAnimationEntryMetadata('name', [
new CompileAnimationStateTransitionMetadata('key => value',
new CompileAnimationSequenceMetadata([
new CompileAnimationStyleMetadata(0, [{ "color": "red" }]),
new CompileAnimationAnimateMetadata(1000,
new CompileAnimationStyleMetadata(0, [{ "color": "blue" }]))
])
)
]);
let full = new CompileAnimationEntryMetadata(
'name', [new CompileAnimationStateTransitionMetadata(
'key => value', new CompileAnimationSequenceMetadata([
new CompileAnimationStyleMetadata(0, [{'color': 'red'}]),
new CompileAnimationAnimateMetadata(
1000, new CompileAnimationStyleMetadata(0, [{'color': 'blue'}]))
]))]);
expect(CompileAnimationEntryMetadata.fromJson(full.toJson())).toEqual(full);
});

View File

@ -1,27 +1,12 @@
import {
ddescribe,
describe,
it,
iit,
xit,
expect,
beforeEach,
afterEach
} from '@angular/core/testing/testing_internal';
import {CssLexer, CssLexerMode, CssScannerError, CssToken, CssTokenType} from '@angular/compiler/src/css/lexer';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {isPresent} from '../../src/facade/lang';
import {
CssToken,
CssScannerError,
CssLexer,
CssLexerMode,
CssTokenType
} from '@angular/compiler/src/css/lexer';
export function main() {
function tokenize(code: any /** TODO #9100 */, trackComments: boolean = false,
mode: CssLexerMode = CssLexerMode.ALL): CssToken[] {
function tokenize(
code: any /** TODO #9100 */, 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: any /** TODO #9100 */;
try {
@ -305,36 +293,38 @@ export function main() {
it('should consider attribute selectors as valid input and throw when an invalid modifier is used',
() => {
function tokenizeAttr(modifier: any /** TODO #9100 */) {
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();
});
});
describe('Media Query Mode', () => {
it('should validate media queries with a reduced subset of valid characters', () => {
function tokenizeQuery(code: any /** TODO #9100 */) { return tokenize(code, false, CssLexerMode.MEDIA_QUERY); }
function tokenizeQuery(code: any /** TODO #9100 */) {
return tokenize(code, false, CssLexerMode.MEDIA_QUERY);
}
// 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 +335,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 +352,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: any /** TODO #9100 */) { 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: any /** TODO #9100 */) {
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();
});
});
});
}

View File

@ -1,38 +1,9 @@
import {
ddescribe,
describe,
it,
iit,
xit,
expect,
beforeEach,
afterEach
} from '@angular/core/testing/testing_internal';
import {CssLexer} from '@angular/compiler/src/css/lexer';
import {BlockType, CssBlockAST, CssBlockDefinitionRuleAST, CssBlockRuleAST, CssDefinitionAST, CssInlineRuleAST, CssKeyframeDefinitionAST, CssKeyframeRuleAST, CssMediaQueryRuleAST, CssParseError, CssParser, CssRuleAST, CssSelectorAST, CssSelectorRuleAST, CssStyleSheetAST, CssStyleValueAST, ParsedCssResult} from '@angular/compiler/src/css/parser';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {BaseException} from '../../src/facade/exceptions';
import {
ParsedCssResult,
CssParser,
BlockType,
CssSelectorRuleAST,
CssKeyframeRuleAST,
CssKeyframeDefinitionAST,
CssBlockDefinitionRuleAST,
CssMediaQueryRuleAST,
CssBlockRuleAST,
CssInlineRuleAST,
CssStyleValueAST,
CssSelectorAST,
CssDefinitionAST,
CssStyleSheetAST,
CssRuleAST,
CssBlockAST,
CssParseError
} from '@angular/compiler/src/css/parser';
import {CssLexer} from '@angular/compiler/src/css/lexer';
export function assertTokens(tokens: any /** TODO #9100 */, valuesArr: any /** TODO #9100 */) {
for (var i = 0; i < tokens.length; i++) {
expect(tokens[i].strValue == valuesArr[i]);
@ -94,17 +65,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 +158,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',
@ -217,11 +188,13 @@ export function main() {
expect(defs.length).toEqual(4);
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', ')']);
assertTokens((<CssDefinitionAST>defs[3]).value.tokens,
['linear-gradient', '(', '45deg, rgba(100, 0, 0, 0.5), black', ')']);
assertTokens(
(<CssDefinitionAST>defs[3]).value.tokens,
['linear-gradient', '(', '45deg, rgba(100, 0, 0, 0.5), black', ')']);
});
it('should parse un-named block-level CSS values', () => {
@ -268,7 +241,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);
@ -333,7 +306,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', () => {
@ -351,11 +324,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];
@ -411,15 +384,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);
});

View File

@ -1,41 +1,9 @@
import {
ddescribe,
describe,
it,
iit,
xit,
expect,
beforeEach,
afterEach
} from '@angular/core/testing/testing_internal';
import {NumberWrapper, StringWrapper, isPresent} from '../../src/facade/lang';
import {BaseException} from '../../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 '@angular/compiler/src/css/parser';
import {CssLexer} from '@angular/compiler/src/css/lexer';
import {BlockType, CssAST, CssASTVisitor, CssBlockAST, CssBlockDefinitionRuleAST, CssBlockRuleAST, CssDefinitionAST, CssInlineRuleAST, CssKeyframeDefinitionAST, CssKeyframeRuleAST, CssMediaQueryRuleAST, CssParseError, CssParser, CssRuleAST, CssSelectorAST, CssSelectorRuleAST, CssStyleSheetAST, CssStyleValueAST, CssToken, CssUnknownTokenListAST} from '@angular/compiler/src/css/parser';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {BaseException} from '../../src/facade/exceptions';
import {NumberWrapper, StringWrapper, isPresent} from '../../src/facade/lang';
function _assertTokens(tokens: any /** TODO #9100 */, valuesArr: any /** TODO #9100 */) {
for (var i = 0; i < tokens.length; i++) {
@ -46,56 +14,59 @@ function _assertTokens(tokens: any /** TODO #9100 */, valuesArr: any /** TODO #9
class MyVisitor implements CssASTVisitor {
captures: {[key: string]: any[]} = {};
_capture(method: any /** TODO #9100 */, ast: any /** TODO #9100 */, context: any /** TODO #9100 */) {
_capture(
method: any /** TODO #9100 */, ast: any /** TODO #9100 */, context: any /** TODO #9100 */) {
this.captures[method] = isPresent(this.captures[method]) ? this.captures[method] : [];
this.captures[method].push([ast, context]);
}
constructor(ast: CssStyleSheetAST, context?: any) { ast.visit(this, context); }
visitCssValue(ast: any /** TODO #9100 */, context?: any): void { this._capture("visitCssValue", ast, context); }
visitCssValue(ast: any /** TODO #9100 */, context?: any): void {
this._capture('visitCssValue', ast, context);
}
visitInlineCssRule(ast: any /** TODO #9100 */, 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 +179,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);
});

View File

@ -1,13 +1,4 @@
import {
beforeEach,
xdescribe,
ddescribe,
describe,
expect,
iit,
inject,
it,
} from '@angular/core/testing/testing_internal';
import {beforeEach, xdescribe, ddescribe, describe, expect, iit, inject, it,} from '@angular/core/testing/testing_internal';
import {hasLifecycleHook} from '@angular/compiler/src/directive_lifecycle_reflector';
import {LifecycleHooks} from '@angular/core/src/metadata/lifecycle_hooks';
@ -16,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);
});
});

View File

@ -1,22 +1,12 @@
import {
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit,
beforeEachProviders
} from '@angular/core/testing/testing_internal';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {CompileTypeMetadata, CompileTemplateMetadata} from '@angular/compiler/src/compile_metadata';
import {ViewEncapsulation} from '@angular/core/src/metadata/view';
import {CompilerConfig} from "@angular/compiler/src/config";
import {CompileTemplateMetadata, CompileTypeMetadata} from '@angular/compiler/src/compile_metadata';
import {CompilerConfig} from '@angular/compiler/src/config';
import {DirectiveNormalizer} from '@angular/compiler/src/directive_normalizer';
import {XHR} from '@angular/compiler/src/xhr';
import {MockXHR} from '@angular/compiler/testing';
import {ViewEncapsulation} from '@angular/core/src/metadata/view';
import {beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {TEST_PROVIDERS} from './test_bindings';
export function main() {
@ -35,154 +25,171 @@ export function main() {
describe('loadTemplate', () => {
describe('inline template', () => {
it('should store the template',
inject([AsyncTestCompleter, DirectiveNormalizer],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer) => {
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, DirectiveNormalizer],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer) => {
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, DirectiveNormalizer],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer) => {
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, DirectiveNormalizer],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer) => {
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, DirectiveNormalizer],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer) => {
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, DirectiveNormalizer],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer) => {
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();
});
}));
it('should use ViewEncapsulation.Emulated by default',
inject([AsyncTestCompleter, DirectiveNormalizer],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer) => {
normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: '',
templateUrl: null,
styles: [],
styleUrls: ['test.css']
}))
.then((template: CompileTemplateMetadata) => {
expect(template.encapsulation).toEqual(ViewEncapsulation.Emulated);
async.done();
});
}));
inject(
[AsyncTestCompleter, DirectiveNormalizer],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer) => {
normalizer
.normalizeTemplate(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: '',
templateUrl: null,
styles: [],
styleUrls: ['test.css']
}))
.then((template: CompileTemplateMetadata) => {
expect(template.encapsulation).toEqual(ViewEncapsulation.Emulated);
async.done();
});
}));
it('should use default encapsulation provided by CompilerConfig',
inject([AsyncTestCompleter, CompilerConfig , DirectiveNormalizer],
(async: AsyncTestCompleter, config: CompilerConfig, normalizer: DirectiveNormalizer) => {
config.defaultEncapsulation = ViewEncapsulation.None;
normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: '',
templateUrl: null,
styles: [],
styleUrls: ['test.css']
}))
.then((template: CompileTemplateMetadata) => {
expect(template.encapsulation).toEqual(ViewEncapsulation.None);
async.done();
});
}));
inject(
[AsyncTestCompleter, CompilerConfig, DirectiveNormalizer],
(async: AsyncTestCompleter, config: CompilerConfig,
normalizer: DirectiveNormalizer) => {
config.defaultEncapsulation = ViewEncapsulation.None;
normalizer
.normalizeTemplate(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: '',
templateUrl: null,
styles: [],
styleUrls: ['test.css']
}))
.then((template: CompileTemplateMetadata) => {
expect(template.encapsulation).toEqual(ViewEncapsulation.None);
async.done();
});
}));
});
describe('templateUrl', () => {
it('should load a template from a url that is resolved against moduleUrl',
inject([AsyncTestCompleter, DirectiveNormalizer, XHR],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer, 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, DirectiveNormalizer, XHR],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer, 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, DirectiveNormalizer, XHR],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer, 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, DirectiveNormalizer, XHR],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer, 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, DirectiveNormalizer, XHR],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer, 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, DirectiveNormalizer, XHR],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer, 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([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
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');
}));

View File

@ -1,21 +1,6 @@
import {ddescribe, describe, it, iit, expect, beforeEach} from '@angular/core/testing';
import {DirectiveResolver} from '@angular/compiler/src/directive_resolver';
import {
DirectiveMetadata,
Directive,
Input,
Output,
HostBinding,
HostListener,
ContentChildren,
ContentChildrenMetadata,
ViewChildren,
ViewChildrenMetadata,
ContentChild,
ContentChildMetadata,
ViewChild,
ViewChildMetadata
} from '@angular/core/src/metadata';
import {ContentChild, ContentChildMetadata, ContentChildren, ContentChildrenMetadata, Directive, DirectiveMetadata, HostBinding, HostListener, Input, Output, ViewChild, ViewChildMetadata, ViewChildren, ViewChildrenMetadata} from '@angular/core/src/metadata';
import {beforeEach, ddescribe, describe, expect, iit, it} from '@angular/core/testing';
@Directive({selector: 'someDirective'})
class SomeDirective {
@ -28,14 +13,14 @@ class SomeChildDirective extends SomeDirective {
@Directive({selector: 'someDirective', inputs: ['c']})
class SomeDirectiveWithInputs {
@Input() a: any /** TODO #9100 */;
@Input("renamed") b: any /** TODO #9100 */;
@Input('renamed') b: any /** TODO #9100 */;
c: any /** TODO #9100 */;
}
@Directive({selector: 'someDirective', outputs: ['c']})
class SomeDirectiveWithOutputs {
@Output() a: any /** TODO #9100 */;
@Output("renamed") b: any /** TODO #9100 */;
@Output('renamed') b: any /** TODO #9100 */;
c: any /** TODO #9100 */;
}
@ -55,64 +40,59 @@ class SomeDirectiveWithEvents {
@Directive({selector: 'someDirective'})
class SomeDirectiveWithSetterProps {
@Input("renamed")
set a(value: any /** TODO #9100 */) {
}
@Input('renamed')
set a(value: any /** TODO #9100 */) {}
}
@Directive({selector: 'someDirective'})
class SomeDirectiveWithGetterOutputs {
@Output("renamed")
get a(): any /** TODO #9100 */ {
return null;
}
@Output('renamed')
get a(): any /** TODO #9100 */ { return null; }
}
@Directive({selector: 'someDirective', host: {'[c]': 'c'}})
class SomeDirectiveWithHostBindings {
@HostBinding() a: any /** TODO #9100 */;
@HostBinding("renamed") b: any /** TODO #9100 */;
@HostBinding('renamed') b: any /** TODO #9100 */;
c: any /** TODO #9100 */;
}
@Directive({selector: 'someDirective', host: {'(c)': 'onC()'}})
class SomeDirectiveWithHostListeners {
@HostListener('a')
onA() {
}
onA() {}
@HostListener('b', ['$event.value'])
onB(value: any /** TODO #9100 */) {
}
onB(value: any /** TODO #9100 */) {}
}
@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: any /** TODO #9100 */;
}
@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: any /** TODO #9100 */;
}
@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: any /** TODO #9100 */;
}
@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: any /** TODO #9100 */;
}
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')});
});
});
});

View File

@ -1,6 +1,5 @@
import {ddescribe, describe, it, expect} from '@angular/core/testing';
import {Lexer, Token} from '@angular/compiler/src/expression_parser/lexer';
import {ddescribe, describe, expect, it} from '@angular/core/testing';
import {StringWrapper} from '../../src/facade/lang';
@ -13,36 +12,42 @@ function expectToken(token: any /** TODO #9100 */, index: any /** TODO #9100 */)
expect(token.index).toEqual(index);
}
function expectCharacterToken(token: any /** TODO #9100 */, index: any /** TODO #9100 */, character: any /** TODO #9100 */) {
function expectCharacterToken(
token: any /** TODO #9100 */, index: any /** TODO #9100 */, character: any /** TODO #9100 */) {
expect(character.length).toBe(1);
expectToken(token, index);
expect(token.isCharacter(StringWrapper.charCodeAt(character, 0))).toBe(true);
}
function expectOperatorToken(token: any /** TODO #9100 */, index: any /** TODO #9100 */, operator: any /** TODO #9100 */) {
function expectOperatorToken(
token: any /** TODO #9100 */, index: any /** TODO #9100 */, operator: any /** TODO #9100 */) {
expectToken(token, index);
expect(token.isOperator(operator)).toBe(true);
}
function expectNumberToken(token: any /** TODO #9100 */, index: any /** TODO #9100 */, n: any /** TODO #9100 */) {
function expectNumberToken(
token: any /** TODO #9100 */, index: any /** TODO #9100 */, n: any /** TODO #9100 */) {
expectToken(token, index);
expect(token.isNumber()).toBe(true);
expect(token.toNumber()).toEqual(n);
}
function expectStringToken(token: any /** TODO #9100 */, index: any /** TODO #9100 */, str: any /** TODO #9100 */) {
function expectStringToken(
token: any /** TODO #9100 */, index: any /** TODO #9100 */, str: any /** TODO #9100 */) {
expectToken(token, index);
expect(token.isString()).toBe(true);
expect(token.toString()).toEqual(str);
}
function expectIdentifierToken(token: any /** TODO #9100 */, index: any /** TODO #9100 */, identifier: any /** TODO #9100 */) {
function expectIdentifierToken(
token: any /** TODO #9100 */, index: any /** TODO #9100 */, identifier: any /** TODO #9100 */) {
expectToken(token, index);
expect(token.isIdentifier()).toBe(true);
expect(token.toString()).toEqual(identifier);
}
function expectKeywordToken(token: any /** TODO #9100 */, index: any /** TODO #9100 */, keyword: any /** TODO #9100 */) {
function expectKeywordToken(
token: any /** TODO #9100 */, index: any /** TODO #9100 */, keyword: any /** TODO #9100 */) {
expectToken(token, index);
expect(token.isKeyword()).toBe(true);
expect(token.toString()).toEqual(keyword);
@ -52,13 +57,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 +71,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 +113,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 +151,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 +164,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 +172,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 +202,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 +213,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, '#');
});

View File

@ -1,9 +1,11 @@
import {ddescribe, describe, it, xit, iit, expect, beforeEach} from '@angular/core/testing';
import {isBlank, isPresent} from '../../src/facade/lang';
import {Parser} from '@angular/compiler/src/expression_parser/parser';
import {Unparser} from './unparser';
import {AST, BindingPipe, LiteralPrimitive} from '@angular/compiler/src/expression_parser/ast';
import {Lexer} from '@angular/compiler/src/expression_parser/lexer';
import {BindingPipe, LiteralPrimitive, AST} from '@angular/compiler/src/expression_parser/ast';
import {Parser} from '@angular/compiler/src/expression_parser/parser';
import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing';
import {isBlank, isPresent} from '../../src/facade/lang';
import {Unparser} from './unparser';
export function main() {
function createParser() { return new Parser(new Lexer()); }
@ -16,15 +18,18 @@ export function main() {
return createParser().parseBinding(text, location);
}
function parseTemplateBindings(text: any /** TODO #9100 */, location: any /** TODO #9100 */ = null): any {
function parseTemplateBindings(
text: any /** TODO #9100 */, location: any /** TODO #9100 */ = null): any {
return createParser().parseTemplateBindings(text, location).templateBindings;
}
function parseInterpolation(text: any /** TODO #9100 */, location: any /** TODO #9100 */ = null): any {
function parseInterpolation(
text: any /** TODO #9100 */, location: any /** TODO #9100 */ = null): any {
return createParser().parseInterpolation(text, location);
}
function parseSimpleBinding(text: any /** TODO #9100 */, location: any /** TODO #9100 */ = null): any {
function parseSimpleBinding(
text: any /** TODO #9100 */, location: any /** TODO #9100 */ = null): any {
return createParser().parseSimpleBinding(text, location);
}
@ -48,60 +53,64 @@ export function main() {
expect(unparse(ast)).toEqual(expected);
}
function expectActionError(text: any /** TODO #9100 */) { return expect(() => parseAction(text)); }
function expectActionError(text: any /** TODO #9100 */) {
return expect(() => parseAction(text));
}
function expectBindingError(text: any /** TODO #9100 */) { return expect(() => parseBinding(text)); }
function expectBindingError(text: any /** TODO #9100 */) {
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 ignore comments in expressions', () => { checkAction('a //comment', 'a'); });
@ -110,33 +119,33 @@ export function main() {
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', () => {
@ -151,46 +160,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',
@ -199,31 +209,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)');
@ -261,16 +271,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'); });
@ -311,105 +321,109 @@ 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:let b");
var bindings = parseTemplateBindings('a:let b');
expect(keyValues(bindings)).toEqual(['a', 'let 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 with a deprecation warning', () => {
var bindings = createParser().parseTemplateBindings("var i", null);
var bindings = createParser().parseTemplateBindings('var i', null);
expect(keyValues(bindings.templateBindings)).toEqual(['let i=\$implicit']);
expect(bindings.warnings)
.toEqual(['"var" inside of expressions is deprecated. Use "let" instead!']);
expect(bindings.warnings).toEqual([
'"var" inside of expressions is deprecated. Use "let" instead!'
]);
});
it('should support # notation with a deprecation warning', () => {
var bindings = createParser().parseTemplateBindings("#i", null);
var bindings = createParser().parseTemplateBindings('#i', null);
expect(keyValues(bindings.templateBindings)).toEqual(['let i=\$implicit']);
expect(bindings.warnings)
.toEqual(['"#" inside of expressions is deprecated. Use "let" instead!']);
expect(bindings.warnings).toEqual([
'"#" inside of expressions is deprecated. Use "let" instead!'
]);
});
it('should support let notation', () => {
var bindings = parseTemplateBindings("let i");
var bindings = parseTemplateBindings('let i');
expect(keyValues(bindings)).toEqual(['let i=\$implicit']);
bindings = parseTemplateBindings("let i");
bindings = parseTemplateBindings('let i');
expect(keyValues(bindings)).toEqual(['let i=\$implicit']);
bindings = parseTemplateBindings("let a; let b");
bindings = parseTemplateBindings('let a; let b');
expect(keyValues(bindings)).toEqual(['let a=\$implicit', 'let b=\$implicit']);
bindings = parseTemplateBindings("let a; let b;");
bindings = parseTemplateBindings('let a; let b;');
expect(keyValues(bindings)).toEqual(['let a=\$implicit', 'let b=\$implicit']);
bindings = parseTemplateBindings("let i-a = k-a");
bindings = parseTemplateBindings('let i-a = k-a');
expect(keyValues(bindings)).toEqual(['let i-a=k-a']);
bindings = parseTemplateBindings("keyword let item; let i = k");
bindings = parseTemplateBindings('keyword let item; let i = k');
expect(keyValues(bindings)).toEqual(['keyword', 'let item=\$implicit', 'let i=k']);
bindings = parseTemplateBindings("keyword: let item; let i = k");
bindings = parseTemplateBindings('keyword: let item; let i = k');
expect(keyValues(bindings)).toEqual(['keyword', 'let item=\$implicit', 'let i=k']);
bindings = parseTemplateBindings("directive: let item in expr; let a = b", 'location');
expect(keyValues(bindings))
.toEqual(
['directive', 'let item=\$implicit', 'directiveIn=expr in location', 'let a=b']);
bindings = parseTemplateBindings('directive: let item in expr; let a = b', 'location');
expect(keyValues(bindings)).toEqual([
'directive', 'let item=\$implicit', 'directiveIn=expr in location', 'let a=b'
]);
});
it('should parse pipes', () => {
@ -436,14 +450,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',
@ -453,7 +467,7 @@ export function main() {
checkInterpolation(`{{ 'foo' +\n 'bar' +\r 'baz' }}`, `{{ "foo" + "bar" + "baz" }}`);
});
describe("comments", () => {
describe('comments', () => {
it('should ignore comments in interpolation expressions',
() => { checkInterpolation('{{a //comment}}', '{{ a }}'); });
@ -469,29 +483,29 @@ export function main() {
() => { checkInterpolation(`{{ "a//b" //comment }}`, `{{ "a//b" }}`); });
it('should retain // in complex strings', () => {
checkInterpolation(`{{"//a\'//b\`//c\`//d\'//e" //comment}}`, `{{ "//a\'//b\`//c\`//d\'//e" }}`);
checkInterpolation(
`{{"//a\'//b\`//c\`//d\'//e" //comment}}`, `{{ "//a\'//b\`//c\`//d\'//e" }}`);
});
it('should retain // in nested, unterminated strings', () => {
checkInterpolation(`{{ "a\'b\`" //comment}}`, `{{ "a\'b\`" }}`);
});
it('should retain // in nested, unterminated strings',
() => { checkInterpolation(`{{ "a\'b\`" //comment}}`, `{{ "a\'b\`" }}`); });
});
});
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');
});
@ -504,7 +518,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"');
});
});
});

View File

@ -1,29 +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 '../../src/expression_parser/ast';
import {AST, AstVisitor, Binary, BindingPipe, Chain, Conditional, EmptyExpr, FunctionCall, ImplicitReceiver, Interpolation, KeyedRead, KeyedWrite, LiteralArray, LiteralMap, LiteralPrimitive, MethodCall, PrefixNot, PropertyRead, PropertyWrite, Quote, SafeMethodCall, SafePropertyRead} from '../../src/expression_parser/ast';
import {StringWrapper, isPresent, isString} from '../../src/facade/lang';
export class Unparser implements AstVisitor {

View File

@ -1,16 +1,7 @@
import {HtmlParser, HtmlParseTreeResult, HtmlTreeError} from '@angular/compiler/src/html_parser';
import {
HtmlAst,
HtmlAstVisitor,
HtmlElementAst,
HtmlAttrAst,
HtmlTextAst,
HtmlCommentAst,
HtmlExpansionAst,
HtmlExpansionCaseAst,
htmlVisitAll
} from '@angular/compiler/src/html_ast';
import {HtmlAst, HtmlAstVisitor, HtmlAttrAst, HtmlCommentAst, HtmlElementAst, HtmlExpansionAst, HtmlExpansionCaseAst, HtmlTextAst, htmlVisitAll} from '@angular/compiler/src/html_ast';
import {HtmlParseTreeResult, HtmlParser, HtmlTreeError} from '@angular/compiler/src/html_parser';
import {ParseError, ParseLocation} from '@angular/compiler/src/parse_util';
import {BaseException} from '../src/facade/exceptions';
export function humanizeDom(parseResult: HtmlParseTreeResult): any[] {

File diff suppressed because it is too large Load Diff

View File

@ -1,28 +1,9 @@
import {
ddescribe,
describe,
it,
iit,
xit,
expect,
beforeEach,
afterEach
} from '@angular/core/testing/testing_internal';
import {HtmlAst, HtmlAstVisitor, HtmlAttrAst, HtmlCommentAst, HtmlElementAst, HtmlExpansionAst, HtmlExpansionCaseAst, HtmlTextAst, htmlVisitAll} from '@angular/compiler/src/html_ast';
import {HtmlTokenType} from '@angular/compiler/src/html_lexer';
import {HtmlParser, HtmlParseTreeResult, HtmlTreeError} from '@angular/compiler/src/html_parser';
import {
HtmlAst,
HtmlAstVisitor,
HtmlElementAst,
HtmlAttrAst,
HtmlTextAst,
HtmlCommentAst,
htmlVisitAll,
HtmlExpansionAst,
HtmlExpansionCaseAst
} from '@angular/compiler/src/html_ast';
import {HtmlParseTreeResult, HtmlParser, HtmlTreeError} from '@angular/compiler/src/html_parser';
import {ParseError, ParseLocation} from '@angular/compiler/src/parse_util';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {humanizeDom, humanizeDomSourceSpans, humanizeLineColumn} from './html_ast_spec_utils';
export function main() {
@ -37,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', () => {
@ -92,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', () => {
@ -128,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', () => {
@ -206,108 +186,109 @@ 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 namespace', () => {
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]
]);
});
});
describe("expansion forms", () => {
it("should parse out expansion forms", () => {
let parsed = parser.parse(`<div>before{messages.length, plural, =0 {You have <b>no</b> messages} =1 {One {{message}}}}after</div>`,
'TestComp', true);
describe('expansion forms', () => {
it('should parse out expansion forms', () => {
let parsed = parser.parse(
`<div>before{messages.length, plural, =0 {You have <b>no</b> messages} =1 {One {{message}}}}after</div>`,
'TestComp', true);
expect(humanizeDom(parsed))
.toEqual([
[HtmlElementAst, 'div', 0],
[HtmlTextAst, 'before', 1],
[HtmlExpansionAst, 'messages.length', 'plural'],
[HtmlExpansionCaseAst, '0'],
[HtmlExpansionCaseAst, '1'],
[HtmlTextAst, 'after', 1]
]);
expect(humanizeDom(parsed)).toEqual([
[HtmlElementAst, 'div', 0], [HtmlTextAst, 'before', 1],
[HtmlExpansionAst, 'messages.length', 'plural'], [HtmlExpansionCaseAst, '0'],
[HtmlExpansionCaseAst, '1'], [HtmlTextAst, 'after', 1]
]);
let cases = (<any>parsed.rootNodes[0]).children[1].cases;
expect(humanizeDom(new HtmlParseTreeResult(cases[0].expression, [])))
.toEqual([
[HtmlTextAst, 'You have ', 0],
[HtmlElementAst, 'b', 0],
[HtmlTextAst, 'no', 1],
[HtmlTextAst, ' messages', 0],
]);
expect(humanizeDom(new HtmlParseTreeResult(cases[0].expression, []))).toEqual([
[HtmlTextAst, 'You have ', 0],
[HtmlElementAst, 'b', 0],
[HtmlTextAst, 'no', 1],
[HtmlTextAst, ' messages', 0],
]);
expect(humanizeDom(new HtmlParseTreeResult(cases[1].expression, [])))
.toEqual([[HtmlTextAst, 'One {{message}}', 0]]);
expect(humanizeDom(new HtmlParseTreeResult(cases[1].expression, [
]))).toEqual([[HtmlTextAst, 'One {{message}}', 0]]);
});
it("should parse out nested expansion forms", () => {
let parsed = parser.parse(`{messages.length, plural, =0 { {p.gender, gender, =m {m}} }}`,
'TestComp', true);
it('should parse out nested expansion forms', () => {
let parsed = parser.parse(
`{messages.length, plural, =0 { {p.gender, gender, =m {m}} }}`, 'TestComp', true);
expect(humanizeDom(parsed))
.toEqual([
[HtmlExpansionAst, 'messages.length', 'plural'],
[HtmlExpansionCaseAst, '0'],
]);
expect(humanizeDom(parsed)).toEqual([
[HtmlExpansionAst, 'messages.length', 'plural'],
[HtmlExpansionCaseAst, '0'],
]);
let firstCase = (<any>parsed.rootNodes[0]).cases[0];
expect(humanizeDom(new HtmlParseTreeResult(firstCase.expression, [])))
.toEqual([
[HtmlExpansionAst, 'p.gender', 'gender'],
[HtmlExpansionCaseAst, 'm'],
[HtmlTextAst, ' ', 0],
]);
expect(humanizeDom(new HtmlParseTreeResult(firstCase.expression, []))).toEqual([
[HtmlExpansionAst, 'p.gender', 'gender'],
[HtmlExpansionCaseAst, 'm'],
[HtmlTextAst, ' ', 0],
]);
});
it("should error when expansion form is not closed", () => {
it('should error when expansion form is not closed', () => {
let p = parser.parse(`{messages.length, plural, =0 {one}`, 'TestComp', true);
expect(humanizeErrors(p.errors))
.toEqual([[null, "Invalid expansion form. Missing '}'.", '0:34']]);
expect(humanizeErrors(p.errors)).toEqual([
[null, 'Invalid expansion form. Missing \'}\'.', '0:34']
]);
});
it("should error when expansion case is not closed", () => {
it('should error when expansion case is not closed', () => {
let p = parser.parse(`{messages.length, plural, =0 {one`, 'TestComp', true);
expect(humanizeErrors(p.errors))
.toEqual([[null, "Invalid expansion form. Missing '}'.", '0:29']]);
expect(humanizeErrors(p.errors)).toEqual([
[null, 'Invalid expansion form. Missing \'}\'.', '0:29']
]);
});
it("should error when invalid html in the case", () => {
it('should error when invalid html in the case', () => {
let p = parser.parse(`{messages.length, plural, =0 {<b/>}`, 'TestComp', true);
expect(humanizeErrors(p.errors))
.toEqual([['b', 'Only void and foreign elements can be self closed "b"', '0:30']]);
expect(humanizeErrors(p.errors)).toEqual([
['b', 'Only void and foreign elements can be self closed "b"', '0:30']
]);
});
});
@ -352,34 +333,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']
]);
});
});
});

View File

@ -1,59 +1,66 @@
import {describe, expect, it, iit, ddescribe} from "@angular/core/testing/testing_internal";
import {I18nHtmlParser} from "@angular/compiler/src/i18n/i18n_html_parser";
import {Message, id} from "@angular/compiler/src/i18n/message";
import {Parser} from "@angular/compiler/src/expression_parser/parser";
import {Lexer} from "@angular/compiler/src/expression_parser/lexer";
import {StringMapWrapper} from "../../src/facade/collection";
import {HtmlParser, HtmlParseTreeResult} from "@angular/compiler/src/html_parser";
import {HtmlElementAst, HtmlAttrAst, HtmlTextAst} from "@angular/compiler/src/html_ast";
import {deserializeXmb} from "@angular/compiler/src/i18n/xmb_serializer";
import {ParseError} from "@angular/compiler/src/parse_util";
import {humanizeDom} from "@angular/compiler/test/html_ast_spec_utils";
import {Lexer} from '@angular/compiler/src/expression_parser/lexer';
import {Parser} from '@angular/compiler/src/expression_parser/parser';
import {HtmlAttrAst, HtmlElementAst, HtmlTextAst} from '@angular/compiler/src/html_ast';
import {HtmlParseTreeResult, HtmlParser} from '@angular/compiler/src/html_parser';
import {I18nHtmlParser} from '@angular/compiler/src/i18n/i18n_html_parser';
import {Message, id} from '@angular/compiler/src/i18n/message';
import {deserializeXmb} from '@angular/compiler/src/i18n/xmb_serializer';
import {ParseError} from '@angular/compiler/src/parse_util';
import {humanizeDom} from '@angular/compiler/test/html_ast_spec_utils';
import {ddescribe, describe, expect, iit, it} from '@angular/core/testing/testing_internal';
import {StringMapWrapper} from '../../src/facade/collection';
export function main() {
describe('I18nHtmlParser', () => {
function parse(template: string, messages: {[key: string]: string}, implicitTags: string[] = [],
implicitAttrs: {[k: string]: string[]} = {}): HtmlParseTreeResult {
function parse(
template: string, messages: {[key: string]: string}, implicitTags: string[] = [],
implicitAttrs: {[k: string]: string[]} = {}): HtmlParseTreeResult {
var parser = new Parser(new Lexer());
let htmlParser = new HtmlParser();
let msgs = '';
StringMapWrapper.forEach(messages, (v: any /** TODO #9100 */, k: any /** TODO #9100 */) => msgs += `<msg id="${k}">${v}</msg>`);
StringMapWrapper.forEach(
messages, (v: any /** TODO #9100 */, k: any /** TODO #9100 */) => msgs +=
`<msg id="${k}">${v}</msg>`);
let res = deserializeXmb(`<message-bundle>${msgs}</message-bundle>`, 'someUrl');
return new I18nHtmlParser(htmlParser, parser, res.content, res.messages, implicitTags,
implicitAttrs)
.parse(template, "someurl", true);
return new I18nHtmlParser(
htmlParser, parser, res.content, res.messages, implicitTags, implicitAttrs)
.parse(template, 'someurl', true);
}
it("should delegate to the provided parser when no i18n", () => {
expect(humanizeDom(parse('<div>a</div>', {})))
.toEqual([[HtmlElementAst, 'div', 0], [HtmlTextAst, 'a', 1]]);
it('should delegate to the provided parser when no i18n', () => {
expect(humanizeDom(parse('<div>a</div>', {}))).toEqual([
[HtmlElementAst, 'div', 0], [HtmlTextAst, 'a', 1]
]);
});
it("should replace attributes", () => {
it('should replace attributes', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message("some message", "meaning", null))] = "another message";
translations[id(new Message('some message', 'meaning', null))] = 'another message';
expect(humanizeDom(parse("<div value='some message' i18n-value='meaning|comment'></div>",
translations)))
expect(
humanizeDom(parse(
'<div value=\'some message\' i18n-value=\'meaning|comment\'></div>', translations)))
.toEqual([[HtmlElementAst, 'div', 0], [HtmlAttrAst, 'value', 'another message']]);
});
it("should replace elements with the i18n attr", () => {
it('should replace elements with the i18n attr', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message("message", "meaning", null))] = "another message";
translations[id(new Message('message', 'meaning', null))] = 'another message';
expect(humanizeDom(parse("<div i18n='meaning|desc'>message</div>", translations)))
.toEqual([[HtmlElementAst, 'div', 0], [HtmlTextAst, 'another message', 1]]);
expect(humanizeDom(parse('<div i18n=\'meaning|desc\'>message</div>', translations))).toEqual([
[HtmlElementAst, 'div', 0], [HtmlTextAst, 'another message', 1]
]);
});
it("should handle interpolation", () => {
it('should handle interpolation', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message('<ph name="0"/> and <ph name="1"/>', null, null))] =
'<ph name="1"/> or <ph name="0"/>';
expect(humanizeDom(parse("<div value='{{a}} and {{b}}' i18n-value></div>", translations)))
expect(humanizeDom(parse('<div value=\'{{a}} and {{b}}\' i18n-value></div>', translations)))
.toEqual([[HtmlElementAst, 'div', 0], [HtmlAttrAst, 'value', '{{b}} or {{a}}']]);
});
@ -87,37 +94,35 @@ export function main() {
]);
});
it("should handle nested html", () => {
it('should handle nested html', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message('<ph name="e0">a</ph><ph name="e2">b</ph>', null, null))] =
'<ph name="e2">B</ph><ph name="e0">A</ph>';
expect(humanizeDom(parse('<div i18n><a>a</a><b>b</b></div>', translations)))
.toEqual([
[HtmlElementAst, 'div', 0],
[HtmlElementAst, 'b', 1],
[HtmlTextAst, 'B', 2],
[HtmlElementAst, 'a', 1],
[HtmlTextAst, 'A', 2],
]);
expect(humanizeDom(parse('<div i18n><a>a</a><b>b</b></div>', translations))).toEqual([
[HtmlElementAst, 'div', 0],
[HtmlElementAst, 'b', 1],
[HtmlTextAst, 'B', 2],
[HtmlElementAst, 'a', 1],
[HtmlTextAst, 'A', 2],
]);
});
it("should support interpolation", () => {
it('should support interpolation', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message(
'<ph name="e0">a</ph><ph name="e2"><ph name="t3">b<ph name="0"/></ph></ph>', null,
null))] = '<ph name="e2"><ph name="t3"><ph name="0"/>B</ph></ph><ph name="e0">A</ph>';
expect(humanizeDom(parse('<div i18n><a>a</a><b>b{{i}}</b></div>', translations)))
.toEqual([
[HtmlElementAst, 'div', 0],
[HtmlElementAst, 'b', 1],
[HtmlTextAst, '{{i}}B', 2],
[HtmlElementAst, 'a', 1],
[HtmlTextAst, 'A', 2],
]);
expect(humanizeDom(parse('<div i18n><a>a</a><b>b{{i}}</b></div>', translations))).toEqual([
[HtmlElementAst, 'div', 0],
[HtmlElementAst, 'b', 1],
[HtmlTextAst, '{{i}}B', 2],
[HtmlElementAst, 'a', 1],
[HtmlTextAst, 'A', 2],
]);
});
it("should i18n attributes of placeholder elements", () => {
it('should i18n attributes of placeholder elements', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message('<ph name="e0">a</ph>', null, null))] = '<ph name="e0">A</ph>';
translations[id(new Message('b', null, null))] = 'B';
@ -126,21 +131,19 @@ export function main() {
.toEqual([
[HtmlElementAst, 'div', 0],
[HtmlElementAst, 'a', 1],
[HtmlAttrAst, 'value', "B"],
[HtmlAttrAst, 'value', 'B'],
[HtmlTextAst, 'A', 2],
]);
});
it("should preserve non-i18n attributes", () => {
it('should preserve non-i18n attributes', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message('message', null, null))] = 'another message';
expect(humanizeDom(parse('<div i18n value="b">message</div>', translations)))
.toEqual([
[HtmlElementAst, 'div', 0],
[HtmlAttrAst, 'value', "b"],
[HtmlTextAst, 'another message', 1]
]);
expect(humanizeDom(parse('<div i18n value="b">message</div>', translations))).toEqual([
[HtmlElementAst, 'div', 0], [HtmlAttrAst, 'value', 'b'],
[HtmlTextAst, 'another message', 1]
]);
});
it('should extract from partitions', () => {
@ -148,16 +151,17 @@ export function main() {
translations[id(new Message('message1', 'meaning1', null))] = 'another message1';
translations[id(new Message('message2', 'meaning2', null))] = 'another message2';
let res = parse(`<!-- i18n: meaning1|desc1 -->message1<!-- /i18n --><!-- i18n: meaning2|desc2 -->message2<!-- /i18n -->`, translations);
let res = parse(
`<!-- i18n: meaning1|desc1 -->message1<!-- /i18n --><!-- i18n: meaning2|desc2 -->message2<!-- /i18n -->`,
translations);
expect(humanizeDom(res))
.toEqual([
[HtmlTextAst, 'another message1', 0],
[HtmlTextAst, 'another message2', 0],
]);
expect(humanizeDom(res)).toEqual([
[HtmlTextAst, 'another message1', 0],
[HtmlTextAst, 'another message2', 0],
]);
});
it("should preserve original positions", () => {
it('should preserve original positions', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message('<ph name="e0">a</ph><ph name="e2">b</ph>', null, null))] =
'<ph name="e2">B</ph><ph name="e0">A</ph>';
@ -169,54 +173,43 @@ export function main() {
expect(res[1].sourceSpan.start.offset).toEqual(10);
});
it("should handle the plural expansion form", () => {
it('should handle the plural expansion form', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message('zero<ph name="e1">bold</ph>', "plural_0", null))] =
translations[id(new Message('zero<ph name="e1">bold</ph>', 'plural_0', null))] =
'ZERO<ph name="e1">BOLD</ph>';
let res = parse(`{messages.length, plural,=0 {zero<b>bold</b>}}`, translations);
expect(humanizeDom(res))
.toEqual([
[HtmlElementAst, 'ul', 0],
[HtmlAttrAst, '[ngPlural]', 'messages.length'],
[HtmlElementAst, 'template', 1],
[HtmlAttrAst, 'ngPluralCase', '0'],
[HtmlElementAst, 'li', 2],
[HtmlTextAst, 'ZERO', 3],
[HtmlElementAst, 'b', 3],
[HtmlTextAst, 'BOLD', 4]
]);
expect(humanizeDom(res)).toEqual([
[HtmlElementAst, 'ul', 0], [HtmlAttrAst, '[ngPlural]', 'messages.length'],
[HtmlElementAst, 'template', 1], [HtmlAttrAst, 'ngPluralCase', '0'],
[HtmlElementAst, 'li', 2], [HtmlTextAst, 'ZERO', 3], [HtmlElementAst, 'b', 3],
[HtmlTextAst, 'BOLD', 4]
]);
});
it("should handle nested expansion forms", () => {
it('should handle nested expansion forms', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message('m', "gender_m", null))] = 'M';
translations[id(new Message('m', 'gender_m', null))] = 'M';
let res = parse(`{messages.length, plural, =0 { {p.gender, gender, =m {m}} }}`, translations);
expect(humanizeDom(res))
.toEqual([
[HtmlElementAst, 'ul', 0],
[HtmlAttrAst, '[ngPlural]', 'messages.length'],
[HtmlElementAst, 'template', 1],
[HtmlAttrAst, 'ngPluralCase', '0'],
[HtmlElementAst, 'li', 2],
expect(humanizeDom(res)).toEqual([
[HtmlElementAst, 'ul', 0], [HtmlAttrAst, '[ngPlural]', 'messages.length'],
[HtmlElementAst, 'template', 1], [HtmlAttrAst, 'ngPluralCase', '0'],
[HtmlElementAst, 'li', 2],
[HtmlElementAst, 'ul', 3],
[HtmlAttrAst, '[ngSwitch]', 'p.gender'],
[HtmlElementAst, 'template', 4],
[HtmlAttrAst, 'ngSwitchWhen', 'm'],
[HtmlElementAst, 'li', 5],
[HtmlTextAst, 'M', 6],
[HtmlElementAst, 'ul', 3], [HtmlAttrAst, '[ngSwitch]', 'p.gender'],
[HtmlElementAst, 'template', 4], [HtmlAttrAst, 'ngSwitchWhen', 'm'],
[HtmlElementAst, 'li', 5], [HtmlTextAst, 'M', 6],
[HtmlTextAst, ' ', 3]
]);
[HtmlTextAst, ' ', 3]
]);
});
it("should correctly set source code positions", () => {
it('should correctly set source code positions', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message('<ph name="e0">bold</ph>', "plural_0", null))] =
translations[id(new Message('<ph name="e0">bold</ph>', 'plural_0', null))] =
'<ph name="e0">BOLD</ph>';
let nodes = parse(`{messages.length, plural,=0 {<b>bold</b>}}`, translations).rootNodes;
@ -253,101 +246,106 @@ export function main() {
expect(b.sourceSpan.end.col).toEqual(32);
});
it("should handle other special forms", () => {
it('should handle other special forms', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message('m', "gender_male", null))] = 'M';
translations[id(new Message('m', 'gender_male', null))] = 'M';
let res = parse(`{person.gender, gender,=male {m}}`, translations);
expect(humanizeDom(res))
.toEqual([
[HtmlElementAst, 'ul', 0],
[HtmlAttrAst, '[ngSwitch]', 'person.gender'],
[HtmlElementAst, 'template', 1],
[HtmlAttrAst, 'ngSwitchWhen', 'male'],
[HtmlElementAst, 'li', 2],
[HtmlTextAst, 'M', 3],
]);
expect(humanizeDom(res)).toEqual([
[HtmlElementAst, 'ul', 0],
[HtmlAttrAst, '[ngSwitch]', 'person.gender'],
[HtmlElementAst, 'template', 1],
[HtmlAttrAst, 'ngSwitchWhen', 'male'],
[HtmlElementAst, 'li', 2],
[HtmlTextAst, 'M', 3],
]);
});
describe("errors", () => {
it("should error when giving an invalid template", () => {
expect(humanizeErrors(parse("<a>a</b>", {}).errors))
.toEqual(['Unexpected closing tag "b"']);
describe('errors', () => {
it('should error when giving an invalid template', () => {
expect(humanizeErrors(parse('<a>a</b>', {}).errors)).toEqual([
'Unexpected closing tag "b"'
]);
});
it("should error when no matching message (attr)", () => {
let mid = id(new Message("some message", null, null));
expect(humanizeErrors(parse("<div value='some message' i18n-value></div>", {}).errors))
it('should error when no matching message (attr)', () => {
let mid = id(new Message('some message', null, null));
expect(humanizeErrors(parse('<div value=\'some message\' i18n-value></div>', {}).errors))
.toEqual([`Cannot find message for id '${mid}', content 'some message'.`]);
});
it("should error when no matching message (text)", () => {
let mid = id(new Message("some message", null, null));
expect(humanizeErrors(parse("<div i18n>some message</div>", {}).errors))
.toEqual([`Cannot find message for id '${mid}', content 'some message'.`]);
it('should error when no matching message (text)', () => {
let mid = id(new Message('some message', null, null));
expect(humanizeErrors(parse('<div i18n>some message</div>', {}).errors)).toEqual([
`Cannot find message for id '${mid}', content 'some message'.`
]);
});
it("should error when a non-placeholder element appears in translation", () => {
it('should error when a non-placeholder element appears in translation', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message("some message", null, null))] = "<a>a</a>";
translations[id(new Message('some message', null, null))] = '<a>a</a>';
expect(humanizeErrors(parse("<div i18n>some message</div>", translations).errors))
.toEqual([`Unexpected tag "a". Only "ph" tags are allowed.`]);
expect(humanizeErrors(parse('<div i18n>some message</div>', translations).errors)).toEqual([
`Unexpected tag "a". Only "ph" tags are allowed.`
]);
});
it("should error when a placeholder element does not have the name attribute", () => {
it('should error when a placeholder element does not have the name attribute', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message("some message", null, null))] = "<ph>a</ph>";
translations[id(new Message('some message', null, null))] = '<ph>a</ph>';
expect(humanizeErrors(parse("<div i18n>some message</div>", translations).errors))
.toEqual([`Missing "name" attribute.`]);
expect(humanizeErrors(parse('<div i18n>some message</div>', translations).errors)).toEqual([
`Missing "name" attribute.`
]);
});
it("should error when the translation refers to an invalid expression", () => {
it('should error when the translation refers to an invalid expression', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message('hi <ph name="0"/>', null, null))] = 'hi <ph name="99"/>';
expect(
humanizeErrors(parse("<div value='hi {{a}}' i18n-value></div>", translations).errors))
.toEqual(["Invalid interpolation name '99'"]);
humanizeErrors(parse('<div value=\'hi {{a}}\' i18n-value></div>', translations).errors))
.toEqual(['Invalid interpolation name \'99\'']);
});
describe('implicit translation', () => {
it("should support attributes", () => {
it('should support attributes', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message("some message", null, null))] = "another message";
translations[id(new Message('some message', null, null))] = 'another message';
expect(humanizeDom(parse("<i18n-el value='some message'></i18n-el>", translations, [],
{'i18n-el': ['value']})))
expect(humanizeDom(parse('<i18n-el value=\'some message\'></i18n-el>', translations, [], {
'i18n-el': ['value']
}))).toEqual([[HtmlElementAst, 'i18n-el', 0], [HtmlAttrAst, 'value', 'another message']]);
});
it('should support attributes with meaning and description', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message('some message', 'meaning', 'description'))] =
'another message';
expect(
humanizeDom(parse(
'<i18n-el value=\'some message\' i18n-value=\'meaning|description\'></i18n-el>',
translations, [], {'i18n-el': ['value']})))
.toEqual([[HtmlElementAst, 'i18n-el', 0], [HtmlAttrAst, 'value', 'another message']]);
});
it("should support attributes with meaning and description", () => {
it('should support elements', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message("some message", "meaning", "description"))] =
"another message";
translations[id(new Message('message', null, null))] = 'another message';
expect(humanizeDom(parse(
"<i18n-el value='some message' i18n-value='meaning|description'></i18n-el>",
translations, [], {'i18n-el': ['value']})))
.toEqual([[HtmlElementAst, 'i18n-el', 0], [HtmlAttrAst, 'value', 'another message']]);
});
it("should support elements", () => {
let translations: {[key: string]: string} = {};
translations[id(new Message("message", null, null))] = "another message";
expect(humanizeDom(parse("<i18n-el>message</i18n-el>", translations, ['i18n-el'])))
expect(humanizeDom(parse('<i18n-el>message</i18n-el>', translations, ['i18n-el'])))
.toEqual([[HtmlElementAst, 'i18n-el', 0], [HtmlTextAst, 'another message', 1]]);
});
it("should support elements with meaning and description", () => {
it('should support elements with meaning and description', () => {
let translations: {[key: string]: string} = {};
translations[id(new Message("message", "meaning", "description"))] = "another message";
translations[id(new Message('message', 'meaning', 'description'))] = 'another message';
expect(humanizeDom(parse("<i18n-el i18n='meaning|description'>message</i18n-el>",
translations, ['i18n-el'])))
expect(humanizeDom(parse(
'<i18n-el i18n=\'meaning|description\'>message</i18n-el>', translations,
['i18n-el'])))
.toEqual([[HtmlElementAst, 'i18n-el', 0], [HtmlTextAst, 'another message', 1]]);
});
});

View File

@ -1,20 +1,9 @@
import {
beforeEach,
describe,
ddescribe,
expect,
iit,
inject,
it,
xdescribe,
xit
} from '@angular/core/testing/testing_internal';
import {HtmlParser} from '@angular/compiler/src/html_parser';
import {MessageExtractor, removeDuplicates} from '@angular/compiler/src/i18n/message_extractor';
import {Message} from '@angular/compiler/src/i18n/message';
import {Parser} from '@angular/compiler/src/expression_parser/parser';
import {Lexer} from '@angular/compiler/src/expression_parser/lexer';
import {Parser} from '@angular/compiler/src/expression_parser/parser';
import {HtmlParser} from '@angular/compiler/src/html_parser';
import {Message} from '@angular/compiler/src/i18n/message';
import {MessageExtractor, removeDuplicates} from '@angular/compiler/src/i18n/message_extractor';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
export function main() {
describe('MessageExtractor', () => {
@ -27,156 +16,144 @@ export function main() {
});
it('should extract from elements with the i18n attr', () => {
let res = extractor.extract("<div i18n='meaning|desc'>message</div>", "someurl");
expect(res.messages).toEqual([new Message("message", 'meaning', 'desc')]);
let res = extractor.extract('<div i18n=\'meaning|desc\'>message</div>', 'someurl');
expect(res.messages).toEqual([new Message('message', 'meaning', 'desc')]);
});
it('should extract from elements with the i18n attr without a desc', () => {
let res = extractor.extract("<div i18n='meaning'>message</div>", "someurl");
expect(res.messages).toEqual([new Message("message", 'meaning', null)]);
let res = extractor.extract('<div i18n=\'meaning\'>message</div>', 'someurl');
expect(res.messages).toEqual([new Message('message', 'meaning', null)]);
});
it('should extract from elements with the i18n attr without a meaning', () => {
let res = extractor.extract("<div i18n>message</div>", "someurl");
expect(res.messages).toEqual([new Message("message", null, null)]);
let res = extractor.extract('<div i18n>message</div>', 'someurl');
expect(res.messages).toEqual([new Message('message', null, null)]);
});
it('should extract from attributes', () => {
let res = extractor.extract(`
let res = extractor.extract(
`
<div
title1='message1' i18n-title1='meaning1|desc1'
title2='message2' i18n-title2='meaning2|desc2'>
</div>
`,
"someurl");
'someurl');
expect(res.messages)
.toEqual([
new Message("message1", "meaning1", "desc1"),
new Message("message2", "meaning2", "desc2")
]);
expect(res.messages).toEqual([
new Message('message1', 'meaning1', 'desc1'), new Message('message2', 'meaning2', 'desc2')
]);
});
it('should extract from partitions', () => {
let res = extractor.extract(`
let res = extractor.extract(
`
<!-- i18n: meaning1|desc1 -->message1<!-- /i18n -->
<!-- i18n: meaning2|desc2 -->message2<!-- /i18n -->`,
"someUrl");
'someUrl');
expect(res.messages)
.toEqual([
new Message("message1", "meaning1", "desc1"),
new Message("message2", "meaning2", "desc2")
]);
expect(res.messages).toEqual([
new Message('message1', 'meaning1', 'desc1'), new Message('message2', 'meaning2', 'desc2')
]);
});
it('should ignore other comments', () => {
let res = extractor.extract(`
let res = extractor.extract(
`
<!-- i18n: meaning1|desc1 --><!-- other -->message1<!-- /i18n -->`,
"someUrl");
'someUrl');
expect(res.messages).toEqual([new Message("message1", "meaning1", "desc1")]);
expect(res.messages).toEqual([new Message('message1', 'meaning1', 'desc1')]);
});
it('should replace interpolation with placeholders (text nodes)', () => {
let res = extractor.extract("<div i18n>Hi {{one}} and {{two}}</div>", "someurl");
expect(res.messages)
.toEqual(
[new Message('<ph name="t0">Hi <ph name="0"/> and <ph name="1"/></ph>', null, null)]);
let res = extractor.extract('<div i18n>Hi {{one}} and {{two}}</div>', 'someurl');
expect(res.messages).toEqual([new Message(
'<ph name="t0">Hi <ph name="0"/> and <ph name="1"/></ph>', null, null)]);
});
it('should replace interpolation with placeholders (attributes)', () => {
let res =
extractor.extract("<div title='Hi {{one}} and {{two}}' i18n-title></div>", "someurl");
expect(res.messages)
.toEqual([new Message('Hi <ph name="0"/> and <ph name="1"/>', null, null)]);
extractor.extract('<div title=\'Hi {{one}} and {{two}}\' i18n-title></div>', 'someurl');
expect(res.messages).toEqual([new Message(
'Hi <ph name="0"/> and <ph name="1"/>', null, null)]);
});
it('should replace interpolation with named placeholders if provided (text nodes)', () => {
let res = extractor.extract(`
let res = extractor.extract(
`
<div i18n>Hi {{one //i18n(ph="FIRST")}} and {{two //i18n(ph="SECOND")}}</div>`,
'someurl');
expect(res.messages)
.toEqual([
new Message('<ph name="t0">Hi <ph name="FIRST"/> and <ph name="SECOND"/></ph>', null,
null)
]);
'someurl');
expect(res.messages).toEqual([new Message(
'<ph name="t0">Hi <ph name="FIRST"/> and <ph name="SECOND"/></ph>', null, null)]);
});
it('should replace interpolation with named placeholders if provided (attributes)', () => {
let res = extractor.extract(`
let res = extractor.extract(
`
<div title='Hi {{one //i18n(ph="FIRST")}} and {{two //i18n(ph="SECOND")}}'
i18n-title></div>`,
'someurl');
expect(res.messages)
.toEqual([new Message('Hi <ph name="FIRST"/> and <ph name="SECOND"/>', null, null)]);
'someurl');
expect(res.messages).toEqual([new Message(
'Hi <ph name="FIRST"/> and <ph name="SECOND"/>', null, null)]);
});
it('should match named placeholders with extra spacing', () => {
let res = extractor.extract(`
let res = extractor.extract(
`
<div title='Hi {{one // i18n ( ph = "FIRST" )}} and {{two // i18n ( ph = "SECOND" )}}'
i18n-title></div>`,
'someurl');
expect(res.messages)
.toEqual([new Message('Hi <ph name="FIRST"/> and <ph name="SECOND"/>', null, null)]);
'someurl');
expect(res.messages).toEqual([new Message(
'Hi <ph name="FIRST"/> and <ph name="SECOND"/>', null, null)]);
});
it('should suffix duplicate placeholder names with numbers', () => {
let res = extractor.extract(`
let res = extractor.extract(
`
<div title='Hi {{one //i18n(ph="FIRST")}} and {{two //i18n(ph="FIRST")}} and {{three //i18n(ph="FIRST")}}'
i18n-title></div>`,
'someurl');
expect(res.messages)
.toEqual([
new Message('Hi <ph name="FIRST"/> and <ph name="FIRST_1"/> and <ph name="FIRST_2"/>',
null, null)
]);
'someurl');
expect(res.messages).toEqual([new Message(
'Hi <ph name="FIRST"/> and <ph name="FIRST_1"/> and <ph name="FIRST_2"/>', null, null)]);
});
it("should handle html content", () => {
it('should handle html content', () => {
let res = extractor.extract(
'<div i18n><div attr="value">zero<div>one</div></div><div>two</div></div>', "someurl");
expect(res.messages)
.toEqual([
new Message('<ph name="e0">zero<ph name="e2">one</ph></ph><ph name="e4">two</ph>', null,
null)
]);
'<div i18n><div attr="value">zero<div>one</div></div><div>two</div></div>', 'someurl');
expect(res.messages).toEqual([new Message(
'<ph name="e0">zero<ph name="e2">one</ph></ph><ph name="e4">two</ph>', null, null)]);
});
it("should handle html content with interpolation", () => {
it('should handle html content with interpolation', () => {
let res =
extractor.extract('<div i18n><div>zero{{a}}<div>{{b}}</div></div></div>', "someurl");
expect(res.messages)
.toEqual([
new Message(
'<ph name="e0"><ph name="t1">zero<ph name="0"/></ph><ph name="e2"><ph name="t3"><ph name="0"/></ph></ph></ph>',
null, null)
]);
extractor.extract('<div i18n><div>zero{{a}}<div>{{b}}</div></div></div>', 'someurl');
expect(res.messages).toEqual([new Message(
'<ph name="e0"><ph name="t1">zero<ph name="0"/></ph><ph name="e2"><ph name="t3"><ph name="0"/></ph></ph></ph>',
null, null)]);
});
it("should extract from nested elements", () => {
it('should extract from nested elements', () => {
let res = extractor.extract(
'<div title="message1" i18n-title="meaning1|desc1"><div i18n="meaning2|desc2">message2</div></div>',
"someurl");
expect(res.messages)
.toEqual([
new Message("message2", "meaning2", "desc2"),
new Message("message1", "meaning1", "desc1")
]);
'someurl');
expect(res.messages).toEqual([
new Message('message2', 'meaning2', 'desc2'), new Message('message1', 'meaning1', 'desc1')
]);
});
it("should extract messages from attributes in i18n blocks", () => {
it('should extract messages from attributes in i18n blocks', () => {
let res = extractor.extract(
'<div i18n><div attr="value" i18n-attr="meaning|desc">message</div></div>', "someurl");
expect(res.messages)
.toEqual([
new Message('<ph name="e0">message</ph>', null, null),
new Message('value', "meaning", "desc")
]);
'<div i18n><div attr="value" i18n-attr="meaning|desc">message</div></div>', 'someurl');
expect(res.messages).toEqual([
new Message('<ph name="e0">message</ph>', null, null),
new Message('value', 'meaning', 'desc')
]);
});
it("should extract messages from special forms", () => {
let res = extractor.extract(`
it('should extract messages from special forms', () => {
let res = extractor.extract(
`
<div>
{messages.length, plural,
=0 {You have <b>no</b> messages}
@ -184,75 +161,76 @@ export function main() {
}
</div>
`,
"someurl");
'someurl');
expect(res.messages)
.toEqual([
new Message('You have <ph name="e1">no</ph> messages', "plural_0", null),
new Message('You have one message', "plural_1", null)
]);
expect(res.messages).toEqual([
new Message('You have <ph name="e1">no</ph> messages', 'plural_0', null),
new Message('You have one message', 'plural_1', null)
]);
});
it("should remove duplicate messages", () => {
let res = extractor.extract(`
it('should remove duplicate messages', () => {
let res = extractor.extract(
`
<!-- i18n: meaning|desc1 -->message<!-- /i18n -->
<!-- i18n: meaning|desc2 -->message<!-- /i18n -->`,
"someUrl");
'someUrl');
expect(removeDuplicates(res.messages))
.toEqual([
new Message("message", "meaning", "desc1"),
]);
expect(removeDuplicates(res.messages)).toEqual([
new Message('message', 'meaning', 'desc1'),
]);
});
describe('implicit translation', () => {
it('should extract from elements', () => {
let res = extractor.extract("<i18n-tag>message</i18n-tag>", "someurl");
expect(res.messages).toEqual([new Message("message", null, null)]);
let res = extractor.extract('<i18n-tag>message</i18n-tag>', 'someurl');
expect(res.messages).toEqual([new Message('message', null, null)]);
});
it('should extract meaning and description from elements when present', () => {
let res =
extractor.extract("<i18n-tag i18n='meaning|description'>message</i18n-tag>", "someurl");
expect(res.messages).toEqual([new Message("message", "meaning", "description")]);
let res = extractor.extract(
'<i18n-tag i18n=\'meaning|description\'>message</i18n-tag>', 'someurl');
expect(res.messages).toEqual([new Message('message', 'meaning', 'description')]);
});
it('should extract from attributes', () => {
let res = extractor.extract(`<i18n-el trans='message'></i18n-el>`, "someurl");
expect(res.messages).toEqual([new Message("message", null, null)]);
let res = extractor.extract(`<i18n-el trans='message'></i18n-el>`, 'someurl');
expect(res.messages).toEqual([new Message('message', null, null)]);
});
it('should extract meaning and description from attributes when present', () => {
let res = extractor.extract(`<i18n-el trans='message' i18n-trans="meaning|desc"></i18n-el>`,
"someurl");
expect(res.messages).toEqual([new Message("message", "meaning", "desc")]);
let res = extractor.extract(
`<i18n-el trans='message' i18n-trans="meaning|desc"></i18n-el>`, 'someurl');
expect(res.messages).toEqual([new Message('message', 'meaning', 'desc')]);
});
});
describe("errors", () => {
describe('errors', () => {
it('should error on i18n attributes without matching "real" attributes', () => {
let res = extractor.extract(`
let res = extractor.extract(
`
<div
title1='message1' i18n-title1='meaning1|desc1' i18n-title2='meaning2|desc2'>
</div>
`,
"someurl");
'someurl');
expect(res.errors.length).toEqual(1);
expect(res.errors[0].msg).toEqual("Missing attribute 'title2'.");
expect(res.errors[0].msg).toEqual('Missing attribute \'title2\'.');
});
it('should error when cannot find a matching desc', () => {
let res = extractor.extract(`
let res = extractor.extract(
`
<!-- i18n: meaning1|desc1 -->message1`,
"someUrl");
'someUrl');
expect(res.errors.length).toEqual(1);
expect(res.errors[0].msg).toEqual("Missing closing 'i18n' comment.");
expect(res.errors[0].msg).toEqual('Missing closing \'i18n\' comment.');
});
it("should return parse errors when the template is invalid", () => {
let res = extractor.extract("<input&#Besfs", "someurl");
it('should return parse errors when the template is invalid', () => {
let res = extractor.extract('<input&#Besfs', 'someurl');
expect(res.errors.length).toEqual(1);
expect(res.errors[0].msg).toEqual('Unexpected character "s"');
});

View File

@ -1,23 +1,12 @@
import {
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xdescribe,
xit
} from '@angular/core/testing/testing_internal';
import {Message, id} from '@angular/compiler/src/i18n/message';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
export function main() {
describe('Message', () => {
describe("id", () => {
it("should return a different id for messages with and without the meaning", () => {
let m1 = new Message("content", "meaning", null);
let m2 = new Message("content", null, null);
describe('id', () => {
it('should return a different id for messages with and without the meaning', () => {
let m1 = new Message('content', 'meaning', null);
let m2 = new Message('content', null, null);
expect(id(m1)).toEqual(id(m1));
expect(id(m1)).not.toEqual(id(m2));
});

View File

@ -1,47 +1,36 @@
import {
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xdescribe,
xit
} from '@angular/core/testing/testing_internal';
import {HtmlAst} from '@angular/compiler/src/html_ast';
import {Message, id} from '@angular/compiler/src/i18n/message';
import {serializeXmb, deserializeXmb} from '@angular/compiler/src/i18n/xmb_serializer';
import {ParseSourceSpan, ParseError} from '@angular/compiler/src/parse_util';
import {deserializeXmb, serializeXmb} from '@angular/compiler/src/i18n/xmb_serializer';
import {ParseError, ParseSourceSpan} from '@angular/compiler/src/parse_util';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
export function main() {
describe("Xmb", () => {
describe('Xmb', () => {
describe('Xmb Serialization', () => {
it("should return an empty message bundle for an empty list of messages",
() => { expect(serializeXmb([])).toEqual("<message-bundle></message-bundle>"); });
it('should return an empty message bundle for an empty list of messages',
() => { expect(serializeXmb([])).toEqual('<message-bundle></message-bundle>'); });
it("should serializeXmb messages without desc", () => {
let m = new Message("content", "meaning", null);
it('should serializeXmb messages without desc', () => {
let m = new Message('content', 'meaning', null);
let expected = `<message-bundle><msg id='${id(m)}'>content</msg></message-bundle>`;
expect(serializeXmb([m])).toEqual(expected);
});
it("should serializeXmb messages with desc", () => {
let m = new Message("content", "meaning", "description");
it('should serializeXmb messages with desc', () => {
let m = new Message('content', 'meaning', 'description');
let expected =
`<message-bundle><msg id='${id(m)}' desc='description'>content</msg></message-bundle>`;
expect(serializeXmb([m])).toEqual(expected);
});
});
describe("Xmb Deserialization", () => {
it("should parse an empty bundle", () => {
let mb = "<message-bundle></message-bundle>";
expect(deserializeXmb(mb, "url").messages).toEqual({});
describe('Xmb Deserialization', () => {
it('should parse an empty bundle', () => {
let mb = '<message-bundle></message-bundle>';
expect(deserializeXmb(mb, 'url').messages).toEqual({});
});
it("should parse an non-empty bundle", () => {
it('should parse an non-empty bundle', () => {
let mb = `
<message-bundle>
<msg id="id1" desc="description1">content1</msg>
@ -49,59 +38,59 @@ export function main() {
</message-bundle>
`;
let parsed = deserializeXmb(mb, "url").messages;
expect(_serialize(parsed["id1"])).toEqual("content1");
expect(_serialize(parsed["id2"])).toEqual("content2");
let parsed = deserializeXmb(mb, 'url').messages;
expect(_serialize(parsed['id1'])).toEqual('content1');
expect(_serialize(parsed['id2'])).toEqual('content2');
});
it("should error when cannot parse the content", () => {
it('should error when cannot parse the content', () => {
let mb = `
<message-bundle>
<msg id="id1" desc="description1">content
</message-bundle>
`;
let res = deserializeXmb(mb, "url");
let res = deserializeXmb(mb, 'url');
expect(_serializeErrors(res.errors)).toEqual(['Unexpected closing tag "message-bundle"']);
});
it("should error when cannot find the id attribute", () => {
it('should error when cannot find the id attribute', () => {
let mb = `
<message-bundle>
<msg>content</msg>
</message-bundle>
`;
let res = deserializeXmb(mb, "url");
let res = deserializeXmb(mb, 'url');
expect(_serializeErrors(res.errors)).toEqual(['"id" attribute is missing']);
});
it("should error on empty content", () => {
it('should error on empty content', () => {
let mb = ``;
let res = deserializeXmb(mb, "url");
let res = deserializeXmb(mb, 'url');
expect(_serializeErrors(res.errors)).toEqual(['Missing element "message-bundle"']);
});
it("should error on an invalid element", () => {
it('should error on an invalid element', () => {
let mb = `
<message-bundle>
<invalid>content</invalid>
</message-bundle>
`;
let res = deserializeXmb(mb, "url");
let res = deserializeXmb(mb, 'url');
expect(_serializeErrors(res.errors)).toEqual(['Unexpected element "invalid"']);
});
it("should expand 'ph' elements", () => {
it('should expand \'ph\' elements', () => {
let mb = `
<message-bundle>
<msg id="id1">a<ph name="i0"/></msg>
</message-bundle>
`;
let res = deserializeXmb(mb, "url").messages["id1"];
expect((<any>res[1]).name).toEqual("ph");
let res = deserializeXmb(mb, 'url').messages['id1'];
expect((<any>res[1]).name).toEqual('ph');
});
});
});

View File

@ -1,5 +1,5 @@
import {Component} from '@angular/core';
@Component({styles:<any>('foo'), template: ''})
@Component({styles: <any>('foo'), template: ''})
export class MalformedStylesComponent {
}

View File

@ -1,35 +1,10 @@
import {
ddescribe,
describe,
xdescribe,
it,
iit,
xit,
expect,
beforeEach,
afterEach,
inject,
beforeEachProviders
} from '@angular/core/testing/testing_internal';
import {LIFECYCLE_HOOKS_VALUES} from '@angular/core/src/metadata/lifecycle_hooks';
import {afterEach, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {IS_DART, stringify} from '../src/facade/lang';
import {CompileMetadataResolver} from '../src/metadata_resolver';
import {LIFECYCLE_HOOKS_VALUES} from '@angular/core/src/metadata/lifecycle_hooks';
import {
Component,
Directive,
ViewEncapsulation,
ChangeDetectionStrategy,
OnChanges,
OnInit,
DoCheck,
OnDestroy,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked,
SimpleChanges,
} from '@angular/core';
import {Component, Directive, ViewEncapsulation, ChangeDetectionStrategy, OnChanges, OnInit, DoCheck, OnDestroy, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, SimpleChanges,} from '@angular/core';
import {TEST_PROVIDERS} from './test_bindings';
import {PLATFORM_DIRECTIVES} from '@angular/core/src/platform_directives_and_pipes';
@ -96,7 +71,7 @@ export function main() {
.toContain(resolver.getDirectiveMetadata(SomeDirective));
}));
describe("platform directives", () => {
describe('platform directives', () => {
beforeEachProviders(
() => [{provide: PLATFORM_DIRECTIVES, useValue: [ADirective], multi: true}]);

View File

@ -1,11 +1,13 @@
// ATTENTION: This file will be overwritten with generated code by main()
import {print, IS_DART} from '../src/facade/lang';
import {TypeScriptEmitter} from '@angular/compiler/src/output/ts_emitter';
import {DartEmitter} from '@angular/compiler/src/output/dart_emitter';
import {DartImportGenerator} from '@angular/compiler/src/output/dart_imports';
import * as o from '@angular/compiler/src/output/output_ast';
import {compileComp, compAMetadata} from './offline_compiler_util';
import {TypeScriptEmitter} from '@angular/compiler/src/output/ts_emitter';
import {ComponentFactory} from '@angular/core/src/linker/component_factory';
import {IS_DART, print} from '../src/facade/lang';
import {compAMetadata, compileComp} from './offline_compiler_util';
import {CompA, SimpleJsImportGenerator} from './offline_compiler_util';
export const CompANgFactory: ComponentFactory<CompA> = null;

View File

@ -1,8 +1,10 @@
// ATTENTION: This file will be overwritten with generated code by main()
import {print} from '../src/facade/lang';
import {JavaScriptEmitter} from '@angular/compiler/src/output/js_emitter';
import {compileComp, compAMetadata} from './offline_compiler_util';
import {ComponentFactory} from '@angular/core/src/linker/component_factory';
import {print} from '../src/facade/lang';
import {compAMetadata, compileComp} from './offline_compiler_util';
import {CompA, SimpleJsImportGenerator} from './offline_compiler_util';
export const CompANgFactory: ComponentFactory<CompA> = null;

View File

@ -1,16 +1,4 @@
import {
ddescribe,
describe,
xdescribe,
it,
iit,
xit,
expect,
beforeEach,
afterEach,
inject,
beforeEachProviders,
} from '@angular/core/testing/testing_internal';
import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, inject, beforeEachProviders,} from '@angular/core/testing/testing_internal';
import {IS_DART} from '../src/facade/lang';
import {Injector} from '@angular/core';
@ -43,10 +31,12 @@ export function main() {
var injector: Injector;
var sharedStylesHost: SharedStylesHost;
beforeEach(inject([Injector, SharedStylesHost], (_injector: Injector, _sharedStylesHost: SharedStylesHost) => {
injector = _injector;
sharedStylesHost = _sharedStylesHost;
}));
beforeEach(inject(
[Injector, SharedStylesHost],
(_injector: Injector, _sharedStylesHost: SharedStylesHost) => {
injector = _injector;
sharedStylesHost = _sharedStylesHost;
}));
fixtures.forEach((fixture) => {
describe(`${fixture.name}`, () => {

View File

@ -1,31 +1,22 @@
import {print, isPresent, IS_DART} from '../src/facade/lang';
import {OutputEmitter} from '@angular/compiler/src/output/abstract_emitter';
import {Console} from '../core_private';
import {
OfflineCompiler,
NormalizedComponentWithViewDirectives,
SourceModule
} from '@angular/compiler/src/offline_compiler';
import {TemplateParser} from '@angular/compiler/src/template_parser';
import {Parser} from '@angular/compiler/src/expression_parser/parser';
import {Lexer} from '@angular/compiler/src/expression_parser/lexer';
import {HtmlParser} from '@angular/compiler/src/html_parser';
import {StyleCompiler} from '@angular/compiler/src/style_compiler';
import {ViewCompiler} from '@angular/compiler/src/view_compiler/view_compiler';
import {DirectiveNormalizer} from '@angular/compiler/src/directive_normalizer';
import {CompileDirectiveMetadata, CompileTemplateMetadata, CompileTypeMetadata} from '@angular/compiler/src/compile_metadata';
import {CompilerConfig} from '@angular/compiler/src/config';
import {createOfflineCompileUrlResolver} from '@angular/compiler/src/url_resolver';
import {MockSchemaRegistry} from '../testing/schema_registry_mock';
import {MODULE_SUFFIX} from '@angular/compiler/src/util';
import {MockXHR} from '../testing/xhr_mock';
import {DirectiveNormalizer} from '@angular/compiler/src/directive_normalizer';
import {Lexer} from '@angular/compiler/src/expression_parser/lexer';
import {Parser} from '@angular/compiler/src/expression_parser/parser';
import {HtmlParser} from '@angular/compiler/src/html_parser';
import {NormalizedComponentWithViewDirectives, OfflineCompiler, SourceModule} from '@angular/compiler/src/offline_compiler';
import {OutputEmitter} from '@angular/compiler/src/output/abstract_emitter';
import {ImportGenerator} from '@angular/compiler/src/output/path_util';
import {StyleCompiler} from '@angular/compiler/src/style_compiler';
import {TemplateParser} from '@angular/compiler/src/template_parser';
import {createOfflineCompileUrlResolver} from '@angular/compiler/src/url_resolver';
import {MODULE_SUFFIX} from '@angular/compiler/src/util';
import {ViewCompiler} from '@angular/compiler/src/view_compiler/view_compiler';
import {
CompileDirectiveMetadata,
CompileTypeMetadata,
CompileTemplateMetadata
} from '@angular/compiler/src/compile_metadata';
import {Console} from '../core_private';
import {IS_DART, isPresent, print} from '../src/facade/lang';
import {MockSchemaRegistry} from '../testing/schema_registry_mock';
import {MockXHR} from '../testing/xhr_mock';
export class CompA { user: string; }
@ -50,16 +41,18 @@ function _createOfflineCompiler(xhr: MockXHR, emitter: OutputEmitter): OfflineCo
xhr.when(`${THIS_MODULE_PATH}/offline_compiler_compa.html`, 'Hello World {{user}}!');
var htmlParser = new HtmlParser();
var config = new CompilerConfig(true, true, true);
var normalizer = new DirectiveNormalizer(xhr, urlResolver, htmlParser, new CompilerConfig(true, true, true));
var normalizer =
new DirectiveNormalizer(xhr, urlResolver, htmlParser, new CompilerConfig(true, true, true));
return new OfflineCompiler(
normalizer, new TemplateParser(new Parser(new Lexer()), new MockSchemaRegistry({}, {}),
htmlParser, new Console(), []),
normalizer,
new TemplateParser(
new Parser(new Lexer()), new MockSchemaRegistry({}, {}), htmlParser, new Console(), []),
new StyleCompiler(urlResolver), new ViewCompiler(new CompilerConfig(true, true, true)),
emitter, xhr);
}
export function compileComp(emitter: OutputEmitter,
comp: CompileDirectiveMetadata): Promise<string> {
export function compileComp(
emitter: OutputEmitter, comp: CompileDirectiveMetadata): Promise<string> {
var xhr = new MockXHR();
var compiler = _createOfflineCompiler(xhr, emitter);
var result = compiler.normalizeDirectiveMetadata(comp).then((normComp) => {

View File

@ -1,13 +1,4 @@
import {
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {escapeSingleQuoteString} from '@angular/compiler/src/output/abstract_emitter';

View File

@ -1,13 +1,4 @@
import {
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {isBlank} from '../../src/facade/lang';
import {DartEmitter} from '@angular/compiler/src/output/dart_emitter';
@ -52,8 +43,9 @@ export function main() {
expect(emitStmt(someVar.set(o.literal(1)).toDeclStmt())).toEqual(`var someVar = 1;`);
expect(emitStmt(someVar.set(o.literal(1)).toDeclStmt(null, [o.StmtModifier.Final])))
.toEqual(`final someVar = 1;`);
expect(emitStmt(someVar.set(o.literal(1, new o.BuiltinType(o.BuiltinTypeName.Int,
[o.TypeModifier.Const])))
expect(emitStmt(someVar
.set(o.literal(
1, new o.BuiltinType(o.BuiltinTypeName.Int, [o.TypeModifier.Const])))
.toDeclStmt(null, [o.StmtModifier.Final])))
.toEqual(`const int someVar = 1;`);
expect(emitStmt(someVar.set(o.literal(1)).toDeclStmt(), ['someVar']))
@ -123,8 +115,9 @@ export function main() {
it('should support external identifiers', () => {
expect(emitStmt(o.importExpr(sameModuleIdentifier).toStmt())).toEqual('someLocalId;');
expect(emitStmt(o.importExpr(externalModuleIdentifier).toStmt()))
.toEqual([`import 'someOtherPath' as import0;`, `import0.someExternalId;`].join('\n'));
expect(emitStmt(o.importExpr(externalModuleIdentifier).toStmt())).toEqual([
`import 'someOtherPath' as import0;`, `import0.someExternalId;`
].join('\n'));
});
it('should support operators', () => {
@ -155,40 +148,42 @@ export function main() {
it('should support function expressions', () => {
expect(emitStmt(o.fn([], []).toStmt())).toEqual(['() {', '};'].join('\n'));
expect(emitStmt(o.fn([new o.FnParam('param1', o.INT_TYPE)], []).toStmt()))
.toEqual(['(int param1) {', '};'].join('\n'));
expect(emitStmt(o.fn([new o.FnParam('param1', o.INT_TYPE)], []).toStmt())).toEqual([
'(int param1) {', '};'
].join('\n'));
});
it('should support function statements', () => {
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [], [])))
.toEqual(['void someFn() {', '}'].join('\n'));
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [], [new o.ReturnStatement(o.literal(1))],
o.INT_TYPE)))
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [], [
]))).toEqual(['void someFn() {', '}'].join('\n'));
expect(emitStmt(new o.DeclareFunctionStmt(
'someFn', [], [new o.ReturnStatement(o.literal(1))], o.INT_TYPE)))
.toEqual(['int someFn() {', ' return 1;', '}'].join('\n'));
expect(
emitStmt(new o.DeclareFunctionStmt('someFn', [new o.FnParam('param1', o.INT_TYPE)], [])))
.toEqual(['void someFn(int param1) {', '}'].join('\n'));
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [new o.FnParam('param1', o.INT_TYPE)], [
]))).toEqual(['void someFn(int param1) {', '}'].join('\n'));
});
it('should support comments',
() => { expect(emitStmt(new o.CommentStmt('a\nb'))).toEqual(['// a', '// b'].join('\n')); });
it('should support comments', () => {
expect(emitStmt(new o.CommentStmt('a\nb'))).toEqual(['// a', '// b'].join('\n'));
});
it('should support if stmt', () => {
var trueCase = o.variable('trueCase').callFn([]).toStmt();
var falseCase = o.variable('falseCase').callFn([]).toStmt();
expect(emitStmt(new o.IfStmt(o.variable('cond'), [trueCase])))
.toEqual(['if (cond) { trueCase(); }'].join('\n'));
expect(emitStmt(new o.IfStmt(o.variable('cond'), [trueCase], [falseCase])))
.toEqual(['if (cond) {', ' trueCase();', '} else {', ' falseCase();', '}'].join('\n'));
expect(emitStmt(new o.IfStmt(o.variable('cond'), [trueCase]))).toEqual([
'if (cond) { trueCase(); }'
].join('\n'));
expect(emitStmt(new o.IfStmt(o.variable('cond'), [trueCase], [falseCase]))).toEqual([
'if (cond) {', ' trueCase();', '} else {', ' falseCase();', '}'
].join('\n'));
});
it('should support try/catch', () => {
var bodyStmt = o.variable('body').callFn([]).toStmt();
var catchStmt = o.variable('catchFn').callFn([o.CATCH_ERROR_VAR, o.CATCH_STACK_VAR]).toStmt();
expect(emitStmt(new o.TryCatchStmt([bodyStmt], [catchStmt])))
.toEqual(
['try {', ' body();', '} catch (error, stack) {', ' catchFn(error,stack);', '}']
.join('\n'));
expect(emitStmt(new o.TryCatchStmt([bodyStmt], [catchStmt]))).toEqual([
'try {', ' body();', '} catch (error, stack) {', ' catchFn(error,stack);', '}'
].join('\n'));
});
it('should support support throwing',
@ -200,11 +195,10 @@ export function main() {
beforeEach(() => { callSomeMethod = o.THIS_EXPR.callMethod('someMethod', []).toStmt(); });
it('should support declaring classes', () => {
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, [])))
.toEqual(['class SomeClass {', '}'].join('\n'));
expect(
emitStmt(new o.ClassStmt('SomeClass', o.variable('SomeSuperClass'), [], [], null, [])))
.toEqual(['class SomeClass extends SomeSuperClass {', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, [
]))).toEqual(['class SomeClass {', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', o.variable('SomeSuperClass'), [], [], null, [
]))).toEqual(['class SomeClass extends SomeSuperClass {', '}'].join('\n'));
});
it('should support declaring constructors', () => {
@ -216,23 +210,23 @@ export function main() {
'SomeClass', null, [], [],
new o.ClassMethod(null, [new o.FnParam('someParam', o.INT_TYPE)], []), [])))
.toEqual(['class SomeClass {', ' SomeClass(int someParam) {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [],
new o.ClassMethod(null, [], [superCall]), [])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], new o.ClassMethod(null, [], [superCall]), [])))
.toEqual(
['class SomeClass {', ' SomeClass(): super(someParam) {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [],
new o.ClassMethod(null, [], [callSomeMethod]), [])))
.toEqual(
['class SomeClass {', ' SomeClass() {', ' this.someMethod();', ' }', '}'].join(
'\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], new o.ClassMethod(null, [], [callSomeMethod]), [])))
.toEqual([
'class SomeClass {', ' SomeClass() {', ' this.someMethod();', ' }', '}'
].join('\n'));
});
it('should support declaring fields', () => {
expect(emitStmt(new o.ClassStmt('SomeClass', null, [new o.ClassField('someField')], [],
null, [])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [new o.ClassField('someField')], [], null, [])))
.toEqual(['class SomeClass {', ' var someField;', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null,
[new o.ClassField('someField', o.INT_TYPE)], [], null, [])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [new o.ClassField('someField', o.INT_TYPE)], [], null, [])))
.toEqual(['class SomeClass {', ' int someField;', '}'].join('\n'));
expect(
emitStmt(new o.ClassStmt(
@ -242,39 +236,40 @@ export function main() {
});
it('should support declaring getters', () => {
expect(emitStmt(new o.ClassStmt('SomeClass', null, [],
[new o.ClassGetter('someGetter', [])], null, [])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [new o.ClassGetter('someGetter', [])], null, [])))
.toEqual(['class SomeClass {', ' get someGetter {', ' }', '}'].join('\n'));
expect(
emitStmt(new o.ClassStmt('SomeClass', null, [],
[new o.ClassGetter('someGetter', [], o.INT_TYPE)], null, [])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [new o.ClassGetter('someGetter', [], o.INT_TYPE)], null,
[])))
.toEqual(['class SomeClass {', ' int get someGetter {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [],
[new o.ClassGetter('someGetter', [callSomeMethod])], null,
[])))
.toEqual(
['class SomeClass {', ' get someGetter {', ' this.someMethod();', ' }', '}']
.join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [new o.ClassGetter('someGetter', [callSomeMethod])], null,
[])))
.toEqual([
'class SomeClass {', ' get someGetter {', ' this.someMethod();', ' }', '}'
].join('\n'));
});
it('should support methods', () => {
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null,
[new o.ClassMethod('someMethod', [], [])])))
.toEqual(['class SomeClass {', ' void someMethod() {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null,
[new o.ClassMethod('someMethod', [], [], o.INT_TYPE)])))
.toEqual(['class SomeClass {', ' int someMethod() {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, [
new o.ClassMethod('someMethod', [], [])
]))).toEqual(['class SomeClass {', ' void someMethod() {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, [
new o.ClassMethod('someMethod', [], [], o.INT_TYPE)
]))).toEqual(['class SomeClass {', ' int someMethod() {', ' }', '}'].join('\n'));
expect(
emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], null,
[new o.ClassMethod('someMethod', [new o.FnParam('someParam', o.INT_TYPE)], [])])))
.toEqual(
['class SomeClass {', ' void someMethod(int someParam) {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null,
[new o.ClassMethod('someMethod', [], [callSomeMethod])])))
.toEqual(
['class SomeClass {', ' void someMethod() {', ' this.someMethod();', ' }', '}']
.join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], null,
[new o.ClassMethod('someMethod', [], [callSomeMethod])])))
.toEqual([
'class SomeClass {', ' void someMethod() {', ' this.someMethod();', ' }', '}'
].join('\n'));
});
});
@ -292,9 +287,9 @@ export function main() {
var writeVarExpr = o.variable('a').set(o.NULL_EXPR);
expect(emitStmt(writeVarExpr.toDeclStmt(o.importType(sameModuleIdentifier))))
.toEqual('someLocalId a = null;');
expect(emitStmt(writeVarExpr.toDeclStmt(o.importType(externalModuleIdentifier))))
.toEqual([`import 'someOtherPath' as import0;`, `import0.someExternalId a = null;`].join(
'\n'));
expect(emitStmt(writeVarExpr.toDeclStmt(o.importType(externalModuleIdentifier)))).toEqual([
`import 'someOtherPath' as import0;`, `import0.someExternalId a = null;`
].join('\n'));
});
it('should support combined types', () => {

View File

@ -1,13 +1,4 @@
import {
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {DartImportGenerator} from '@angular/compiler/src/output/dart_imports';
@ -31,8 +22,8 @@ export function main() {
expect(
generator.getImportPath('asset:somePkg/lib/dir1/modPath', 'asset:somePkg/lib/impPath'))
.toEqual('../impPath');
expect(generator.getImportPath('asset:somePkg/lib/dir1/modPath',
'asset:somePkg/lib/dir2/impPath'))
expect(generator.getImportPath(
'asset:somePkg/lib/dir1/modPath', 'asset:somePkg/lib/dir2/impPath'))
.toEqual('../dir2/impPath');
});
@ -43,8 +34,9 @@ export function main() {
});
it('should not allow absolute imports of non lib modules', () => {
expect(() => generator.getImportPath('asset:somePkg/lib/modPath',
'asset:somePkg/test/impPath'))
expect(
() =>
generator.getImportPath('asset:somePkg/lib/modPath', 'asset:somePkg/test/impPath'))
.toThrowError(
`Can't import url asset:somePkg/test/impPath from asset:somePkg/lib/modPath`);
});

View File

@ -1,13 +1,4 @@
import {
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {isBlank} from '../../src/facade/lang';
import {JavaScriptEmitter} from '@angular/compiler/src/output/js_emitter';
@ -47,11 +38,10 @@ export function main() {
it('should declare variables', () => {
expect(emitStmt(someVar.set(o.literal(1)).toDeclStmt())).toEqual(`var someVar = 1;`);
expect(emitStmt(someVar.set(o.literal(1)).toDeclStmt(), ['someVar']))
.toEqual([
'var someVar = 1;',
`Object.defineProperty(exports, 'someVar', { get: function() { return someVar; }});`
].join('\n'));
expect(emitStmt(someVar.set(o.literal(1)).toDeclStmt(), ['someVar'])).toEqual([
'var someVar = 1;',
`Object.defineProperty(exports, 'someVar', { get: function() { return someVar; }});`
].join('\n'));
});
it('should read and write variables', () => {
@ -111,11 +101,11 @@ export function main() {
it('should support external identifiers', () => {
expect(emitStmt(o.importExpr(sameModuleIdentifier).toStmt())).toEqual('someLocalId;');
expect(emitStmt(o.importExpr(externalModuleIdentifier).toStmt()))
.toEqual([
`var import0 = re` + `quire('somePackage/someOtherPath');`,
`import0.someExternalId;`
].join('\n'));
expect(emitStmt(o.importExpr(externalModuleIdentifier).toStmt())).toEqual([
`var import0 = re` +
`quire('somePackage/someOtherPath');`,
`import0.someExternalId;`
].join('\n'));
});
it('should support operators', () => {
@ -145,52 +135,50 @@ export function main() {
it('should support function expressions', () => {
expect(emitStmt(o.fn([], []).toStmt())).toEqual(['function() {', '};'].join('\n'));
expect(emitStmt(o.fn([], [new o.ReturnStatement(o.literal(1))]).toStmt()))
.toEqual(['function() {', ' return 1;\n};'].join('\n'));
expect(emitStmt(o.fn([new o.FnParam('param1')], []).toStmt()))
.toEqual(['function(param1) {', '};'].join('\n'));
expect(emitStmt(o.fn([], [new o.ReturnStatement(o.literal(1))]).toStmt())).toEqual([
'function() {', ' return 1;\n};'
].join('\n'));
expect(emitStmt(o.fn([new o.FnParam('param1')], []).toStmt())).toEqual([
'function(param1) {', '};'
].join('\n'));
});
it('should support function statements', () => {
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [], [])))
.toEqual(['function someFn() {', '}'].join('\n'));
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [], []), ['someFn']))
.toEqual([
'function someFn() {',
'}',
`Object.defineProperty(exports, 'someFn', { get: function() { return someFn; }});`
].join('\n'));
expect(
emitStmt(new o.DeclareFunctionStmt('someFn', [], [new o.ReturnStatement(o.literal(1))])))
.toEqual(['function someFn() {', ' return 1;', '}'].join('\n'));
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [new o.FnParam('param1')], [])))
.toEqual(['function someFn(param1) {', '}'].join('\n'));
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [], [
]))).toEqual(['function someFn() {', '}'].join('\n'));
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [], []), ['someFn'])).toEqual([
'function someFn() {', '}',
`Object.defineProperty(exports, 'someFn', { get: function() { return someFn; }});`
].join('\n'));
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [], [
new o.ReturnStatement(o.literal(1))
]))).toEqual(['function someFn() {', ' return 1;', '}'].join('\n'));
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [new o.FnParam('param1')], [
]))).toEqual(['function someFn(param1) {', '}'].join('\n'));
});
it('should support comments',
() => { expect(emitStmt(new o.CommentStmt('a\nb'))).toEqual(['// a', '// b'].join('\n')); });
it('should support comments', () => {
expect(emitStmt(new o.CommentStmt('a\nb'))).toEqual(['// a', '// b'].join('\n'));
});
it('should support if stmt', () => {
var trueCase = o.variable('trueCase').callFn([]).toStmt();
var falseCase = o.variable('falseCase').callFn([]).toStmt();
expect(emitStmt(new o.IfStmt(o.variable('cond'), [trueCase])))
.toEqual(['if (cond) { trueCase(); }'].join('\n'));
expect(emitStmt(new o.IfStmt(o.variable('cond'), [trueCase], [falseCase])))
.toEqual(['if (cond) {', ' trueCase();', '} else {', ' falseCase();', '}'].join('\n'));
expect(emitStmt(new o.IfStmt(o.variable('cond'), [trueCase]))).toEqual([
'if (cond) { trueCase(); }'
].join('\n'));
expect(emitStmt(new o.IfStmt(o.variable('cond'), [trueCase], [falseCase]))).toEqual([
'if (cond) {', ' trueCase();', '} else {', ' falseCase();', '}'
].join('\n'));
});
it('should support try/catch', () => {
var bodyStmt = o.variable('body').callFn([]).toStmt();
var catchStmt = o.variable('catchFn').callFn([o.CATCH_ERROR_VAR, o.CATCH_STACK_VAR]).toStmt();
expect(emitStmt(new o.TryCatchStmt([bodyStmt], [catchStmt])))
.toEqual([
'try {',
' body();',
'} catch (error) {',
' var stack = error.stack;',
' catchFn(error,stack);',
'}'
].join('\n'));
expect(emitStmt(new o.TryCatchStmt([bodyStmt], [catchStmt]))).toEqual([
'try {', ' body();', '} catch (error) {', ' var stack = error.stack;',
' catchFn(error,stack);', '}'
].join('\n'));
});
it('should support support throwing',
@ -202,19 +190,17 @@ export function main() {
beforeEach(() => { callSomeMethod = o.THIS_EXPR.callMethod('someMethod', []).toStmt(); });
it('should support declaring classes', () => {
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, [])))
.toEqual(['function SomeClass() {', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, [
]))).toEqual(['function SomeClass() {', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, []), ['SomeClass']))
.toEqual([
'function SomeClass() {',
'}',
'function SomeClass() {', '}',
`Object.defineProperty(exports, 'SomeClass', { get: function() { return SomeClass; }});`
].join('\n'));
expect(
emitStmt(new o.ClassStmt('SomeClass', o.variable('SomeSuperClass'), [], [], null, [])))
.toEqual([
'function SomeClass() {',
'}',
'function SomeClass() {', '}',
'SomeClass.prototype = Object.create(SomeSuperClass.prototype);'
].join('\n'));
});
@ -224,75 +210,61 @@ export function main() {
expect(emitStmt(
new o.ClassStmt('SomeClass', null, [], [], new o.ClassMethod(null, [], []), [])))
.toEqual(['function SomeClass() {', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [],
new o.ClassMethod(null, [new o.FnParam('someParam')], []),
[])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [],
new o.ClassMethod(null, [new o.FnParam('someParam')], []), [])))
.toEqual(['function SomeClass(someParam) {', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', o.variable('SomeSuperClass'), [], [],
new o.ClassMethod(null, [], [superCall]), [])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', o.variable('SomeSuperClass'), [], [],
new o.ClassMethod(null, [], [superCall]), [])))
.toEqual([
'function SomeClass() {',
' var self = this;',
' SomeSuperClass.call(this, someParam);',
'}',
'function SomeClass() {', ' var self = this;',
' SomeSuperClass.call(this, someParam);', '}',
'SomeClass.prototype = Object.create(SomeSuperClass.prototype);'
].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [],
new o.ClassMethod(null, [], [callSomeMethod]), [])))
.toEqual(
['function SomeClass() {', ' var self = this;', ' self.someMethod();', '}'].join(
'\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], new o.ClassMethod(null, [], [callSomeMethod]), [])))
.toEqual([
'function SomeClass() {', ' var self = this;', ' self.someMethod();', '}'
].join('\n'));
});
it('should support declaring getters', () => {
expect(emitStmt(new o.ClassStmt('SomeClass', null, [],
[new o.ClassGetter('someGetter', [])], null, [])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [new o.ClassGetter('someGetter', [])], null, [])))
.toEqual([
'function SomeClass() {',
'}',
`Object.defineProperty(SomeClass.prototype, 'someGetter', { get: function() {`,
`}});`
'function SomeClass() {', '}',
`Object.defineProperty(SomeClass.prototype, 'someGetter', { get: function() {`, `}});`
].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [],
[new o.ClassGetter('someGetter', [callSomeMethod])], null,
[])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [new o.ClassGetter('someGetter', [callSomeMethod])], null,
[])))
.toEqual([
'function SomeClass() {',
'}',
'function SomeClass() {', '}',
`Object.defineProperty(SomeClass.prototype, 'someGetter', { get: function() {`,
` var self = this;`,
` self.someMethod();`,
`}});`
` var self = this;`, ` self.someMethod();`, `}});`
].join('\n'));
});
it('should support methods', () => {
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null,
[new o.ClassMethod('someMethod', [], [])])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], null, [new o.ClassMethod('someMethod', [], [])])))
.toEqual([
'function SomeClass() {',
'}',
'SomeClass.prototype.someMethod = function() {',
'};'
'function SomeClass() {', '}', 'SomeClass.prototype.someMethod = function() {', '};'
].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], null,
[new o.ClassMethod('someMethod', [new o.FnParam('someParam')], [])])))
.toEqual([
'function SomeClass() {',
'}',
'SomeClass.prototype.someMethod = function(someParam) {',
'};'
'function SomeClass() {', '}',
'SomeClass.prototype.someMethod = function(someParam) {', '};'
].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null,
[new o.ClassMethod('someMethod', [], [callSomeMethod])])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], null,
[new o.ClassMethod('someMethod', [], [callSomeMethod])])))
.toEqual([
'function SomeClass() {',
'}',
'SomeClass.prototype.someMethod = function() {',
' var self = this;',
' self.someMethod();',
'};'
'function SomeClass() {', '}', 'SomeClass.prototype.someMethod = function() {',
' var self = this;', ' self.someMethod();', '};'
].join('\n'));
});
});

View File

@ -1,14 +1,16 @@
// ATTENTION: This file will be overwritten with generated code by main()
import {print, IS_DART} from '../../src/facade/lang';
import {unimplemented} from '../../src/facade/exceptions';
import {codegenExportsVars, codegenStmts} from './output_emitter_util';
import {TypeScriptEmitter} from '@angular/compiler/src/output/ts_emitter';
import {DartEmitter} from '@angular/compiler/src/output/dart_emitter';
import {DartImportGenerator} from '@angular/compiler/src/output/dart_imports';
import * as o from '@angular/compiler/src/output/output_ast';
import {TypeScriptEmitter} from '@angular/compiler/src/output/ts_emitter';
import {unimplemented} from '../../src/facade/exceptions';
import {IS_DART, print} from '../../src/facade/lang';
import {assetUrl} from '../../src/util';
import {SimpleJsImportGenerator} from '../offline_compiler_util';
import {codegenExportsVars, codegenStmts} from './output_emitter_util';
export function getExpressions(): any {
return unimplemented();
}
@ -17,9 +19,9 @@ export function getExpressions(): any {
export function emit() {
var emitter = IS_DART ? new DartEmitter(new DartImportGenerator()) :
new TypeScriptEmitter(new SimpleJsImportGenerator());
var emittedCode =
emitter.emitStatements(assetUrl('compiler', 'output/output_emitter_codegen_typed', 'test'),
codegenStmts, codegenExportsVars);
var emittedCode = emitter.emitStatements(
assetUrl('compiler', 'output/output_emitter_codegen_typed', 'test'), codegenStmts,
codegenExportsVars);
return emittedCode;
}

View File

@ -1,11 +1,13 @@
// ATTENTION: This file will be overwritten with generated code by main()
import {print} from '../../src/facade/lang';
import {unimplemented} from '../../src/facade/exceptions';
import {codegenExportsVars, codegenStmts} from './output_emitter_util';
import {JavaScriptEmitter} from '@angular/compiler/src/output/js_emitter';
import {unimplemented} from '../../src/facade/exceptions';
import {print} from '../../src/facade/lang';
import {assetUrl} from '../../src/util';
import {SimpleJsImportGenerator} from '../offline_compiler_util';
import {codegenExportsVars, codegenStmts} from './output_emitter_util';
export function getExpressions(): any {
return unimplemented();
}
@ -13,9 +15,9 @@ export function getExpressions(): any {
// Generator
export function emit() {
var emitter = new JavaScriptEmitter(new SimpleJsImportGenerator());
var emittedCode =
emitter.emitStatements(assetUrl('compiler', 'output/output_emitter_codegen_untyped', 'test'),
codegenStmts, codegenExportsVars);
var emittedCode = emitter.emitStatements(
assetUrl('compiler', 'output/output_emitter_codegen_untyped', 'test'), codegenStmts,
codegenExportsVars);
return emittedCode;
}

View File

@ -1,13 +1,4 @@
import {
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {IS_DART} from '../../src/facade/lang';
@ -20,23 +11,18 @@ import {EventEmitter} from '@angular/core';
import {ViewType} from '@angular/core/src/linker/view_type';
import {BaseException} from '@angular/core';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {
browserDetection
} from '@angular/platform-browser/testing'
import {browserDetection} from '@angular/platform-browser/testing'
export function
main() {
var outputDefs: any[] /** TODO #9100 */ = [];
outputDefs.push({
'getExpressions': () => interpretStatements(codegenStmts, 'getExpressions',
new DynamicClassInstanceFactory()),
export function main() {
var outputDefs: any[] /** TODO #9100 */ = []; outputDefs.push({
'getExpressions': () => interpretStatements(
codegenStmts, 'getExpressions', new DynamicClassInstanceFactory()),
'name': 'interpreted'
});
if (IS_DART || !getDOM().supportsDOMEvents()) {
// Our generator only works on node.js and Dart...
outputDefs.push({'getExpressions': () => typed.getExpressions, 'name': 'typed'});
}
if (!IS_DART) {
} if (!IS_DART) {
// Our generator only works on node.js and Dart...
if (!getDOM().supportsDOMEvents()) {
outputDefs.push({'getExpressions': () => untyped.getExpressions, 'name': 'untyped'});
@ -47,155 +33,166 @@ import {
});
}
describe('output emitter', () => {
outputDefs.forEach((outputDef) => {
describe(`${outputDef['name']}`, () => {
var expressions: any /** TODO #9100 */;
beforeEach(() => { expressions = outputDef['getExpressions']()(); });
describe(
'output emitter',
() => {
outputDefs.forEach((outputDef) => {
describe(`${outputDef['name']}`, () => {
var expressions: any /** TODO #9100 */;
beforeEach(() => { expressions = outputDef['getExpressions']()(); });
it('should support literals', () => {
expect(expressions['stringLiteral']).toEqual('Hello World!');
expect(expressions['intLiteral']).toEqual(42);
expect(expressions['boolLiteral']).toEqual(true);
expect(expressions['arrayLiteral']).toEqual([0]);
expect(expressions['mapLiteral']).toEqual({'key0': 0});
});
it('should support literals', () => {
expect(expressions['stringLiteral']).toEqual('Hello World!');
expect(expressions['intLiteral']).toEqual(42);
expect(expressions['boolLiteral']).toEqual(true);
expect(expressions['arrayLiteral']).toEqual([0]);
expect(expressions['mapLiteral']).toEqual({'key0': 0});
});
it('should support reading vars/keys/props', () => {
expect(expressions['readVar']).toEqual('someValue');
expect(expressions['readKey']).toEqual('someValue');
expect(expressions['readPropExternalInstance']).toEqual('someValue');
expect(expressions['readPropDynamicInstance']).toEqual('dynamicValue');
expect(expressions['readGetterDynamicInstance'])
.toEqual({'data': 'someValue', 'dynamicProp': 'dynamicValue'});
});
it('should support reading vars/keys/props', () => {
expect(expressions['readVar']).toEqual('someValue');
expect(expressions['readKey']).toEqual('someValue');
expect(expressions['readPropExternalInstance']).toEqual('someValue');
expect(expressions['readPropDynamicInstance']).toEqual('dynamicValue');
expect(expressions['readGetterDynamicInstance'])
.toEqual({'data': 'someValue', 'dynamicProp': 'dynamicValue'});
});
it('should support writing to vars / keys / props', () => {
expect(expressions['changedVar']).toEqual('changedValue');
expect(expressions['changedKey']).toEqual('changedValue');
expect(expressions['changedPropExternalInstance']).toEqual('changedValue');
expect(expressions['changedPropDynamicInstance']).toEqual('changedValue');
});
it('should support writing to vars / keys / props', () => {
expect(expressions['changedVar']).toEqual('changedValue');
expect(expressions['changedKey']).toEqual('changedValue');
expect(expressions['changedPropExternalInstance']).toEqual('changedValue');
expect(expressions['changedPropDynamicInstance']).toEqual('changedValue');
});
it('should support declaring functions with parameters and return', () => {
expect(expressions['fn']('someParam')).toEqual({'param': 'someParam'});
expect(expressions['closureInDynamicInstance']('someParam'))
.toEqual({'param': 'someParam', 'data': 'someValue', 'dynamicProp': 'dynamicValue'});
});
it('should support declaring functions with parameters and return', () => {
expect(expressions['fn']('someParam')).toEqual({'param': 'someParam'});
expect(expressions['closureInDynamicInstance']('someParam')).toEqual({
'param': 'someParam',
'data': 'someValue',
'dynamicProp': 'dynamicValue'
});
});
it('should support invoking functions and methods', () => {
expect(expressions['invokeFn']).toEqual({'param': 'someParam'});
expect(expressions['concatedArray']).toEqual([0, 1]);
expect(expressions['invokeMethodExternalInstance'])
.toEqual({'data': 'someValue', 'param': 'someParam'});
expect(expressions['invokeMethodExternalInstanceViaBind'])
.toEqual({'data': 'someValue', 'param': 'someParam'});
expect(expressions['invokeMethodDynamicInstance'])
.toEqual({'data': 'someValue', 'dynamicProp': 'dynamicValue', 'param': 'someParam'});
expect(expressions['invokeMethodDynamicInstanceViaBind'])
.toEqual({'data': 'someValue', 'dynamicProp': 'dynamicValue', 'param': 'someParam'});
});
it('should support invoking functions and methods', () => {
expect(expressions['invokeFn']).toEqual({'param': 'someParam'});
expect(expressions['concatedArray']).toEqual([0, 1]);
expect(expressions['invokeMethodExternalInstance'])
.toEqual({'data': 'someValue', 'param': 'someParam'});
expect(expressions['invokeMethodExternalInstanceViaBind'])
.toEqual({'data': 'someValue', 'param': 'someParam'});
expect(expressions['invokeMethodDynamicInstance']).toEqual({
'data': 'someValue',
'dynamicProp': 'dynamicValue',
'param': 'someParam'
});
expect(expressions['invokeMethodDynamicInstanceViaBind']).toEqual({
'data': 'someValue',
'dynamicProp': 'dynamicValue',
'param': 'someParam'
});
});
it('should support conditionals', () => {
expect(expressions['conditionalTrue']).toEqual('true');
expect(expressions['conditionalFalse']).toEqual('false');
});
it('should support conditionals', () => {
expect(expressions['conditionalTrue']).toEqual('true');
expect(expressions['conditionalFalse']).toEqual('false');
});
it('should support not', () => { expect(expressions['not']).toEqual(true); });
it('should support not', () => { expect(expressions['not']).toEqual(true); });
it('should support reading external identifiers', () => {
expect(expressions['externalTestIdentifier']).toBe(ExternalClass);
expect(expressions['externalSrcIdentifier']).toBe(EventEmitter);
expect(expressions['externalEnumIdentifier']).toBe(ViewType.HOST);
});
it('should support reading external identifiers', () => {
expect(expressions['externalTestIdentifier']).toBe(ExternalClass);
expect(expressions['externalSrcIdentifier']).toBe(EventEmitter);
expect(expressions['externalEnumIdentifier']).toBe(ViewType.HOST);
});
it('should support instantiating classes', () => {
expect(expressions['externalInstance']).toBeAnInstanceOf(ExternalClass);
// Note: toBeAnInstanceOf does not check super classes in Dart...
expect(expressions['dynamicInstance'] instanceof ExternalClass).toBe(true);
});
it('should support instantiating classes', () => {
expect(expressions['externalInstance']).toBeAnInstanceOf(ExternalClass);
// Note: toBeAnInstanceOf does not check super classes in Dart...
expect(expressions['dynamicInstance'] instanceof ExternalClass).toBe(true);
});
describe('operators', () => {
var ops: any /** TODO #9100 */;
var aObj: any /** TODO #9100 */, bObj: any /** TODO #9100 */;
beforeEach(() => {
ops = expressions['operators'];
aObj = new Object();
bObj = new Object();
describe('operators', () => {
var ops: any /** TODO #9100 */;
var aObj: any /** TODO #9100 */, bObj: any /** TODO #9100 */;
beforeEach(() => {
ops = expressions['operators'];
aObj = new Object();
bObj = new Object();
});
it('should support ==', () => {
expect(ops['=='](aObj, aObj)).toBe(true);
expect(ops['=='](aObj, bObj)).toBe(false);
expect(ops['=='](1, 1)).toBe(true);
expect(ops['=='](0, 1)).toBe(false);
expect(ops['==']('a', 'a')).toBe(true);
expect(ops['==']('a', 'b')).toBe(false);
});
it('should support !=', () => {
expect(ops['!='](aObj, aObj)).toBe(false);
expect(ops['!='](aObj, bObj)).toBe(true);
expect(ops['!='](1, 1)).toBe(false);
expect(ops['!='](0, 1)).toBe(true);
expect(ops['!=']('a', 'a')).toBe(false);
expect(ops['!=']('a', 'b')).toBe(true);
});
it('should support ===', () => {
expect(ops['==='](aObj, aObj)).toBe(true);
expect(ops['==='](aObj, bObj)).toBe(false);
expect(ops['==='](1, 1)).toBe(true);
expect(ops['==='](0, 1)).toBe(false);
});
it('should support !==', () => {
expect(ops['!=='](aObj, aObj)).toBe(false);
expect(ops['!=='](aObj, bObj)).toBe(true);
expect(ops['!=='](1, 1)).toBe(false);
expect(ops['!=='](0, 1)).toBe(true);
});
it('should support -', () => { expect(ops['-'](3, 2)).toEqual(1); });
it('should support +', () => { expect(ops['+'](1, 2)).toEqual(3); });
it('should support /', () => { expect(ops['/'](6, 2)).toEqual(3); });
it('should support *', () => { expect(ops['*'](2, 3)).toEqual(6); });
it('should support %', () => { expect(ops['%'](3, 2)).toEqual(1); });
it('should support &&', () => {
expect(ops['&&'](true, true)).toBe(true);
expect(ops['&&'](true, false)).toBe(false);
});
it('should support ||', () => {
expect(ops['||'](true, false)).toBe(true);
expect(ops['||'](false, false)).toBe(false);
});
it('should support <', () => {
expect(ops['<'](1, 2)).toBe(true);
expect(ops['<'](1, 1)).toBe(false);
});
it('should support <=', () => {
expect(ops['<='](1, 2)).toBe(true);
expect(ops['<='](1, 1)).toBe(true);
});
it('should support >', () => {
expect(ops['>'](2, 1)).toBe(true);
expect(ops['>'](1, 1)).toBe(false);
});
it('should support >=', () => {
expect(ops['>='](2, 1)).toBe(true);
expect(ops['>='](1, 1)).toBe(true);
});
});
it('should support throwing errors',
() => { expect(expressions['throwError']).toThrowError('someError'); });
it('should support catching errors', () => {
function someOperation() { throw new BaseException('Boom!'); }
var errorAndStack = expressions['catchError'](someOperation);
expect(errorAndStack[0].message).toEqual('Boom!');
// Somehow we don't get stacktraces on ios7...
if (!browserDetection.isIOS7 && !browserDetection.isIE) {
expect(errorAndStack[1].toString()).toContain('someOperation');
}
});
});
it('should support ==', () => {
expect(ops['=='](aObj, aObj)).toBe(true);
expect(ops['=='](aObj, bObj)).toBe(false);
expect(ops['=='](1, 1)).toBe(true);
expect(ops['=='](0, 1)).toBe(false);
expect(ops['==']('a', 'a')).toBe(true);
expect(ops['==']('a', 'b')).toBe(false);
});
it('should support !=', () => {
expect(ops['!='](aObj, aObj)).toBe(false);
expect(ops['!='](aObj, bObj)).toBe(true);
expect(ops['!='](1, 1)).toBe(false);
expect(ops['!='](0, 1)).toBe(true);
expect(ops['!=']('a', 'a')).toBe(false);
expect(ops['!=']('a', 'b')).toBe(true);
});
it('should support ===', () => {
expect(ops['==='](aObj, aObj)).toBe(true);
expect(ops['==='](aObj, bObj)).toBe(false);
expect(ops['==='](1, 1)).toBe(true);
expect(ops['==='](0, 1)).toBe(false);
});
it('should support !==', () => {
expect(ops['!=='](aObj, aObj)).toBe(false);
expect(ops['!=='](aObj, bObj)).toBe(true);
expect(ops['!=='](1, 1)).toBe(false);
expect(ops['!=='](0, 1)).toBe(true);
});
it('should support -', () => { expect(ops['-'](3, 2)).toEqual(1); });
it('should support +', () => { expect(ops['+'](1, 2)).toEqual(3); });
it('should support /', () => { expect(ops['/'](6, 2)).toEqual(3); });
it('should support *', () => { expect(ops['*'](2, 3)).toEqual(6); });
it('should support %', () => { expect(ops['%'](3, 2)).toEqual(1); });
it('should support &&', () => {
expect(ops['&&'](true, true)).toBe(true);
expect(ops['&&'](true, false)).toBe(false);
});
it('should support ||', () => {
expect(ops['||'](true, false)).toBe(true);
expect(ops['||'](false, false)).toBe(false);
});
it('should support <', () => {
expect(ops['<'](1, 2)).toBe(true);
expect(ops['<'](1, 1)).toBe(false);
});
it('should support <=', () => {
expect(ops['<='](1, 2)).toBe(true);
expect(ops['<='](1, 1)).toBe(true);
});
it('should support >', () => {
expect(ops['>'](2, 1)).toBe(true);
expect(ops['>'](1, 1)).toBe(false);
});
it('should support >=', () => {
expect(ops['>='](2, 1)).toBe(true);
expect(ops['>='](1, 1)).toBe(true);
});
});
it('should support throwing errors',
() => { expect(expressions['throwError']).toThrowError('someError'); });
it('should support catching errors', () => {
function someOperation() { throw new BaseException('Boom!'); }
var errorAndStack = expressions['catchError'](someOperation);
expect(errorAndStack[0].message).toEqual('Boom!');
// Somehow we don't get stacktraces on ios7...
if (!browserDetection.isIOS7 && !browserDetection.isIE) {
expect(errorAndStack[1].toString()).toContain('someOperation');
}
});
});
});
});
}

View File

@ -1,11 +1,11 @@
import {CompileIdentifierMetadata} from '@angular/compiler/src/compile_metadata';
import * as o from '@angular/compiler/src/output/output_ast';
import {DynamicInstance, InstanceFactory} from '@angular/compiler/src/output/output_interpreter';
import {assetUrl} from '@angular/compiler/src/util';
import {EventEmitter} from '@angular/core';
import {ViewType} from '@angular/core/src/linker/view_type';
import {BaseException} from '../../src/facade/exceptions';
import {InstanceFactory, DynamicInstance} from '@angular/compiler/src/output/output_interpreter';
import {assetUrl} from '@angular/compiler/src/util';
import * as o from '@angular/compiler/src/output/output_ast';
import {BaseException} from '../../src/facade/exceptions';
export class ExternalClass {
changeable: any;
@ -37,9 +37,7 @@ export var codegenExportsVars = [
var _getExpressionsStmts: o.Statement[] = [
o.variable('readVar')
.set(o.literal('someValue'))
.toDeclStmt(),
o.variable('readVar').set(o.literal('someValue')).toDeclStmt(),
o.variable('changedVar').set(o.literal('initialValue')).toDeclStmt(),
o.variable('changedVar').set(o.literal('changedValue')).toStmt(),
@ -58,34 +56,29 @@ var _getExpressionsStmts: o.Statement[] = [
o.variable('externalInstance').prop('changeable').set(o.literal('changedValue')).toStmt(),
o.variable('fn')
.set(o.fn([new o.FnParam('param')],
[new o.ReturnStatement(o.literalMap([['param', o.variable('param')]]))],
o.DYNAMIC_TYPE))
.set(o.fn(
[new o.FnParam('param')],
[new o.ReturnStatement(o.literalMap([['param', o.variable('param')]]))], o.DYNAMIC_TYPE))
.toDeclStmt(),
o.variable('throwError')
.set(o.fn([],
[
new o.ThrowStmt(o.importExpr(baseExceptionIdentifier)
.instantiate([o.literal('someError')]))
]))
.set(o.fn([], [new o.ThrowStmt(o.importExpr(baseExceptionIdentifier).instantiate([o.literal(
'someError')]))]))
.toDeclStmt(),
o.variable('catchError')
.set(o.fn([new o.FnParam('runCb')],
[
new o.TryCatchStmt([o.variable('runCb').callFn([]).toStmt()],
[
new o.ReturnStatement(
o.literalArr([o.CATCH_ERROR_VAR, o.CATCH_STACK_VAR]))
])
],
o.DYNAMIC_TYPE))
.set(o.fn(
[new o.FnParam('runCb')],
[new o.TryCatchStmt(
[o.variable('runCb').callFn([]).toStmt()],
[new o.ReturnStatement(o.literalArr([o.CATCH_ERROR_VAR, o.CATCH_STACK_VAR]))])],
o.DYNAMIC_TYPE))
.toDeclStmt(),
o.variable('dynamicInstance')
.set(o.variable('DynamicClass')
.instantiate([o.literal('someValue'), o.literal('dynamicValue')]))
.set(o.variable('DynamicClass').instantiate([
o.literal('someValue'), o.literal('dynamicValue')
]))
.toDeclStmt(),
o.variable('dynamicInstance').prop('dynamicChangeable').set(o.literal('changedValue')).toStmt(),
@ -129,9 +122,8 @@ var _getExpressionsStmts: o.Statement[] = [
.callFn([o.literal('someParam')])
],
[
'concatedArray',
o.literalArr([o.literal(0)])
.callMethod(o.BuiltinMethod.ConcatArray, [o.literalArr([o.literal(1)])])
'concatedArray', o.literalArr([o.literal(0)])
.callMethod(o.BuiltinMethod.ConcatArray, [o.literalArr([o.literal(1)])])
],
['fn', o.variable('fn')],
@ -139,18 +131,16 @@ var _getExpressionsStmts: o.Statement[] = [
['invokeFn', o.variable('fn').callFn([o.literal('someParam')])],
[
'conditionalTrue',
o.literal('')
.prop('length')
.equals(o.literal(0))
.conditional(o.literal('true'), o.literal('false'))
'conditionalTrue', o.literal('')
.prop('length')
.equals(o.literal(0))
.conditional(o.literal('true'), o.literal('false'))
],
[
'conditionalFalse',
o.literal('')
.prop('length')
.notEquals(o.literal(0))
.conditional(o.literal('true'), o.literal('false'))
'conditionalFalse', o.literal('')
.prop('length')
.notEquals(o.literal(0))
.conditional(o.literal('true'), o.literal('false'))
],
['not', o.not(o.literal(false))],
@ -166,8 +156,7 @@ var _getExpressionsStmts: o.Statement[] = [
['catchError', o.variable('catchError')],
[
'operators',
o.literalMap([
'operators', o.literalMap([
['==', createOperatorFn(o.BinaryOperator.Equals)],
['!=', createOperatorFn(o.BinaryOperator.NotEquals)],
['===', createOperatorFn(o.BinaryOperator.Identical)],
@ -257,8 +246,9 @@ function createOperatorFn(op: o.BinaryOperator) {
}
export class DynamicClassInstanceFactory implements InstanceFactory {
createInstance(superClass: any, clazz: any, args: any[], props: Map<string, any>,
getters: Map<string, Function>, methods: Map<string, Function>): any {
createInstance(
superClass: any, clazz: any, args: any[], props: Map<string, any>,
getters: Map<string, Function>, methods: Map<string, Function>): any {
if (superClass === ExternalClass) {
return new _InterpretiveDynamicClass(args, clazz, props, getters, methods);
}
@ -267,8 +257,9 @@ export class DynamicClassInstanceFactory implements InstanceFactory {
}
class _InterpretiveDynamicClass extends ExternalClass implements DynamicInstance {
constructor(args: any[], public clazz: any, public props: Map<string, any>,
public getters: Map<string, Function>, public methods: Map<string, Function>) {
constructor(
args: any[], public clazz: any, public props: Map<string, any>,
public getters: Map<string, Function>, public methods: Map<string, Function>) {
super(args[0]);
}
childMethod(a: any /** TODO #9100 */) { return this.methods.get('childMethod')(a); }

View File

@ -1,13 +1,4 @@
import {
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {isBlank} from '../../src/facade/lang';
import {TypeScriptEmitter} from '@angular/compiler/src/output/ts_emitter';
@ -112,11 +103,9 @@ export function main() {
it('should support external identifiers', () => {
expect(emitStmt(o.importExpr(sameModuleIdentifier).toStmt())).toEqual('someLocalId;');
expect(emitStmt(o.importExpr(externalModuleIdentifier).toStmt()))
.toEqual([
`import * as import0 from 'somePackage/someOtherPath';`,
`import0.someExternalId;`
].join('\n'));
expect(emitStmt(o.importExpr(externalModuleIdentifier).toStmt())).toEqual([
`import * as import0 from 'somePackage/someOtherPath';`, `import0.someExternalId;`
].join('\n'));
});
it('should support operators', () => {
@ -149,47 +138,46 @@ export function main() {
expect(emitStmt(o.fn([], []).toStmt())).toEqual(['():void => {', '};'].join('\n'));
expect(emitStmt(o.fn([], [new o.ReturnStatement(o.literal(1))], o.INT_TYPE).toStmt()))
.toEqual(['():number => {', ' return 1;\n};'].join('\n'));
expect(emitStmt(o.fn([new o.FnParam('param1', o.INT_TYPE)], []).toStmt()))
.toEqual(['(param1:number):void => {', '};'].join('\n'));
expect(emitStmt(o.fn([new o.FnParam('param1', o.INT_TYPE)], []).toStmt())).toEqual([
'(param1:number):void => {', '};'
].join('\n'));
});
it('should support function statements', () => {
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [], [])))
.toEqual(['function someFn():void {', '}'].join('\n'));
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [], []), ['someFn']))
.toEqual(['export function someFn():void {', '}'].join('\n'));
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [], [new o.ReturnStatement(o.literal(1))],
o.INT_TYPE)))
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [], [
]))).toEqual(['function someFn():void {', '}'].join('\n'));
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [], []), ['someFn'])).toEqual([
'export function someFn():void {', '}'
].join('\n'));
expect(emitStmt(new o.DeclareFunctionStmt(
'someFn', [], [new o.ReturnStatement(o.literal(1))], o.INT_TYPE)))
.toEqual(['function someFn():number {', ' return 1;', '}'].join('\n'));
expect(
emitStmt(new o.DeclareFunctionStmt('someFn', [new o.FnParam('param1', o.INT_TYPE)], [])))
.toEqual(['function someFn(param1:number):void {', '}'].join('\n'));
expect(emitStmt(new o.DeclareFunctionStmt('someFn', [new o.FnParam('param1', o.INT_TYPE)], [
]))).toEqual(['function someFn(param1:number):void {', '}'].join('\n'));
});
it('should support comments',
() => { expect(emitStmt(new o.CommentStmt('a\nb'))).toEqual(['// a', '// b'].join('\n')); });
it('should support comments', () => {
expect(emitStmt(new o.CommentStmt('a\nb'))).toEqual(['// a', '// b'].join('\n'));
});
it('should support if stmt', () => {
var trueCase = o.variable('trueCase').callFn([]).toStmt();
var falseCase = o.variable('falseCase').callFn([]).toStmt();
expect(emitStmt(new o.IfStmt(o.variable('cond'), [trueCase])))
.toEqual(['if (cond) { trueCase(); }'].join('\n'));
expect(emitStmt(new o.IfStmt(o.variable('cond'), [trueCase], [falseCase])))
.toEqual(['if (cond) {', ' trueCase();', '} else {', ' falseCase();', '}'].join('\n'));
expect(emitStmt(new o.IfStmt(o.variable('cond'), [trueCase]))).toEqual([
'if (cond) { trueCase(); }'
].join('\n'));
expect(emitStmt(new o.IfStmt(o.variable('cond'), [trueCase], [falseCase]))).toEqual([
'if (cond) {', ' trueCase();', '} else {', ' falseCase();', '}'
].join('\n'));
});
it('should support try/catch', () => {
var bodyStmt = o.variable('body').callFn([]).toStmt();
var catchStmt = o.variable('catchFn').callFn([o.CATCH_ERROR_VAR, o.CATCH_STACK_VAR]).toStmt();
expect(emitStmt(new o.TryCatchStmt([bodyStmt], [catchStmt])))
.toEqual([
'try {',
' body();',
'} catch (error) {',
' const stack:any = error.stack;',
' catchFn(error,stack);',
'}'
].join('\n'));
expect(emitStmt(new o.TryCatchStmt([bodyStmt], [catchStmt]))).toEqual([
'try {', ' body();', '} catch (error) {', ' const stack:any = error.stack;',
' catchFn(error,stack);', '}'
].join('\n'));
});
it('should support support throwing',
@ -202,13 +190,12 @@ export function main() {
it('should support declaring classes', () => {
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, [])))
.toEqual(['class SomeClass {', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, [
]))).toEqual(['class SomeClass {', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, []), ['SomeClass']))
.toEqual(['export class SomeClass {', '}'].join('\n'));
expect(
emitStmt(new o.ClassStmt('SomeClass', o.variable('SomeSuperClass'), [], [], null, [])))
.toEqual(['class SomeClass extends SomeSuperClass {', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', o.variable('SomeSuperClass'), [], [], null, [
]))).toEqual(['class SomeClass extends SomeSuperClass {', '}'].join('\n'));
});
it('should support declaring constructors', () => {
@ -221,23 +208,24 @@ export function main() {
new o.ClassMethod(null, [new o.FnParam('someParam', o.INT_TYPE)], []), [])))
.toEqual(
['class SomeClass {', ' constructor(someParam:number) {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [],
new o.ClassMethod(null, [], [superCall]), [])))
.toEqual(['class SomeClass {', ' constructor() {', ' super(someParam);', ' }', '}']
.join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [],
new o.ClassMethod(null, [], [callSomeMethod]), [])))
.toEqual(
['class SomeClass {', ' constructor() {', ' this.someMethod();', ' }', '}']
.join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], new o.ClassMethod(null, [], [superCall]), [])))
.toEqual([
'class SomeClass {', ' constructor() {', ' super(someParam);', ' }', '}'
].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], new o.ClassMethod(null, [], [callSomeMethod]), [])))
.toEqual([
'class SomeClass {', ' constructor() {', ' this.someMethod();', ' }', '}'
].join('\n'));
});
it('should support declaring fields', () => {
expect(emitStmt(new o.ClassStmt('SomeClass', null, [new o.ClassField('someField')], [],
null, [])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [new o.ClassField('someField')], [], null, [])))
.toEqual(['class SomeClass {', ' someField:any;', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null,
[new o.ClassField('someField', o.INT_TYPE)], [], null, [])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [new o.ClassField('someField', o.INT_TYPE)], [], null, [])))
.toEqual(['class SomeClass {', ' someField:number;', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null,
@ -247,45 +235,47 @@ export function main() {
});
it('should support declaring getters', () => {
expect(emitStmt(new o.ClassStmt('SomeClass', null, [],
[new o.ClassGetter('someGetter', [])], null, [])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [new o.ClassGetter('someGetter', [])], null, [])))
.toEqual(['class SomeClass {', ' get someGetter():any {', ' }', '}'].join('\n'));
expect(
emitStmt(new o.ClassStmt('SomeClass', null, [],
[new o.ClassGetter('someGetter', [], o.INT_TYPE)], null, [])))
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [new o.ClassGetter('someGetter', [], o.INT_TYPE)], null,
[])))
.toEqual(['class SomeClass {', ' get someGetter():number {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [],
[new o.ClassGetter('someGetter', [callSomeMethod])], null,
[])))
.toEqual(
['class SomeClass {', ' get someGetter():any {', ' this.someMethod();', ' }', '}']
.join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [new o.ClassGetter('someGetter', [callSomeMethod])], null,
[])))
.toEqual([
'class SomeClass {', ' get someGetter():any {', ' this.someMethod();', ' }', '}'
].join('\n'));
expect(
emitStmt(new o.ClassStmt(
'SomeClass', null, [],
[new o.ClassGetter('someGetter', [], null, [o.StmtModifier.Private])], null, [])))
.toEqual(['class SomeClass {', ' private get someGetter():any {', ' }', '}'].join('\n'));
.toEqual(
['class SomeClass {', ' private get someGetter():any {', ' }', '}'].join('\n'));
});
it('should support methods', () => {
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null,
[new o.ClassMethod('someMethod', [], [])])))
.toEqual(['class SomeClass {', ' someMethod():void {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null,
[new o.ClassMethod('someMethod', [], [], o.INT_TYPE)])))
.toEqual(['class SomeClass {', ' someMethod():number {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, [
new o.ClassMethod('someMethod', [], [])
]))).toEqual(['class SomeClass {', ' someMethod():void {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null, [
new o.ClassMethod('someMethod', [], [], o.INT_TYPE)
]))).toEqual(['class SomeClass {', ' someMethod():number {', ' }', '}'].join('\n'));
expect(
emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], null,
[new o.ClassMethod('someMethod', [new o.FnParam('someParam', o.INT_TYPE)], [])])))
.toEqual(
['class SomeClass {', ' someMethod(someParam:number):void {', ' }', '}'].join(
'\n'));
expect(emitStmt(new o.ClassStmt('SomeClass', null, [], [], null,
[new o.ClassMethod('someMethod', [], [callSomeMethod])])))
.toEqual(
['class SomeClass {', ' someMethod():void {', ' this.someMethod();', ' }', '}']
.join('\n'));
.toEqual([
'class SomeClass {', ' someMethod(someParam:number):void {', ' }', '}'
].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [], null,
[new o.ClassMethod('someMethod', [], [callSomeMethod])])))
.toEqual([
'class SomeClass {', ' someMethod():void {', ' this.someMethod();', ' }', '}'
].join('\n'));
});
});
@ -303,11 +293,10 @@ export function main() {
var writeVarExpr = o.variable('a').set(o.NULL_EXPR);
expect(emitStmt(writeVarExpr.toDeclStmt(o.importType(sameModuleIdentifier))))
.toEqual('var a:someLocalId = null;');
expect(emitStmt(writeVarExpr.toDeclStmt(o.importType(externalModuleIdentifier))))
.toEqual([
`import * as import0 from 'somePackage/someOtherPath';`,
`var a:import0.someExternalId = null;`
].join('\n'));
expect(emitStmt(writeVarExpr.toDeclStmt(o.importType(externalModuleIdentifier)))).toEqual([
`import * as import0 from 'somePackage/someOtherPath';`,
`var a:import0.someExternalId = null;`
].join('\n'));
});
it('should support combined types', () => {

View File

@ -1,22 +1,11 @@
import {
beforeEach,
ddescribe,
xdescribe,
describe,
expect,
iit,
inject,
it,
xit
} from '@angular/core/testing/testing_internal';
import {HtmlParser} from '@angular/compiler/src/html_parser';
import {HtmlElementAst} from '@angular/compiler/src/html_ast';
import {HtmlParser} from '@angular/compiler/src/html_parser';
import {DomElementSchemaRegistry} from '@angular/compiler/src/schema/dom_element_schema_registry';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {browserDetection} from '@angular/platform-browser/testing';
import {DomElementSchemaRegistry} from '@angular/compiler/src/schema/dom_element_schema_registry';
import {SecurityContext} from '../../core_private';
import {extractSchema} from './schema_extractor';
export function main() {
@ -73,7 +62,7 @@ export function main() {
it('should detect properties on namespaced elements', () => {
let htmlAst = new HtmlParser().parse('<svg:style>', 'TestComp');
let nodeName = (<HtmlElementAst>htmlAst.rootNodes[0]).name;
let nodeName = (<HtmlElementAst>htmlAst.rootNodes[0]).name;
expect(registry.hasProperty(nodeName, 'type')).toBeTruthy();
});
@ -86,12 +75,10 @@ export function main() {
if (browserDetection.isChromeDesktop) {
it('generate a new schema', () => {
let schema = '\n';
extractSchema().forEach((props, name) => {
schema += `'${name}|${props.join(',')}',\n`;
});
extractSchema().forEach((props, name) => { schema += `'${name}|${props.join(',')}',\n`; });
// Uncomment this line to see:
// the generated schema which can then be pasted to the DomElementSchemaRegistry
//console.log(schema);
// console.log(schema);
});
}

View File

@ -1,14 +1,17 @@
import {isString, isPresent} from '../../src/facade/lang';
import {isPresent, isString} from '../../src/facade/lang';
const SVG_PREFIX = ':svg:';
var document = typeof (global as any /** TODO #???? */)['document'] == 'object' ? (global as any /** TODO #???? */)['document'] : null;
var document = typeof(global as any /** TODO #???? */)['document'] == 'object' ?
(global as any /** TODO #???? */)['document'] :
null;
export function extractSchema(): Map<string, string[]> {
var SVGGraphicsElement = (global as any /** TODO #???? */)['SVGGraphicsElement'];
var SVGAnimationElement = (global as any /** TODO #???? */)['SVGAnimationElement'];
var SVGGeometryElement = (global as any /** TODO #???? */)['SVGGeometryElement'];
var SVGComponentTransferFunctionElement = (global as any /** TODO #???? */)['SVGComponentTransferFunctionElement'];
var SVGComponentTransferFunctionElement =
(global as any /** TODO #???? */)['SVGComponentTransferFunctionElement'];
var SVGGradientElement = (global as any /** TODO #???? */)['SVGGradientElement'];
var SVGTextContentElement = (global as any /** TODO #???? */)['SVGTextContentElement'];
var SVGTextPositioningElement = (global as any /** TODO #???? */)['SVGTextPositioningElement'];
@ -27,44 +30,47 @@ export function extractSchema(): Map<string, string[]> {
extractProperties(HTMLElement, element, visited, descMap, '', '*');
extractProperties(HTMLMediaElement, element, visited, descMap, 'media', '');
extractProperties(SVGElement, svgText, visited, descMap, SVG_PREFIX, '*');
extractProperties(SVGGraphicsElement, svgText, visited, descMap, SVG_PREFIX + 'graphics',
SVG_PREFIX);
extractProperties(SVGAnimationElement, svgAnimation, visited, descMap,
SVG_PREFIX + 'animation', SVG_PREFIX);
extractProperties(SVGGeometryElement, svgPath, visited, descMap, SVG_PREFIX + 'geometry',
SVG_PREFIX);
extractProperties(SVGComponentTransferFunctionElement, svgFeFuncA, visited, descMap,
SVG_PREFIX + 'componentTransferFunction', SVG_PREFIX);
extractProperties(SVGGradientElement, svgGradient, visited, descMap, SVG_PREFIX + 'gradient',
SVG_PREFIX);
extractProperties(SVGTextContentElement, svgText, visited, descMap,
SVG_PREFIX + 'textContent', SVG_PREFIX + 'graphics');
extractProperties(SVGTextPositioningElement, svgText, visited, descMap,
SVG_PREFIX + 'textPositioning', SVG_PREFIX + 'textContent');
extractProperties(
SVGGraphicsElement, svgText, visited, descMap, SVG_PREFIX + 'graphics', SVG_PREFIX);
extractProperties(
SVGAnimationElement, svgAnimation, visited, descMap, SVG_PREFIX + 'animation', SVG_PREFIX);
extractProperties(
SVGGeometryElement, svgPath, visited, descMap, SVG_PREFIX + 'geometry', SVG_PREFIX);
extractProperties(
SVGComponentTransferFunctionElement, svgFeFuncA, visited, descMap,
SVG_PREFIX + 'componentTransferFunction', SVG_PREFIX);
extractProperties(
SVGGradientElement, svgGradient, visited, descMap, SVG_PREFIX + 'gradient', SVG_PREFIX);
extractProperties(
SVGTextContentElement, svgText, visited, descMap, SVG_PREFIX + 'textContent',
SVG_PREFIX + 'graphics');
extractProperties(
SVGTextPositioningElement, svgText, visited, descMap, SVG_PREFIX + 'textPositioning',
SVG_PREFIX + 'textContent');
var keys = Object.getOwnPropertyNames(window).filter(
k => k.endsWith('Element') && (k.startsWith('HTML') || k.startsWith('SVG')));
keys.sort();
keys.forEach(name => extractRecursiveProperties(visited, descMap, (window as any /** TODO #???? */)[name]));
keys.forEach(
name =>
extractRecursiveProperties(visited, descMap, (window as any /** TODO #???? */)[name]));
return descMap;
}
function extractRecursiveProperties(visited: {[name: string]: boolean}, descMap: Map<string, string[]>,
type: Function): string {
function extractRecursiveProperties(
visited: {[name: string]: boolean}, descMap: Map<string, string[]>, type: Function): string {
var name = extractName(type);
if (visited[name]) return name; // already been here
var superName = '';
if (name != '*') {
superName =
extractRecursiveProperties(visited, descMap, type.prototype.__proto__.constructor);
superName = extractRecursiveProperties(visited, descMap, type.prototype.__proto__.constructor);
}
var instance: HTMLElement = null;
name.split(',').forEach(tagName => {
instance = isSVG(type) ?
document.createElementNS('http://www.w3.org/2000/svg',
tagName.replace(SVG_PREFIX, '')) :
document.createElement(tagName);
document.createElementNS('http://www.w3.org/2000/svg', tagName.replace(SVG_PREFIX, '')) :
document.createElement(tagName);
var htmlType = type;
if (tagName == 'cite') htmlType = HTMLElement;
if (!(instance instanceof htmlType)) {
@ -75,8 +81,9 @@ function extractRecursiveProperties(visited: {[name: string]: boolean}, descMap:
return name;
}
function extractProperties(type: Function, instance: any, visited: {[name: string]: boolean},
descMap: Map<string, string[]>, name: string, superName: string) {
function extractProperties(
type: Function, instance: any, visited: {[name: string]: boolean},
descMap: Map<string, string[]>, name: string, superName: string) {
if (!type) return;
visited[name] = true;
const fullName = name + (superName ? '^' + superName : '');

View File

@ -1,12 +1,14 @@
import {describe, it, expect, beforeEach, ddescribe, iit, xit} from '@angular/core/testing';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {SelectorMatcher} from '@angular/compiler/src/selector';
import {CssSelector} from '@angular/compiler/src/selector';
import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {el} from '@angular/platform-browser/testing';
export function main() {
describe('SelectorMatcher', () => {
var matcher: any /** TODO #9100 */, selectableCollector: any /** TODO #9100 */, s1: any /** TODO #9100 */, s2: any /** TODO #9100 */, s3: any /** TODO #9100 */, s4: any /** TODO #9100 */;
var matcher: any /** TODO #9100 */, selectableCollector: any /** TODO #9100 */,
s1: any /** TODO #9100 */, s2: any /** TODO #9100 */, s3: any /** TODO #9100 */,
s4: any /** TODO #9100 */;
var matched: any[];
function reset() { matched = []; }
@ -72,20 +74,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 +122,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 +144,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 +207,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 +302,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 +312,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', () => {

View File

@ -1,11 +1,4 @@
import {
describe,
beforeEach,
it,
expect,
ddescribe,
iit,
} from '@angular/core/testing/testing_internal';
import {describe, beforeEach, it, expect, ddescribe, iit,} from '@angular/core/testing/testing_internal';
import {ShadowCss, processRules, CssRule} from '@angular/compiler/src/shadow_css';
import {RegExpWrapper, StringWrapper, isPresent} from '../src/facade/lang';
@ -110,7 +103,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');
@ -118,7 +111,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');
@ -126,15 +119,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');
@ -203,26 +197,30 @@ 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: any /** TODO #9100 */) => new CssRule(cssRule.selector + '2', cssRule.content)))
expect(processRules(
'@import a; b {c {d}} e {f}', (cssRule: any /** TODO #9100 */) => 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: any /** TODO #9100 */) => new CssRule(cssRule.selector, cssRule.content + '2')))
expect(processRules(
'a {b}', (cssRule: any /** TODO #9100 */) =>
new CssRule(cssRule.selector, cssRule.content + '2')))
.toEqual('a {b2}');
});
});

View File

@ -1,7 +1,6 @@
import {describe, it, expect, beforeEach, ddescribe, iit, xit} from '@angular/core/testing';
import {extractStyleUrls, isStyleUrlResolvable} from '@angular/compiler/src/style_url_resolver';
import {UrlResolver} from '@angular/compiler/src/url_resolver';
import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing';
export function main() {
describe('extractStyleUrls', () => {
@ -38,8 +37,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 +56,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', () => {

File diff suppressed because it is too large Load Diff

View File

@ -1,23 +1,6 @@
import {
ddescribe,
describe,
xdescribe,
it,
iit,
xit,
expect,
beforeEach,
afterEach,
inject,
beforeEachProviders
} from '@angular/core/testing/testing_internal';
import {HtmlParser} from '@angular/compiler/src/html_parser';
import {
preparseElement,
PreparsedElementType,
PreparsedElement
} from '@angular/compiler/src/template_preparser';
import {PreparsedElement, PreparsedElementType, preparseElement} from '@angular/compiler/src/template_preparser';
import {afterEach, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
export function main() {
describe('preparseElement', () => {

View File

@ -1,7 +1,7 @@
import {provide} from '@angular/core';
import {MockSchemaRegistry, MockXHR} from '@angular/compiler/testing';
import {ElementSchemaRegistry, XHR, UrlResolver} from '@angular/compiler';
import {ElementSchemaRegistry, UrlResolver, XHR} from '@angular/compiler';
import {createUrlResolverWithoutPackagePrefix} from '@angular/compiler/src/url_resolver';
import {MockSchemaRegistry, MockXHR} from '@angular/compiler/testing';
import {provide} from '@angular/core';
export var TEST_PROVIDERS: any[] = [
{provide: ElementSchemaRegistry, useValue: new MockSchemaRegistry({}, {})},

View File

@ -1,42 +1,18 @@
import {
beforeEach,
ddescribe,
xdescribe,
describe,
expect,
iit,
inject,
beforeEachProviders,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {
TestComponentBuilder,
ComponentFixtureAutoDetect,
ComponentFixtureNoNgZone
} from '@angular/compiler/testing';
import {beforeEach, ddescribe, xdescribe, describe, expect, iit, inject, beforeEachProviders, it, xit,} from '@angular/core/testing/testing_internal';
import {TestComponentBuilder, ComponentFixtureAutoDetect, ComponentFixtureNoNgZone} from '@angular/compiler/testing';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {
Injectable,
Component,
Input,
ViewMetadata,
ComponentResolver
} from '@angular/core';
import {Injectable, Component, Input, ViewMetadata, ComponentResolver} from '@angular/core';
import {NgIf} from '@angular/common';
import {TimerWrapper} from '../src/facade/async';
import {IS_DART} from '../src/facade/lang';
import {PromiseWrapper} from '../src/facade/promise';
import {dispatchEvent} from "@angular/platform-browser/testing";
import {
withProviders
} from "@angular/core/testing/test_injector"
import {dispatchEvent} from '@angular/platform-browser/testing';
import {withProviders} from '@angular/core/testing/test_injector';
@Component({
selector: 'child-comp',
template: `<span>Original {{childBinding}}</span>`,
directives: []
}) @Injectable() class ChildComp {
@Component(
{selector: 'child-comp', template: `<span>Original {{childBinding}}</span>`, directives: []})
@Injectable()
class ChildComp {
childBinding: string;
constructor() { this.childBinding = 'Child'; }
}
@ -138,8 +114,8 @@ class NestedAsyncTimeoutComp {
text: string = '1';
click() {
TimerWrapper.setTimeout(() => { TimerWrapper.setTimeout(() => { this.text += '1'; }, 10); },
10);
TimerWrapper.setTimeout(
() => { TimerWrapper.setTimeout(() => { this.text += '1'; }, 10); }, 10);
}
}
@ -183,8 +159,11 @@ class ListDir2 {
const LIST_CHILDREN = /*@ts2dart_const*/[ListDir1, ListDir2];
@Component(
{selector: 'directive-list-comp', template: `(<li1></li1>)(<li2></li2>)`, directives: [LIST_CHILDREN]})
@Component({
selector: 'directive-list-comp',
template: `(<li1></li1>)(<li2></li2>)`,
directives: [LIST_CHILDREN]
})
class DirectiveListComp {
}
@ -192,424 +171,449 @@ class DirectiveListComp {
export function main() {
describe('test component builder', function() {
it('should instantiate a component with valid DOM',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(ChildComp).then((componentFixture) => {
componentFixture.detectChanges();
tcb.createAsync(ChildComp).then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('Original Child');
async.done();
});
}));
expect(componentFixture.nativeElement).toHaveText('Original Child');
async.done();
});
}));
it('should allow changing members of the component',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(MyIfComp).then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('MyIf()');
tcb.createAsync(MyIfComp).then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('MyIf()');
componentFixture.componentInstance.showMore = true;
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('MyIf(More)');
componentFixture.componentInstance.showMore = true;
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('MyIf(More)');
async.done();
});
}));
async.done();
});
}));
it('should override a template',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideTemplate(MockChildComp, '<span>Mock</span>')
.createAsync(MockChildComp)
.then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('Mock');
tcb.overrideTemplate(MockChildComp, '<span>Mock</span>')
.createAsync(MockChildComp)
.then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('Mock');
async.done();
});
}));
async.done();
});
}));
it('should override a view',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideView(ChildComp,
new ViewMetadata({template: '<span>Modified {{childBinding}}</span>'}))
.createAsync(ChildComp)
.then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('Modified Child');
tcb.overrideView(
ChildComp,
new ViewMetadata({template: '<span>Modified {{childBinding}}</span>'}))
.createAsync(ChildComp)
.then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('Modified Child');
async.done();
});
}));
async.done();
});
}));
it('should override component dependencies',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideDirective(ParentComp, ChildComp, MockChildComp)
.createAsync(ParentComp)
.then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('Parent(Mock)');
tcb.overrideDirective(ParentComp, ChildComp, MockChildComp)
.createAsync(ParentComp)
.then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('Parent(Mock)');
async.done();
});
}));
async.done();
});
}));
it('should override items from a list',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideDirective(DirectiveListComp, ListDir1, ListDir1Alt)
.createAsync(DirectiveListComp)
.then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('(Alternate One)(Two)');
tcb.overrideDirective(DirectiveListComp, ListDir1, ListDir1Alt)
.createAsync(DirectiveListComp)
.then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('(Alternate One)(Two)');
async.done();
});
}));
async.done();
});
}));
it("should override child component's dependencies",
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
it('should override child component\'s dependencies',
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideDirective(ParentComp, ChildComp, ChildWithChildComp)
.overrideDirective(ChildWithChildComp, ChildChildComp, MockChildChildComp)
.createAsync(ParentComp)
.then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement)
.toHaveText('Parent(Original Child(ChildChild Mock))');
tcb.overrideDirective(ParentComp, ChildComp, ChildWithChildComp)
.overrideDirective(ChildWithChildComp, ChildChildComp, MockChildChildComp)
.createAsync(ParentComp)
.then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement)
.toHaveText('Parent(Original Child(ChildChild Mock))');
async.done();
});
}));
async.done();
});
}));
it('should override a provider',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideProviders(TestBindingsComp,
[{provide: FancyService, useClass: MockFancyService}])
.createAsync(TestBindingsComp)
.then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement)
.toHaveText('injected value: mocked out value');
async.done();
});
}));
tcb.overrideProviders(
TestBindingsComp, [{provide: FancyService, useClass: MockFancyService}])
.createAsync(TestBindingsComp)
.then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement)
.toHaveText('injected value: mocked out value');
async.done();
});
}));
it('should override a viewBinding',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideViewProviders(TestViewBindingsComp,
[{provide: FancyService, useClass: MockFancyService}])
.createAsync(TestViewBindingsComp)
.then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement)
.toHaveText('injected value: mocked out value');
async.done();
});
}));
tcb.overrideViewProviders(
TestViewBindingsComp, [{provide: FancyService, useClass: MockFancyService}])
.createAsync(TestViewBindingsComp)
.then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement)
.toHaveText('injected value: mocked out value');
async.done();
});
}));
if (!IS_DART) {
describe('ComponentFixture', () => {
it('should auto detect changes if autoDetectChanges is called',
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(AutoDetectComp)
.then((componentFixture) => {
expect(componentFixture.ngZone).not.toBeNull();
componentFixture.autoDetectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
tcb.createAsync(AutoDetectComp).then((componentFixture) => {
expect(componentFixture.ngZone).not.toBeNull();
componentFixture.autoDetectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.isStable()).toBe(true);
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
}));
expect(componentFixture.isStable()).toBe(true);
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
}));
it('should auto detect changes if ComponentFixtureAutoDetect is provided as true',
withProviders(() => [{provide: ComponentFixtureAutoDetect, useValue: true}])
.inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
.inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(AutoDetectComp)
.then((componentFixture) => {
expect(componentFixture.nativeElement).toHaveText('1');
tcb.createAsync(AutoDetectComp).then((componentFixture) => {
expect(componentFixture.nativeElement).toHaveText('1');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
}));
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
}));
it('should signal through whenStable when the fixture is stable (autoDetectChanges)',
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(AsyncComp).then((componentFixture) => {
componentFixture.autoDetectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
tcb.createAsync(AsyncComp).then((componentFixture) => {
componentFixture.autoDetectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
// Component is updated asynchronously. Wait for the fixture to become stable
// before checking for new value.
expect(componentFixture.isStable()).toBe(false);
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
});
}));
// Component is updated asynchronously. Wait for the fixture to become stable
// before checking for new value.
expect(componentFixture.isStable()).toBe(false);
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
});
}));
it('should signal through isStable when the fixture is stable (no autoDetectChanges)',
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(AsyncComp).then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
tcb.createAsync(AsyncComp).then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
// Component is updated asynchronously. Wait for the fixture to become stable
// before checking.
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
});
}));
// Component is updated asynchronously. Wait for the fixture to become stable
// before checking.
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
});
}));
it('should wait for macroTask(setTimeout) while checking for whenStable ' +
'(autoDetectChanges)',
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(AsyncTimeoutComp)
.then((componentFixture) => {
componentFixture.autoDetectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
tcb.createAsync(AsyncTimeoutComp).then((componentFixture) => {
componentFixture.autoDetectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
// Component is updated asynchronously. Wait for the fixture to become
// stable before checking for new value.
expect(componentFixture.isStable()).toBe(false);
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
});
}));
// Component is updated asynchronously. Wait for the fixture to become
// stable before checking for new value.
expect(componentFixture.isStable()).toBe(false);
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
});
}));
it('should wait for macroTask(setTimeout) while checking for whenStable ' +
'(no autoDetectChanges)',
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(AsyncTimeoutComp)
.then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
tcb.createAsync(AsyncTimeoutComp).then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
// Component is updated asynchronously. Wait for the fixture to become
// stable before checking for new value.
expect(componentFixture.isStable()).toBe(false);
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
});
}));
// Component is updated asynchronously. Wait for the fixture to become
// stable before checking for new value.
expect(componentFixture.isStable()).toBe(false);
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
});
}));
it('should wait for nested macroTasks(setTimeout) while checking for whenStable ' +
'(autoDetectChanges)',
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(NestedAsyncTimeoutComp)
.then((componentFixture) => {
componentFixture.autoDetectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
tcb.createAsync(NestedAsyncTimeoutComp).then((componentFixture) => {
componentFixture.autoDetectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
// Component is updated asynchronously. Wait for the fixture to become
// stable before checking for new value.
expect(componentFixture.isStable()).toBe(false);
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
});
}));
// Component is updated asynchronously. Wait for the fixture to become
// stable before checking for new value.
expect(componentFixture.isStable()).toBe(false);
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
});
}));
it('should wait for nested macroTasks(setTimeout) while checking for whenStable ' +
'(no autoDetectChanges)',
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(NestedAsyncTimeoutComp)
.then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
tcb.createAsync(NestedAsyncTimeoutComp).then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
// Component is updated asynchronously. Wait for the fixture to become
// stable before checking for new value.
expect(componentFixture.isStable()).toBe(false);
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
});
}));
// Component is updated asynchronously. Wait for the fixture to become
// stable before checking for new value.
expect(componentFixture.isStable()).toBe(false);
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
});
}));
it('should stabilize after async task in change detection (autoDetectChanges)',
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(AsyncChangeComp)
.then((componentFixture) => {
componentFixture.autoDetectChanges();
componentFixture.whenStable().then((_) => {
expect(componentFixture.nativeElement).toHaveText('1');
tcb.createAsync(AsyncChangeComp).then((componentFixture) => {
componentFixture.autoDetectChanges();
componentFixture.whenStable().then((_) => {
expect(componentFixture.nativeElement).toHaveText('1');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
componentFixture.whenStable().then((_) => {
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
});
});
}));
componentFixture.whenStable().then((_) => {
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
});
});
}));
it('should stabilize after async task in change detection(no autoDetectChanges)',
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(AsyncChangeComp)
.then((componentFixture) => {
componentFixture.detectChanges();
componentFixture.whenStable().then((_) => {
// Run detectChanges again so that stabilized value is reflected in the
// DOM.
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
tcb.createAsync(AsyncChangeComp).then((componentFixture) => {
componentFixture.detectChanges();
componentFixture.whenStable().then((_) => {
// Run detectChanges again so that stabilized value is reflected in the
// DOM.
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
componentFixture.detectChanges();
let element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
componentFixture.detectChanges();
componentFixture.whenStable().then((_) => {
// Run detectChanges again so that stabilized value is reflected in
// the DOM.
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
});
});
}));
componentFixture.whenStable().then((_) => {
// Run detectChanges again so that stabilized value is reflected in
// the DOM.
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('11');
async.done();
});
});
});
}));
describe('No NgZone', () => {
beforeEachProviders(() => [{provide: ComponentFixtureNoNgZone, useValue: true}]);
it('calling autoDetectChanges raises an error', () => {
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder,
async: AsyncTestCompleter) => {
tcb.createAsync(ChildComp).then((componentFixture) => {
expect(() => {
componentFixture.autoDetectChanges();
}).toThrow('Cannot call autoDetectChanges when ComponentFixtureNoNgZone is set!!');
async.done();
});
});
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(ChildComp).then((componentFixture) => {
expect(() => { componentFixture.autoDetectChanges(); })
.toThrow(
'Cannot call autoDetectChanges when ComponentFixtureNoNgZone is set!!');
async.done();
});
});
});
it('should instantiate a component with valid DOM',
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(ChildComp).then((componentFixture) => {
expect(componentFixture.ngZone).toBeNull();
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('Original Child');
async.done();
});
}));
tcb.createAsync(ChildComp).then((componentFixture) => {
expect(componentFixture.ngZone).toBeNull();
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('Original Child');
async.done();
});
}));
it('should allow changing members of the component',
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(MyIfComp).then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('MyIf()');
tcb.createAsync(MyIfComp).then((componentFixture) => {
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('MyIf()');
componentFixture.componentInstance.showMore = true;
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('MyIf(More)');
componentFixture.componentInstance.showMore = true;
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('MyIf(More)');
async.done();
});
}));
async.done();
});
}));
});
describe('createSync', () => {
it('should create components',
inject([ComponentResolver, TestComponentBuilder, AsyncTestCompleter],
(cr: ComponentResolver, tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
cr.resolveComponent(MyIfComp).then((cmpFactory) => {
let componentFixture = tcb.createSync(cmpFactory);
inject(
[ComponentResolver, TestComponentBuilder, AsyncTestCompleter],
(cr: ComponentResolver, tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
cr.resolveComponent(MyIfComp).then((cmpFactory) => {
let componentFixture = tcb.createSync(cmpFactory);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('MyIf()');
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('MyIf()');
componentFixture.componentInstance.showMore = true;
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('MyIf(More)');
componentFixture.componentInstance.showMore = true;
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('MyIf(More)');
async.done();
});
}));
async.done();
});
}));
});

View File

@ -1,15 +1,7 @@
import {
describe,
it,
expect,
beforeEach,
ddescribe,
iit,
xit,
inject
} from '@angular/core/testing/testing_internal';
import {IS_DART} from '../src/facade/lang';
import {UrlResolver, createOfflineCompileUrlResolver} from '@angular/compiler/src/url_resolver';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {IS_DART} from '../src/facade/lang';
export function main() {
describe('UrlResolver', () => {
@ -82,9 +74,9 @@ 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');
});
});
@ -128,11 +120,11 @@ export function main() {
});
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');
});
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');
});
});
});
}

View File

@ -1,11 +1,4 @@
import {
beforeEach,
ddescribe,
describe,
expect,
iit,
it,
} from '@angular/core/testing/testing_internal';
import {beforeEach, ddescribe, describe, expect, iit, it,} from '@angular/core/testing/testing_internal';
import {stringify} from '../src/facade/lang';
import {MockViewResolver} from '../testing';

View File

@ -1,16 +1,16 @@
import {ddescribe, describe, it, iit, expect, beforeEach} from '@angular/core/testing';
import {ViewResolver} from '@angular/compiler/src/view_resolver';
import {Component, ViewMetadata} from '@angular/core/src/metadata';
import {beforeEach, ddescribe, describe, expect, iit, it} from '@angular/core/testing';
class SomeDir {}
class SomePipe {}
@Component({
selector: 'sample',
template: "some template",
template: 'some template',
directives: [SomeDir],
pipes: [SomePipe],
styles: ["some styles"]
styles: ['some styles']
})
class ComponentWithTemplate {
}
@ -23,31 +23,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 neither template nor templateUrl 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 component decorator', () => {
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.');
});
});
}

View File

@ -1,12 +1,4 @@
import {
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
} from '@angular/core/testing/testing_internal';
import {beforeEach, ddescribe, describe, expect, iit, inject, it,} from '@angular/core/testing/testing_internal';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {MockXHR} from '@angular/compiler/testing';
import {PromiseWrapper} from '../src/facade/async';
@ -18,7 +10,9 @@ export function main() {
beforeEach(() => { xhr = new MockXHR(); });
function expectResponse(request: Promise<string>, url: string, response: string, done: any /** TODO #9100 */ = null) {
function expectResponse(
request: Promise<string>, url: string, response: string,
done: any /** TODO #9100 */ = null) {
function onResponse(text: string): string {
if (response === null) {
throw `Unexpected response ${url} -> ${text}`;
@ -42,7 +36,8 @@ export function main() {
PromiseWrapper.then(request, onResponse, onError);
}
it('should return a response from the definitions', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
it('should return a response from the definitions',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var url = '/foo';
var response = 'bar';
xhr.when(url, response);
@ -50,7 +45,8 @@ export function main() {
xhr.flush();
}));
it('should return an error from the definitions', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
it('should return an error from the definitions',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var url = '/foo';
var response: any /** TODO #9100 */ = null;
xhr.when(url, response);
@ -58,7 +54,8 @@ export function main() {
xhr.flush();
}));
it('should return a response from the expectations', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
it('should return a response from the expectations',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var url = '/foo';
var response = 'bar';
xhr.expect(url, response);
@ -66,7 +63,8 @@ export function main() {
xhr.flush();
}));
it('should return an error from the expectations', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
it('should return an error from the expectations',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var url = '/foo';
var response: any /** TODO #9100 */ = null;
xhr.expect(url, response);
@ -83,7 +81,8 @@ export function main() {
expect(() => { xhr.flush(); }).toThrowError('Unexpected request /foo');
});
it('should return expectations before definitions', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
it('should return expectations before definitions',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var url = '/foo';
xhr.when(url, 'when');
xhr.expect(url, 'expect');