本文整理汇总了TypeScript中@angular/core/testing/testing_internal.it函数的典型用法代码示例。如果您正苦于以下问题:TypeScript it函数的具体用法?TypeScript it怎么用?TypeScript it使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了it函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: describe
describe('reflector_host', () => {
var context: MockContext;
var host: ts.CompilerHost;
var program: ts.Program;
var reflectorHost: ReflectorHost;
beforeEach(() => {
context = new MockContext('/tmp/src', clone(FILES));
host = new MockCompilerHost(context)
program = ts.createProgram(
['main.ts'], {
module: ts.ModuleKind.CommonJS,
},
host);
// Force a typecheck
let errors = program.getSemanticDiagnostics();
if (errors && errors.length) {
throw new Error('Expected no errors');
}
reflectorHost = new ReflectorHost(
program, host, {
genDir: '/tmp/dist',
basePath: '/tmp/src',
skipMetadataEmit: false,
skipTemplateCodegen: false,
trace: false
},
context);
});
it('should provide the import locations for angular', () => {
let {coreDecorators, diDecorators, diMetadata, animationMetadata, provider} =
reflectorHost.angularImportLocations();
expect(coreDecorators).toEqual('@angular/core/src/metadata');
expect(diDecorators).toEqual('@angular/core/src/di/decorators');
expect(diMetadata).toEqual('@angular/core/src/di/metadata');
expect(animationMetadata).toEqual('@angular/core/src/animation/metadata');
expect(provider).toEqual('@angular/core/src/di/provider');
});
it('should be able to produce an import from main @angular/core', () => {
expect(reflectorHost.getImportPath('main.ts', 'node_modules/@angular/core.d.ts'))
.toEqual('@angular/core');
});
it('should be ble to produce an import from main to a sub-directory', () => {
expect(reflectorHost.getImportPath('main.ts', 'lib/utils.ts')).toEqual('./lib/utils');
});
it('should be able to produce an import from to a peer file', () => {
expect(reflectorHost.getImportPath('lib/utils.ts', 'lib/collections.ts'))
.toEqual('./collections');
});
it('should be able to produce an import from to a sibling directory', () => {
expect(reflectorHost.getImportPath('lib2/utils2.ts', 'lib/utils.ts')).toEqual('../lib/utils');
});
it('should be able to produce a symbol for an exported symbol', () => {
expect(reflectorHost.findDeclaration('@angular/router-deprecated', 'foo', 'main.ts'))
.toBeDefined();
});
it('should be able to produce a symbol for values space only reference', () => {
expect(
reflectorHost.findDeclaration('@angular/router-deprecated/src/providers', 'foo', 'main.ts'))
.toBeDefined();
});
it('should be produce the same symbol if asked twice', () => {
let foo1 = reflectorHost.getStaticSymbol('main.ts', 'foo');
let foo2 = reflectorHost.getStaticSymbol('main.ts', 'foo');
expect(foo1).toBe(foo2);
});
it('should be able to read a metadata file',
() => {
expect(reflectorHost.getMetadataFor('node_modules/@angular/core.d.ts'))
.toEqual({__symbolic: 'module', version: 1, metadata: {foo: {__symbolic: 'class'}}})});
it('should be able to read metadata from an otherwise unused .d.ts file ', () => {
expect(reflectorHost.getMetadataFor('node_modules/@angular/unused.d.ts')).toBeUndefined();
});
});
示例2: describe
describe('classes', () => {
let callSomeMethod: o.Statement;
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', 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'));
});
it('should support declaring constructors', () => {
const superCall = o.SUPER_EXPR.callFn([o.variable('someParam')]).toStmt();
expect(emitStmt(
new o.ClassStmt('SomeClass', null, [], [], new o.ClassMethod(null, [], []), [])))
.toEqual(['class SomeClass {', ' constructor() {', ' }', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null, [], [],
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'));
});
it('should support declaring fields', () => {
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, [])))
.toEqual(['class SomeClass {', ' someField:number;', '}'].join('\n'));
expect(emitStmt(new o.ClassStmt(
'SomeClass', null,
[new o.ClassField('someField', o.INT_TYPE, [o.StmtModifier.Private])], [], null,
[])))
.toEqual(['class SomeClass {', ' /*private*/ someField:number;', '}'].join('\n'));
});
it('should support declaring getters', () => {
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,
[])))
.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', [], null, [o.StmtModifier.Private])], null, [])))
.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', [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'));
});
});
示例3: asyncRoutesWithoutChildrenWithParams
function asyncRoutesWithoutChildrenWithParams() {
var fixture: any /** TODO #9100 */;
var tcb: any /** TODO #9100 */;
var rtr: any /** TODO #9100 */;
beforeEachProviders(() => TEST_ROUTER_PROVIDERS);
beforeEach(inject(
[TestComponentBuilder, Router],
(tcBuilder: any /** TODO #9100 */, router: any /** TODO #9100 */) => {
tcb = tcBuilder;
rtr = router;
}));
it('should navigate by URL', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
compile(tcb)
.then((rtc) => {fixture = rtc})
.then((_) => rtr.config([new AsyncRoute(
{path: '/user/:name', loader: userCmpLoader, name: 'User'})]))
.then((_) => rtr.navigateByUrl('/user/igor'))
.then((_) => {
fixture.detectChanges();
expect(fixture.debugElement.nativeElement).toHaveText('hello igor');
async.done();
});
}));
it('should navigate by link DSL', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
compile(tcb)
.then((rtc) => {fixture = rtc})
.then(
(_) =>
rtr.config([new Route({path: '/user/:name', component: UserCmp, name: 'User'})]))
.then((_) => rtr.navigate(['/User', {name: 'brian'}]))
.then((_) => {
fixture.detectChanges();
expect(fixture.debugElement.nativeElement).toHaveText('hello brian');
async.done();
});
}));
it('should generate a link URL', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
compile(
tcb,
`<a [routerLink]="['User', {name: 'naomi'}]">greet naomi</a> | <router-outlet></router-outlet>`)
.then((rtc) => {fixture = rtc})
.then((_) => rtr.config([new AsyncRoute(
{path: '/user/:name', loader: userCmpLoader, name: 'User'})]))
.then((_) => {
fixture.detectChanges();
expect(getHref(getLinkElement(fixture))).toEqual('/user/naomi');
async.done();
});
}));
it('should navigate from a link click',
inject(
[AsyncTestCompleter, Location],
(async: AsyncTestCompleter, location: any /** TODO #9100 */) => {
compile(
tcb,
`<a [routerLink]="['User', {name: 'naomi'}]">greet naomi</a> | <router-outlet></router-outlet>`)
.then((rtc) => {fixture = rtc})
.then((_) => rtr.config([new AsyncRoute(
{path: '/user/:name', loader: userCmpLoader, name: 'User'})]))
.then((_) => {
fixture.detectChanges();
expect(fixture.debugElement.nativeElement).toHaveText('greet naomi | ');
rtr.subscribe((_: any /** TODO #9100 */) => {
fixture.detectChanges();
expect(fixture.debugElement.nativeElement)
.toHaveText('greet naomi | hello naomi');
expect(location.urlChanges).toEqual(['/user/naomi']);
async.done();
});
clickOnElement(getLinkElement(fixture));
});
}));
it('should navigate between components with different parameters',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
compile(tcb)
.then((rtc) => {fixture = rtc})
.then((_) => rtr.config([new AsyncRoute(
{path: '/user/:name', loader: userCmpLoader, name: 'User'})]))
.then((_) => rtr.navigateByUrl('/user/brian'))
.then((_) => {
fixture.detectChanges();
expect(fixture.debugElement.nativeElement).toHaveText('hello brian');
})
.then((_) => rtr.navigateByUrl('/user/igor'))
.then((_) => {
fixture.detectChanges();
expect(fixture.debugElement.nativeElement).toHaveText('hello igor');
async.done();
});
}));
}
示例4: describe
describe('router bootstrap', () => {
beforeEachProviders(() => [
ROUTER_PROVIDERS,
{provide: LocationStrategy, useClass: MockLocationStrategy},
{provide: ApplicationRef, useClass: MockApplicationRef}
]);
// do not refactor out the `bootstrap` functionality. We still want to
// keep this test around so we can ensure that bootstrap a router works
it('should bootstrap a simple app', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var fakeDoc = getDOM().createHtmlDocument();
var el = getDOM().createElement('app-cmp', fakeDoc);
getDOM().appendChild(fakeDoc.body, el);
bootstrap(AppCmp,
[
ROUTER_PROVIDERS,
{provide: ROUTER_PRIMARY_COMPONENT, useValue: AppCmp},
{provide: LocationStrategy, useClass: MockLocationStrategy},
{provide: DOCUMENT, useValue: fakeDoc},
{provide: Console, useClass: DummyConsole}
])
.then((applicationRef) => {
var router = applicationRef.instance.router;
router.subscribe((_: any /** TODO #9100 */) => {
expect(el).toHaveText('outer { hello }');
expect(applicationRef.instance.location.path()).toEqual('');
async.done();
});
});
}));
describe('broken app', () => {
beforeEachProviders(() => [{provide: ROUTER_PRIMARY_COMPONENT, useValue: BrokenAppCmp}]);
it('should rethrow exceptions from component constructors',
inject([AsyncTestCompleter, TestComponentBuilder], (async: AsyncTestCompleter, tcb: TestComponentBuilder) => {
tcb.createAsync(AppCmp).then((fixture) => {
var router = fixture.debugElement.componentInstance.router;
PromiseWrapper.catchError(router.navigateByUrl('/cause-error'), (error) => {
expect(error).toContainError('oops!');
async.done();
});
});
}));
});
describe('back button app', () => {
beforeEachProviders(() => [{provide: ROUTER_PRIMARY_COMPONENT, useValue: HierarchyAppCmp}]);
it('should change the url without pushing a new history state for back navigations',
inject([AsyncTestCompleter, TestComponentBuilder], (async: AsyncTestCompleter, tcb: TestComponentBuilder) => {
tcb.createAsync(HierarchyAppCmp)
.then((fixture) => {
var router = fixture.debugElement.componentInstance.router;
var position = 0;
var flipped = false;
var history = [
['/parent/child', 'root { parent { hello } }', '/super-parent/child'],
['/super-parent/child', 'root { super-parent { hello2 } }', '/parent/child'],
['/parent/child', 'root { parent { hello } }', false]
];
router.subscribe((_: any /** TODO #9100 */) => {
var location = fixture.debugElement.componentInstance.location;
var element = fixture.debugElement.nativeElement;
var path = location.path();
var entry = history[position];
expect(path).toEqual(entry[0]);
expect(element).toHaveText(entry[1]);
var nextUrl = entry[2];
if (nextUrl == false) {
flipped = true;
}
if (flipped && position == 0) {
async.done();
return;
}
position = position + (flipped ? -1 : 1);
if (flipped) {
location.back();
} else {
router.navigateByUrl(nextUrl);
}
});
router.navigateByUrl(history[0][0]);
});
}), 1000);
});
describe('hierarchical app', () => {
beforeEachProviders(
() => { return [{provide: ROUTER_PRIMARY_COMPONENT, useValue: HierarchyAppCmp}]; });
//.........这里部分代码省略.........
示例5: describe
describe('link', () => {
let parser = new DefaultRouterUrlSerializer();
it("should return the original tree when given an empty array", () => {
let p = parser.parse("/");
let tree = s(p.root);
let t = link(tree.root, tree, p, []);
expect(t).toBe(p);
});
it("should support going to root", () => {
let p = parser.parse("/");
let tree = s(p.root);
let t = link(tree.root, tree, p, ["/"]);
expect(parser.serialize(t)).toEqual("");
});
it("should support positional params", () => {
let p = parser.parse("/a/b");
let tree = s(p.firstChild(p.root));
let t = link(tree.root, tree, p, ["/one", 11, "two", 22]);
expect(parser.serialize(t)).toEqual("/one/11/two/22");
});
it("should preserve route siblings when changing the main route", () => {
let p = parser.parse("/a/11/b(c)");
let tree = s(p.root);
let t = link(tree.root, tree, p, ["/a", 11, 'd']);
expect(parser.serialize(t)).toEqual("/a/11/d(aux:c)");
});
it("should preserve route siblings when changing a aux route", () => {
let p = parser.parse("/a/11/b(c)");
let tree = s(p.root);
let t = link(tree.root, tree, p, ["/a", 11, 'aux:d']);
expect(parser.serialize(t)).toEqual("/a/11/b(aux:d)");
});
it('should update parameters', () => {
let p = parser.parse("/a;aa=11");
let tree = s(p.root);
let t = link(tree.root, tree, p, ["/a", {aa: 22, bb: 33}]);
expect(parser.serialize(t)).toEqual("/a;aa=22;bb=33");
});
it("should update relative subtree (when starts with ./)", () => {
let p = parser.parse("/a(ap)/c(cp)");
let c = p.firstChild(p.root);
let tree = s(c);
let t = link(tree.root, tree, p, ["./c2"]);
expect(parser.serialize(t)).toEqual("/a(aux:ap)/c2(aux:cp)");
});
it("should update relative subtree (when does not start with ./)", () => {
let p = parser.parse("/a(ap)/c(cp)");
let c = p.firstChild(p.root);
let tree = s(c);
let t = link(tree.root, tree, p, ["c2"]);
expect(parser.serialize(t)).toEqual("/a(aux:ap)/c2(aux:cp)");
});
it("should update relative subtree when the provided segment doesn't have url segments", () => {
let p = parser.parse("/a(ap)/c(cp)");
let c = p.firstChild(p.root);
let child = new RouteSegment([], null, null, null, null);
let root = new TreeNode<RouteSegment>(new RouteSegment([c], {}, null, null, null),
[new TreeNode<RouteSegment>(child, [])]);
let tree = new RouteTree(root);
let t = link(child, tree, p, ["./c2"]);
expect(parser.serialize(t)).toEqual("/a(aux:ap)/c2(aux:cp)");
});
});
示例6: describe
describe('validator', () => {
it('should run validator with the initial value', () => {
const c = new FormControl('value', Validators.required);
expect(c.valid).toEqual(true);
});
it('should rerun the validator when the value changes', () => {
const c = new FormControl('value', Validators.required);
c.setValue(null);
expect(c.valid).toEqual(false);
});
it('should support arrays of validator functions if passed', () => {
const c = new FormControl('value', [Validators.required, Validators.minLength(3)]);
c.setValue('a');
expect(c.valid).toEqual(false);
c.setValue('aaa');
expect(c.valid).toEqual(true);
});
it('should return errors', () => {
const c = new FormControl(null, Validators.required);
expect(c.errors).toEqual({'required': true});
});
it('should set single validator', () => {
const c = new FormControl(null);
expect(c.valid).toEqual(true);
c.setValidators(Validators.required);
c.setValue(null);
expect(c.valid).toEqual(false);
c.setValue('abc');
expect(c.valid).toEqual(true);
});
it('should set multiple validators from array', () => {
const c = new FormControl('');
expect(c.valid).toEqual(true);
c.setValidators([Validators.minLength(5), Validators.required]);
c.setValue('');
expect(c.valid).toEqual(false);
c.setValue('abc');
expect(c.valid).toEqual(false);
c.setValue('abcde');
expect(c.valid).toEqual(true);
});
it('should clear validators', () => {
const c = new FormControl('', Validators.required);
expect(c.valid).toEqual(false);
c.clearValidators();
expect(c.validator).toEqual(null);
c.setValue('');
expect(c.valid).toEqual(true);
});
it('should add after clearing', () => {
const c = new FormControl('', Validators.required);
expect(c.valid).toEqual(false);
c.clearValidators();
expect(c.validator).toEqual(null);
c.setValidators([Validators.required]);
expect(c.validator).not.toBe(null);
});
});
示例7: describe
describe('loadTemplate', () => {
describe('inline template', () => {
it('should store the template',
inject([AsyncTestCompleter, DirectiveNormalizer],
(async, normalizer: DirectiveNormalizer) => {
normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: 'a',
templateUrl: null,
styles: [],
styleUrls: ['test.css'],
baseUrl: 'package:some/module/a.js'
}))
.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 baseUrl',
inject([AsyncTestCompleter, DirectiveNormalizer],
(async, normalizer: DirectiveNormalizer) => {
normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: '',
templateUrl: null,
styles: [],
styleUrls: ['test.css'],
baseUrl: 'package:some/module/a.js'
}))
.then((template: CompileTemplateMetadata) => {
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
async.done();
});
}));
it('should resolve styles in the template against the baseUrl',
inject([AsyncTestCompleter, DirectiveNormalizer],
(async, normalizer: DirectiveNormalizer) => {
normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: '<style>@import test.css</style>',
templateUrl: null,
styles: [],
styleUrls: [],
baseUrl: 'package:some/module/a.js'
}))
.then((template: CompileTemplateMetadata) => {
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
async.done();
});
}));
});
describe('templateUrl', () => {
it('should load a template from a url that is resolved against baseUrl',
inject([AsyncTestCompleter, DirectiveNormalizer, XHR],
(async, 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'],
baseUrl: 'package:some/module/a.js'
}))
.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 baseUrl',
inject([AsyncTestCompleter, DirectiveNormalizer, XHR],
(async, 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'],
baseUrl: 'package:some/module/a.js'
}))
.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, normalizer: DirectiveNormalizer, xhr: MockXHR) => {
//.........这里部分代码省略.........
示例8: describe
describe('@Component.precompile', function() {
it('should resolve ComponentFactories from the same component',
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(MainComp).then((compFixture) => {
let mainComp: MainComp = compFixture.componentInstance;
expect(compFixture.debugElement.injector.get(ComponentFactoryResolver))
.toBe(mainComp.cfr);
var cf = mainComp.cfr.resolveComponentFactory(ChildComp);
expect(cf.componentType).toBe(ChildComp);
async.done();
});
}));
it('should resolve ComponentFactories via ANALYZE_FOR_PRECOMPILE',
inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
let compFixture = tcb.createSync(CompWithAnalyzePrecompileProvider);
let mainComp: CompWithAnalyzePrecompileProvider = compFixture.componentInstance;
let cfr: ComponentFactoryResolver =
compFixture.debugElement.injector.get(ComponentFactoryResolver);
expect(cfr.resolveComponentFactory(ChildComp).componentType).toBe(ChildComp);
expect(cfr.resolveComponentFactory(NestedChildComp).componentType).toBe(NestedChildComp);
}));
it('should be able to get a component form a parent component (view hiearchy)',
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideTemplate(MainComp, '<child></child>')
.createAsync(MainComp)
.then((compFixture) => {
let childCompEl = compFixture.debugElement.children[0];
let childComp: ChildComp = childCompEl.componentInstance;
// declared on ChildComp directly
expect(childComp.cfr.resolveComponentFactory(NestedChildComp).componentType)
.toBe(NestedChildComp);
// inherited from MainComp
expect(childComp.cfr.resolveComponentFactory(ChildComp).componentType)
.toBe(ChildComp);
async.done();
});
}));
it('should not be able to get components from a parent component (content hierarchy)',
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideTemplate(MainComp, '<child><nested></nested></child>')
.overrideTemplate(ChildComp, '<ng-content></ng-content>')
.createAsync(MainComp)
.then((compFixture) => {
let nestedChildCompEl = compFixture.debugElement.children[0].children[0];
let nestedChildComp: NestedChildComp = nestedChildCompEl.componentInstance;
expect(nestedChildComp.cfr.resolveComponentFactory(ChildComp).componentType)
.toBe(ChildComp);
expect(() => nestedChildComp.cfr.resolveComponentFactory(NestedChildComp))
.toThrow(new NoComponentFactoryError(NestedChildComp));
async.done();
});
}));
});
示例9: describe
describe('reflector_host', () => {
var context: MockContext;
var host: ts.CompilerHost;
var program: ts.Program;
var reflectorNestedGenDir: ReflectorHost;
var reflectorSiblingGenDir: ReflectorHost;
beforeEach(() => {
context = new MockContext('/tmp/src', clone(FILES));
host = new MockCompilerHost(context);
program = ts.createProgram(
['main.ts'], {
module: ts.ModuleKind.CommonJS,
},
host);
// Force a typecheck
let errors = program.getSemanticDiagnostics();
if (errors && errors.length) {
throw new Error('Expected no errors');
}
reflectorNestedGenDir = new ReflectorHost(
program, host, {
genDir: '/tmp/project/src/gen',
basePath: '/tmp/project/src',
skipMetadataEmit: false,
skipTemplateCodegen: false,
trace: false
},
context);
reflectorSiblingGenDir = new ReflectorHost(
program, host, {
genDir: '/tmp/project/gen',
basePath: '/tmp/project/src',
skipMetadataEmit: false,
skipTemplateCodegen: false,
trace: false
},
context);
});
describe('nestedGenDir', () => {
it('should import node_module from factory', () => {
expect(reflectorNestedGenDir.getImportPath(
'/tmp/project/src/gen/my.ngfactory.ts',
'/tmp/project/node_modules/@angular/core.d.ts'))
.toEqual('@angular/core');
});
it('should import factory from factory', () => {
expect(reflectorNestedGenDir.getImportPath(
'/tmp/project/src/my.ngfactory.ts', '/tmp/project/src/my.other.ngfactory.ts'))
.toEqual('./my.other.ngfactory');
expect(reflectorNestedGenDir.getImportPath(
'/tmp/project/src/a/my.ngfactory.ts', '/tmp/project/src/my.other.css.ts'))
.toEqual('../my.other.css');
expect(reflectorNestedGenDir.getImportPath(
'/tmp/project/src/my.ngfactory.ts', '/tmp/project/src/a/my.other.css.shim.ts'))
.toEqual('./a/my.other.css.shim');
});
it('should import application from factory', () => {
expect(reflectorNestedGenDir.getImportPath(
'/tmp/project/src/my.ngfactory.ts', '/tmp/project/src/my.other.ts'))
.toEqual('../my.other');
expect(reflectorNestedGenDir.getImportPath(
'/tmp/project/src/a/my.ngfactory.ts', '/tmp/project/src/my.other.ts'))
.toEqual('../../my.other');
expect(reflectorNestedGenDir.getImportPath(
'/tmp/project/src/my.ngfactory.ts', '/tmp/project/src/a/my.other.ts'))
.toEqual('../a/my.other');
});
});
describe('nestedGenDir', () => {
it('should import node_module from factory', () => {
expect(reflectorSiblingGenDir.getImportPath(
'/tmp/project/src/gen/my.ngfactory.ts',
'/tmp/project/node_modules/@angular/core.d.ts'))
.toEqual('@angular/core');
});
it('should import factory from factory', () => {
expect(reflectorSiblingGenDir.getImportPath(
'/tmp/project/src/my.ngfactory.ts', '/tmp/project/src/my.other.ngfactory.ts'))
.toEqual('./my.other.ngfactory');
expect(reflectorSiblingGenDir.getImportPath(
'/tmp/project/src/a/my.ngfactory.ts', '/tmp/project/src/my.other.css.ts'))
.toEqual('../my.other.css');
expect(reflectorSiblingGenDir.getImportPath(
'/tmp/project/src/my.ngfactory.ts', '/tmp/project/src/a/my.other.css.shim.ts'))
.toEqual('./a/my.other.css.shim');
});
it('should import application from factory', () => {
expect(reflectorSiblingGenDir.getImportPath(
'/tmp/project/src/my.ngfactory.ts', '/tmp/project/src/my.other.ts'))
.toEqual('./my.other');
expect(reflectorSiblingGenDir.getImportPath(
'/tmp/project/src/a/my.ngfactory.ts', '/tmp/project/src/my.other.ts'))
.toEqual('../my.other');
//.........这里部分代码省略.........
示例10: describe
describe('DatePipe', () => {
var date: Date;
var pipe: DatePipe;
// TODO: reactivate the disabled expectations once emulators are fixed in SauceLabs
// In some old versions of Chrome in Android emulators, time formatting returns dates in the
// timezone of the VM host,
// instead of the device timezone. Same symptoms as
// https://bugs.chromium.org/p/chromium/issues/detail?id=406382
// This happens locally and in SauceLabs, so some checks are disabled to avoid failures.
// Tracking issue: https://github.com/angular/angular/issues/11187
beforeEach(() => {
date = DateWrapper.create(2015, 6, 15, 9, 3, 1);
pipe = new DatePipe('en-US');
});
it('should be marked as pure',
() => { expect(new PipeResolver().resolve(DatePipe).pure).toEqual(true); });
describe('supports', () => {
it('should support date', () => { expect(() => pipe.transform(date)).not.toThrow(); });
it('should support int', () => { expect(() => pipe.transform(123456789)).not.toThrow(); });
it('should support numeric strings',
() => { expect(() => pipe.transform('123456789')).not.toThrow(); });
it('should support decimal strings',
() => { expect(() => pipe.transform('123456789.11')).not.toThrow(); });
it('should support ISO string',
() => { expect(() => pipe.transform('2015-06-15T21:43:11Z')).not.toThrow(); });
it('should not support other objects', () => {
expect(() => pipe.transform({})).toThrow();
expect(() => pipe.transform('')).toThrow();
});
});
describe('transform', () => {
it('should format each component correctly', () => {
expect(pipe.transform(date, 'y')).toEqual('2015');
expect(pipe.transform(date, 'yy')).toEqual('15');
expect(pipe.transform(date, 'M')).toEqual('6');
expect(pipe.transform(date, 'MM')).toEqual('06');
expect(pipe.transform(date, 'MMM')).toEqual('Jun');
expect(pipe.transform(date, 'MMMM')).toEqual('June');
expect(pipe.transform(date, 'd')).toEqual('15');
expect(pipe.transform(date, 'E')).toEqual('Mon');
expect(pipe.transform(date, 'EEEE')).toEqual('Monday');
if (!browserDetection.isOldChrome) {
expect(pipe.transform(date, 'h')).toEqual('9');
expect(pipe.transform(date, 'hh')).toEqual('09');
expect(pipe.transform(date, 'j')).toEqual('9 AM');
}
// IE and Edge can't format a date to minutes and seconds without hours
if (!browserDetection.isEdge && !browserDetection.isIE ||
!browserDetection.supportsNativeIntlApi) {
if (!browserDetection.isOldChrome) {
expect(pipe.transform(date, 'HH')).toEqual('09');
}
expect(pipe.transform(date, 'm')).toEqual('3');
expect(pipe.transform(date, 's')).toEqual('1');
expect(pipe.transform(date, 'mm')).toEqual('03');
expect(pipe.transform(date, 'ss')).toEqual('01');
}
expect(pipe.transform(date, 'Z')).toBeDefined();
});
it('should format common multi component patterns', () => {
expect(pipe.transform(date, 'E, M/d/y')).toEqual('Mon, 6/15/2015');
expect(pipe.transform(date, 'E, M/d')).toEqual('Mon, 6/15');
expect(pipe.transform(date, 'MMM d')).toEqual('Jun 15');
expect(pipe.transform(date, 'dd/MM/yyyy')).toEqual('15/06/2015');
expect(pipe.transform(date, 'MM/dd/yyyy')).toEqual('06/15/2015');
expect(pipe.transform(date, 'yMEd')).toEqual('20156Mon15');
expect(pipe.transform(date, 'MEd')).toEqual('6Mon15');
expect(pipe.transform(date, 'MMMd')).toEqual('Jun15');
expect(pipe.transform(date, 'yMMMMEEEEd')).toEqual('Monday, June 15, 2015');
// IE and Edge can't format a date to minutes and seconds without hours
if (!browserDetection.isEdge && !browserDetection.isIE ||
!browserDetection.supportsNativeIntlApi) {
expect(pipe.transform(date, 'ms')).toEqual('31');
}
if (!browserDetection.isOldChrome) {
expect(pipe.transform(date, 'jm')).toEqual('9:03 AM');
}
});
it('should format with pattern aliases', () => {
if (!browserDetection.isOldChrome) {
// IE and Edge do not add a coma after the year in these 2 cases
if ((browserDetection.isEdge || browserDetection.isIE) &&
browserDetection.supportsNativeIntlApi) {
expect(pipe.transform(date, 'medium')).toEqual('Jun 15, 2015 9:03:01 AM');
expect(pipe.transform(date, 'short')).toEqual('6/15/2015 9:03 AM');
} else {
expect(pipe.transform(date, 'medium')).toEqual('Jun 15, 2015, 9:03:01 AM');
expect(pipe.transform(date, 'short')).toEqual('6/15/2015, 9:03 AM');
}
}
//.........这里部分代码省略.........