How to use configureTestingModule method in storybook-root

Best JavaScript code snippet using storybook-root

view_injector_integration_spec.ts

Source:view_injector_integration_spec.ts Github

copy

Full Screen

...203}204describe('View injector', () => {205 const TOKEN = new InjectionToken<string>('token');206 beforeEach(() => {207 TestBed.configureTestingModule({208 declarations: [TestComp],209 providers: [210 {provide: TOKEN, useValue: 'appService'},211 {provide: 'appService', useFactory: (v: string) => v, deps: [TOKEN]},212 ],213 });214 });215 describe('injection', () => {216 it('should instantiate directives that have no dependencies', () => {217 TestBed.configureTestingModule({declarations: [SimpleDirective]});218 const el = createComponent('<div simpleDirective>');219 expect(el.children[0].injector.get(SimpleDirective)).toBeAnInstanceOf(SimpleDirective);220 });221 it('should instantiate directives that depend on another directive', () => {222 TestBed.configureTestingModule({declarations: [SimpleDirective, NeedsDirective]});223 const el = createComponent('<div simpleDirective needsDirective>');224 const d = el.children[0].injector.get(NeedsDirective);225 expect(d).toBeAnInstanceOf(NeedsDirective);226 expect(d.dependency).toBeAnInstanceOf(SimpleDirective);227 });228 it('should support useValue with different values', () => {229 const el = createComponent('', [230 {provide: 'numLiteral', useValue: 0},231 {provide: 'boolLiteral', useValue: true},232 {provide: 'strLiteral', useValue: 'a'},233 {provide: 'null', useValue: null},234 {provide: 'array', useValue: [1]},235 {provide: 'map', useValue: {'a': 1}},236 {provide: 'instance', useValue: new TestValue('a')},237 {provide: 'nested', useValue: [{'a': [1]}, new TestValue('b')]},238 ]);239 expect(el.injector.get('numLiteral')).toBe(0);240 expect(el.injector.get('boolLiteral')).toBe(true);241 expect(el.injector.get('strLiteral')).toBe('a');242 expect(el.injector.get('null')).toBe(null);243 expect(el.injector.get('array')).toEqual([1]);244 expect(el.injector.get('map')).toEqual({'a': 1});245 expect(el.injector.get('instance')).toEqual(new TestValue('a'));246 expect(el.injector.get('nested')).toEqual([{'a': [1]}, new TestValue('b')]);247 });248 it('should instantiate providers that have dependencies with SkipSelf', () => {249 TestBed.configureTestingModule({declarations: [SimpleDirective, SomeOtherDirective]});250 TestBed.overrideDirective(251 SimpleDirective, {add: {providers: [{provide: 'injectable1', useValue: 'injectable1'}]}});252 TestBed.overrideDirective(SomeOtherDirective, {253 add: {254 providers: [255 {provide: 'injectable1', useValue: 'new-injectable1'}, {256 provide: 'injectable2',257 useFactory: (val: any) => `${val}-injectable2`,258 deps: [[new Inject('injectable1'), new SkipSelf()]]259 }260 ]261 }262 });263 const el = createComponent('<div simpleDirective><span someOtherDirective></span></div>');264 expect(el.children[0].children[0].injector.get('injectable2'))265 .toEqual('injectable1-injectable2');266 });267 it('should instantiate providers that have dependencies', () => {268 TestBed.configureTestingModule({declarations: [SimpleDirective]});269 const providers = [270 {provide: 'injectable1', useValue: 'injectable1'}, {271 provide: 'injectable2',272 useFactory: (val: any) => `${val}-injectable2`,273 deps: ['injectable1']274 }275 ];276 TestBed.overrideDirective(SimpleDirective, {add: {providers}});277 const el = createComponent('<div simpleDirective></div>');278 expect(el.children[0].injector.get('injectable2')).toEqual('injectable1-injectable2');279 });280 it('should instantiate viewProviders that have dependencies', () => {281 TestBed.configureTestingModule({declarations: [SimpleComponent]});282 const viewProviders = [283 {provide: 'injectable1', useValue: 'injectable1'}, {284 provide: 'injectable2',285 useFactory: (val: any) => `${val}-injectable2`,286 deps: ['injectable1']287 }288 ];289 TestBed.overrideComponent(SimpleComponent, {set: {viewProviders}});290 const el = createComponent('<div simpleComponent></div>');291 expect(el.children[0].injector.get('injectable2')).toEqual('injectable1-injectable2');292 });293 it('should instantiate components that depend on viewProviders providers', () => {294 TestBed.configureTestingModule({declarations: [NeedsServiceComponent]});295 TestBed.overrideComponent(296 NeedsServiceComponent, {set: {providers: [{provide: 'service', useValue: 'service'}]}});297 const el = createComponent('<div needsServiceComponent></div>');298 expect(el.children[0].injector.get(NeedsServiceComponent).service).toEqual('service');299 });300 it('should instantiate multi providers', () => {301 TestBed.configureTestingModule({declarations: [SimpleDirective]});302 const providers = [303 {provide: 'injectable1', useValue: 'injectable11', multi: true},304 {provide: 'injectable1', useValue: 'injectable12', multi: true}305 ];306 TestBed.overrideDirective(SimpleDirective, {set: {providers}});307 const el = createComponent('<div simpleDirective></div>');308 expect(el.children[0].injector.get('injectable1')).toEqual(['injectable11', 'injectable12']);309 });310 it('should instantiate providers lazily', () => {311 TestBed.configureTestingModule({declarations: [SimpleDirective]});312 let created = false;313 TestBed.overrideDirective(314 SimpleDirective,315 {set: {providers: [{provide: 'service', useFactory: () => created = true}]}});316 const el = createComponent('<div simpleDirective></div>');317 expect(created).toBe(false);318 el.children[0].injector.get('service');319 expect(created).toBe(true);320 });321 it('should provide undefined', () => {322 let factoryCounter = 0;323 const el = createComponent('', [{324 provide: 'token',325 useFactory: () => {326 factoryCounter++;327 return undefined;328 }329 }]);330 expect(el.injector.get('token')).toBeUndefined();331 expect(el.injector.get('token')).toBeUndefined();332 expect(factoryCounter).toBe(1);333 });334 describe('injecting lazy providers into an eager provider via Injector.get', () => {335 it('should inject providers that were declared before it', () => {336 @Component({337 template: '',338 providers: [339 {provide: 'lazy', useFactory: () => 'lazyValue'},340 {341 provide: 'eager',342 useFactory: (i: Injector) => `eagerValue: ${i.get('lazy')}`,343 deps: [Injector]344 },345 ]346 })347 class MyComp {348 // Component is eager, which makes all of its deps eager349 constructor(@Inject('eager') eager: any) {}350 }351 const ctx =352 TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(MyComp);353 expect(ctx.debugElement.injector.get('eager')).toBe('eagerValue: lazyValue');354 });355 it('should inject providers that were declared after it', () => {356 @Component({357 template: '',358 providers: [359 {360 provide: 'eager',361 useFactory: (i: Injector) => `eagerValue: ${i.get('lazy')}`,362 deps: [Injector]363 },364 {provide: 'lazy', useFactory: () => 'lazyValue'},365 ]366 })367 class MyComp {368 // Component is eager, which makes all of its deps eager369 constructor(@Inject('eager') eager: any) {}370 }371 const ctx =372 TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(MyComp);373 expect(ctx.debugElement.injector.get('eager')).toBe('eagerValue: lazyValue');374 });375 });376 describe('injecting eager providers into an eager provider via Injector.get', () => {377 it('should inject providers that were declared before it', () => {378 @Component({379 template: '',380 providers: [381 {provide: 'eager1', useFactory: () => 'v1'},382 {383 provide: 'eager2',384 useFactory: (i: Injector) => `v2: ${i.get('eager1')}`,385 deps: [Injector]386 },387 ]388 })389 class MyComp {390 // Component is eager, which makes all of its deps eager391 constructor(@Inject('eager1') eager1: any, @Inject('eager2') eager2: any) {}392 }393 const ctx =394 TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(MyComp);395 expect(ctx.debugElement.injector.get('eager2')).toBe('v2: v1');396 });397 it('should inject providers that were declared after it', () => {398 @Component({399 template: '',400 providers: [401 {402 provide: 'eager1',403 useFactory: (i: Injector) => `v1: ${i.get('eager2')}`,404 deps: [Injector]405 },406 {provide: 'eager2', useFactory: () => 'v2'},407 ]408 })409 class MyComp {410 // Component is eager, which makes all of its deps eager411 constructor(@Inject('eager1') eager1: any, @Inject('eager2') eager2: any) {}412 }413 const ctx =414 TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(MyComp);415 expect(ctx.debugElement.injector.get('eager1')).toBe('v1: v2');416 });417 });418 it('should allow injecting lazy providers via Injector.get from an eager provider that is declared earlier',419 () => {420 @Component({providers: [{provide: 'a', useFactory: () => 'aValue'}], template: ''})421 class SomeComponent {422 public a: string;423 constructor(injector: Injector) {424 this.a = injector.get('a');425 }426 }427 const comp = TestBed.configureTestingModule({declarations: [SomeComponent]})428 .createComponent(SomeComponent);429 expect(comp.componentInstance.a).toBe('aValue');430 });431 it('should support ngOnDestroy for lazy providers', () => {432 let created = false;433 let destroyed = false;434 class SomeInjectable {435 constructor() {436 created = true;437 }438 ngOnDestroy() {439 destroyed = true;440 }441 }442 @Component({providers: [SomeInjectable], template: ''})443 class SomeComp {444 }445 TestBed.configureTestingModule({declarations: [SomeComp]});446 let compRef = TestBed.createComponent(SomeComp).componentRef;447 expect(created).toBe(false);448 expect(destroyed).toBe(false);449 // no error if the provider was not yet created450 compRef.destroy();451 expect(created).toBe(false);452 expect(destroyed).toBe(false);453 compRef = TestBed.createComponent(SomeComp).componentRef;454 compRef.injector.get(SomeInjectable);455 expect(created).toBe(true);456 compRef.destroy();457 expect(destroyed).toBe(true);458 });459 it('should instantiate view providers lazily', () => {460 let created = false;461 TestBed.configureTestingModule({declarations: [SimpleComponent]});462 TestBed.overrideComponent(463 SimpleComponent,464 {set: {viewProviders: [{provide: 'service', useFactory: () => created = true}]}});465 const el = createComponent('<div simpleComponent></div>');466 expect(created).toBe(false);467 el.children[0].injector.get('service');468 expect(created).toBe(true);469 });470 it('should not instantiate other directives that depend on viewProviders providers (same element)',471 () => {472 TestBed.configureTestingModule({declarations: [SimpleComponent, NeedsService]});473 TestBed.overrideComponent(474 SimpleComponent, {set: {viewProviders: [{provide: 'service', useValue: 'service'}]}});475 expect(() => createComponent('<div simpleComponent needsService></div>'))476 .toThrowError(/No provider for service!/);477 });478 it('should not instantiate other directives that depend on viewProviders providers (child element)',479 () => {480 TestBed.configureTestingModule({declarations: [SimpleComponent, NeedsService]});481 TestBed.overrideComponent(482 SimpleComponent, {set: {viewProviders: [{provide: 'service', useValue: 'service'}]}});483 expect(() => createComponent('<div simpleComponent><div needsService></div></div>'))484 .toThrowError(/No provider for service!/);485 });486 it('should instantiate directives that depend on providers of other directives', () => {487 TestBed.configureTestingModule({declarations: [SimpleDirective, NeedsService]});488 TestBed.overrideDirective(489 SimpleDirective, {set: {providers: [{provide: 'service', useValue: 'parentService'}]}});490 const el = createComponent('<div simpleDirective><div needsService></div></div>');491 expect(el.children[0].children[0].injector.get(NeedsService).service)492 .toEqual('parentService');493 });494 it('should instantiate directives that depend on providers in a parent view', () => {495 TestBed.configureTestingModule({declarations: [SimpleDirective, NeedsService]});496 TestBed.overrideDirective(497 SimpleDirective, {set: {providers: [{provide: 'service', useValue: 'parentService'}]}});498 const el = createComponent(499 '<div simpleDirective><ng-container *ngIf="true"><div *ngIf="true" needsService></div></ng-container></div>');500 expect(el.children[0].children[0].injector.get(NeedsService).service)501 .toEqual('parentService');502 });503 it('should instantiate directives that depend on providers of a component', () => {504 TestBed.configureTestingModule({declarations: [SimpleComponent, NeedsService]});505 TestBed.overrideComponent(506 SimpleComponent, {set: {providers: [{provide: 'service', useValue: 'hostService'}]}});507 TestBed.overrideComponent(SimpleComponent, {set: {template: '<div needsService></div>'}});508 const el = createComponent('<div simpleComponent></div>');509 expect(el.children[0].children[0].injector.get(NeedsService).service).toEqual('hostService');510 });511 it('should instantiate directives that depend on view providers of a component', () => {512 TestBed.configureTestingModule({declarations: [SimpleComponent, NeedsService]});513 TestBed.overrideComponent(514 SimpleComponent, {set: {providers: [{provide: 'service', useValue: 'hostService'}]}});515 TestBed.overrideComponent(SimpleComponent, {set: {template: '<div needsService></div>'}});516 const el = createComponent('<div simpleComponent></div>');517 expect(el.children[0].children[0].injector.get(NeedsService).service).toEqual('hostService');518 });519 it('should instantiate directives in a root embedded view that depend on view providers of a component',520 () => {521 TestBed.configureTestingModule({declarations: [SimpleComponent, NeedsService]});522 TestBed.overrideComponent(523 SimpleComponent, {set: {providers: [{provide: 'service', useValue: 'hostService'}]}});524 TestBed.overrideComponent(525 SimpleComponent, {set: {template: '<div *ngIf="true" needsService></div>'}});526 const el = createComponent('<div simpleComponent></div>');527 expect(el.children[0].children[0].injector.get(NeedsService).service)528 .toEqual('hostService');529 });530 it('should instantiate directives that depend on instances in the app injector', () => {531 TestBed.configureTestingModule({declarations: [NeedsAppService]});532 const el = createComponent('<div needsAppService></div>');533 expect(el.children[0].injector.get(NeedsAppService).service).toEqual('appService');534 });535 obsoleteInIvy('This error is no longer generated by the compiler')536 .it('should not instantiate a directive with cyclic dependencies', () => {537 TestBed.configureTestingModule({declarations: [CycleDirective]});538 expect(() => createComponent('<div cycleDirective></div>'))539 .toThrowError(540 /Template parse errors:\nCannot instantiate cyclic dependency! CycleDirective \("\[ERROR ->\]<div cycleDirective><\/div>"\): .*TestComp.html@0:0/);541 });542 onlyInIvy('This error is generated by the runtime of Ivy')543 .it('should not instantiate a directive with cyclic dependencies', () => {544 TestBed.configureTestingModule({declarations: [CycleDirective]});545 expect(() => createComponent('<div cycleDirective></div>'))546 .toThrowError('Circular dep for CycleDirective');547 });548 obsoleteInIvy('This error is no longer generated by the compiler')549 .it('should not instantiate a directive in a view that has a host dependency on providers' +550 ' of the component',551 () => {552 TestBed.configureTestingModule(553 {declarations: [SimpleComponent, NeedsServiceFromHost]});554 TestBed.overrideComponent(555 SimpleComponent,556 {set: {providers: [{provide: 'service', useValue: 'hostService'}]}});557 TestBed.overrideComponent(558 SimpleComponent, {set: {template: '<div needsServiceFromHost><div>'}});559 expect(() => createComponent('<div simpleComponent></div>'))560 .toThrowError(561 /Template parse errors:\nNo provider for service \("\[ERROR ->\]<div needsServiceFromHost><div>"\): .*SimpleComponent.html@0:0/);562 });563 onlyInIvy('This error is generated by the runtime of Ivy')564 .it('should not instantiate a directive in a view that has a host dependency on providers' +565 ' of the component',566 () => {567 TestBed.configureTestingModule(568 {declarations: [SimpleComponent, NeedsServiceFromHost]});569 TestBed.overrideComponent(570 SimpleComponent,571 {set: {providers: [{provide: 'service', useValue: 'hostService'}]}});572 TestBed.overrideComponent(573 SimpleComponent, {set: {template: '<div needsServiceFromHost><div>'}});574 expect(() => createComponent('<div simpleComponent></div>'))575 .toThrowError('NodeInjector: NOT_FOUND [service]');576 });577 obsoleteInIvy('This error is no longer generated by the compiler')578 .it('should not instantiate a directive in a view that has a host dependency on providers' +579 ' of a decorator directive',580 () => {581 TestBed.configureTestingModule(582 {declarations: [SimpleComponent, SomeOtherDirective, NeedsServiceFromHost]});583 TestBed.overrideComponent(584 SimpleComponent,585 {set: {providers: [{provide: 'service', useValue: 'hostService'}]}});586 TestBed.overrideComponent(587 SimpleComponent, {set: {template: '<div needsServiceFromHost><div>'}});588 expect(() => createComponent('<div simpleComponent someOtherDirective></div>'))589 .toThrowError(590 /Template parse errors:\nNo provider for service \("\[ERROR ->\]<div needsServiceFromHost><div>"\): .*SimpleComponent.html@0:0/);591 });592 onlyInIvy('This error is generated by the runtime of Ivy')593 .it('should not instantiate a directive in a view that has a host dependency on providers' +594 ' of a decorator directive',595 () => {596 TestBed.configureTestingModule(597 {declarations: [SimpleComponent, SomeOtherDirective, NeedsServiceFromHost]});598 TestBed.overrideComponent(599 SimpleComponent,600 {set: {providers: [{provide: 'service', useValue: 'hostService'}]}});601 TestBed.overrideComponent(602 SimpleComponent, {set: {template: '<div needsServiceFromHost><div>'}});603 expect(() => createComponent('<div simpleComponent someOtherDirective></div>'))604 .toThrowError('NodeInjector: NOT_FOUND [service]');605 });606 obsoleteInIvy('This error is no longer generated by the compiler')607 .it('should not instantiate a directive in a view that has a self dependency on a parent directive',608 () => {609 TestBed.configureTestingModule(610 {declarations: [SimpleDirective, NeedsDirectiveFromSelf]});611 expect(612 () => createComponent(613 '<div simpleDirective><div needsDirectiveFromSelf></div></div>'))614 .toThrowError(615 /Template parse errors:\nNo provider for SimpleDirective \("<div simpleDirective>\[ERROR ->\]<div needsDirectiveFromSelf><\/div><\/div>"\): .*TestComp.html@0:21/);616 });617 onlyInIvy('This error is generated by the runtime of Ivy')618 .it('should not instantiate a directive in a view that has a self dependency on a parent directive',619 () => {620 TestBed.configureTestingModule(621 {declarations: [SimpleDirective, NeedsDirectiveFromSelf]});622 expect(623 () => createComponent(624 '<div simpleDirective><div needsDirectiveFromSelf></div></div>'))625 .toThrowError('NodeInjector: NOT_FOUND [SimpleDirective]');626 });627 it('should instantiate directives that depend on other directives', fakeAsync(() => {628 TestBed.configureTestingModule({declarations: [SimpleDirective, NeedsDirective]});629 const el = createComponent('<div simpleDirective><div needsDirective></div></div>');630 const d = el.children[0].children[0].injector.get(NeedsDirective);631 expect(d).toBeAnInstanceOf(NeedsDirective);632 expect(d.dependency).toBeAnInstanceOf(SimpleDirective);633 }));634 it('should throw when a dependency cannot be resolved', fakeAsync(() => {635 TestBed.configureTestingModule({declarations: [NeedsService]});636 expect(() => createComponent('<div needsService></div>'))637 .toThrowError(/No provider for service!/);638 }));639 it('should inject null when an optional dependency cannot be resolved', () => {640 TestBed.configureTestingModule({declarations: [OptionallyNeedsDirective]});641 const el = createComponent('<div optionallyNeedsDirective></div>');642 const d = el.children[0].injector.get(OptionallyNeedsDirective);643 expect(d.dependency).toBeNull();644 });645 it('should instantiate directives that depends on the host component', () => {646 TestBed.configureTestingModule({declarations: [SimpleComponent, NeedsComponentFromHost]});647 TestBed.overrideComponent(648 SimpleComponent, {set: {template: '<div needsComponentFromHost></div>'}});649 const el = createComponent('<div simpleComponent></div>');650 const d = el.children[0].children[0].injector.get(NeedsComponentFromHost);651 expect(d.dependency).toBeAnInstanceOf(SimpleComponent);652 });653 obsoleteInIvy('@Host() / @Self() no longer looks in module injector')654 .it('should instantiate host views for components that have a @Host dependency ', () => {655 TestBed.configureTestingModule({declarations: [NeedsHostAppService]});656 const el = createComponent('', [], NeedsHostAppService);657 expect(el.componentInstance.service).toEqual('appService');658 });659 obsoleteInIvy('This error is no longer generated by the compiler')660 .it('should not instantiate directives that depend on other directives on the host element',661 () => {662 TestBed.configureTestingModule(663 {declarations: [SimpleComponent, SimpleDirective, NeedsDirectiveFromHost]});664 TestBed.overrideComponent(665 SimpleComponent, {set: {template: '<div needsDirectiveFromHost></div>'}});666 expect(() => createComponent('<div simpleComponent simpleDirective></div>'))667 .toThrowError(668 /Template parse errors:\nNo provider for SimpleDirective \("\[ERROR ->\]<div needsDirectiveFromHost><\/div>"\): .*SimpleComponent.html@0:0/);669 });670 onlyInIvy('This error is generated by the runtime of Ivy')671 .it('should not instantiate directives that depend on other directives on the host element',672 () => {673 TestBed.configureTestingModule(674 {declarations: [SimpleComponent, SimpleDirective, NeedsDirectiveFromHost]});675 TestBed.overrideComponent(676 SimpleComponent, {set: {template: '<div needsDirectiveFromHost></div>'}});677 expect(() => createComponent('<div simpleComponent simpleDirective></div>'))678 .toThrowError('NodeInjector: NOT_FOUND [SimpleDirective]');679 });680 it('should allow to use the NgModule injector from a root ViewContainerRef.parentInjector',681 () => {682 @Component({template: ''})683 class MyComp {684 constructor(public vc: ViewContainerRef) {}685 }686 const compFixture = TestBed687 .configureTestingModule({688 declarations: [MyComp],689 providers: [{provide: 'someToken', useValue: 'someValue'}]690 })691 .createComponent(MyComp);692 expect(compFixture.componentInstance.vc.parentInjector.get('someToken')).toBe('someValue');693 });694 });695 describe('static attributes', () => {696 it('should be injectable', () => {697 TestBed.configureTestingModule({declarations: [NeedsAttribute]});698 const el = createComponent('<div needsAttribute type="text" title></div>');699 const needsAttribute = el.children[0].injector.get(NeedsAttribute);700 expect(needsAttribute.typeAttribute).toEqual('text');701 expect(needsAttribute.titleAttribute).toEqual('');702 expect(needsAttribute.fooAttribute).toEqual(null);703 });704 it('should be injectable without type annotation', () => {705 TestBed.configureTestingModule({declarations: [NeedsAttributeNoType]});706 const el = createComponent('<div needsAttributeNoType foo="bar"></div>');707 const needsAttribute = el.children[0].injector.get(NeedsAttributeNoType);708 expect(needsAttribute.fooAttribute).toEqual('bar');709 });710 });711 describe('refs', () => {712 it('should inject ElementRef', () => {713 TestBed.configureTestingModule({declarations: [NeedsElementRef]});714 const el = createComponent('<div needsElementRef></div>');715 expect(el.children[0].injector.get(NeedsElementRef).elementRef.nativeElement)716 .toBe(el.children[0].nativeElement);717 });718 it('should inject ChangeDetectorRef of the component\'s view into the component', () => {719 TestBed.configureTestingModule({declarations: [PushComponentNeedsChangeDetectorRef]});720 const cf = createComponentFixture('<div componentNeedsChangeDetectorRef></div>');721 cf.detectChanges();722 const compEl = cf.debugElement.children[0];723 const comp = compEl.injector.get(PushComponentNeedsChangeDetectorRef);724 comp.counter = 1;725 cf.detectChanges();726 expect(compEl.nativeElement).toHaveText('0');727 comp.changeDetectorRef.markForCheck();728 cf.detectChanges();729 expect(compEl.nativeElement).toHaveText('1');730 });731 it('should inject ChangeDetectorRef of the containing component into directives', () => {732 TestBed.configureTestingModule(733 {declarations: [PushComponentNeedsChangeDetectorRef, DirectiveNeedsChangeDetectorRef]});734 TestBed.overrideComponent(PushComponentNeedsChangeDetectorRef, {735 set: {736 template:737 '{{counter}}<div directiveNeedsChangeDetectorRef></div><div *ngIf="true" directiveNeedsChangeDetectorRef></div>'738 }739 });740 const cf = createComponentFixture('<div componentNeedsChangeDetectorRef></div>');741 cf.detectChanges();742 const compEl = cf.debugElement.children[0];743 const comp: PushComponentNeedsChangeDetectorRef =744 compEl.injector.get(PushComponentNeedsChangeDetectorRef);745 comp.counter = 1;746 cf.detectChanges();747 expect(compEl.nativeElement).toHaveText('0');748 /**749 * Compares two `ChangeDetectorRef` instances. The logic depends on the engine, as the750 * implementation details of `ViewRef` vary.751 */752 function _compareChangeDetectorRefs(a: ChangeDetectorRef, b: ChangeDetectorRef) {753 if (!ivyEnabled) {754 // View Engine case755 expect(a).toEqual(b);756 } else {757 // Ivy case758 expect((a as any)._lView).toEqual((b as any)._lView);759 expect((a as any).context).toEqual((b as any).context);760 }761 }762 _compareChangeDetectorRefs(763 compEl.children[0].injector.get(DirectiveNeedsChangeDetectorRef).changeDetectorRef,764 comp.changeDetectorRef);765 _compareChangeDetectorRefs(766 compEl.children[1].injector.get(DirectiveNeedsChangeDetectorRef).changeDetectorRef,767 comp.changeDetectorRef);768 comp.changeDetectorRef.markForCheck();769 cf.detectChanges();770 expect(compEl.nativeElement).toHaveText('1');771 });772 it('should inject ChangeDetectorRef of a same element component into a directive', () => {773 TestBed.configureTestingModule(774 {declarations: [PushComponentNeedsChangeDetectorRef, DirectiveNeedsChangeDetectorRef]});775 const cf = createComponentFixture(776 '<div componentNeedsChangeDetectorRef directiveNeedsChangeDetectorRef></div>');777 cf.detectChanges();778 const compEl = cf.debugElement.children[0];779 const comp = compEl.injector.get(PushComponentNeedsChangeDetectorRef);780 const dir = compEl.injector.get(DirectiveNeedsChangeDetectorRef);781 comp.counter = 1;782 cf.detectChanges();783 expect(compEl.nativeElement).toHaveText('0');784 dir.changeDetectorRef.markForCheck();785 cf.detectChanges();786 expect(compEl.nativeElement).toHaveText('1');787 });788 it(`should not inject ChangeDetectorRef of a parent element's component into a directive`, () => {789 TestBed790 .configureTestingModule({791 declarations: [PushComponentNeedsChangeDetectorRef, DirectiveNeedsChangeDetectorRef]792 })793 .overrideComponent(794 PushComponentNeedsChangeDetectorRef,795 {set: {template: '<ng-content></ng-content>{{counter}}'}});796 const cf = createComponentFixture(797 '<div componentNeedsChangeDetectorRef><div directiveNeedsChangeDetectorRef></div></div>');798 cf.detectChanges();799 const compEl = cf.debugElement.children[0];800 const comp = compEl.injector.get(PushComponentNeedsChangeDetectorRef);801 const dirEl = compEl.children[0];802 const dir = dirEl.injector.get(DirectiveNeedsChangeDetectorRef);803 comp.counter = 1;804 cf.detectChanges();805 expect(compEl.nativeElement).toHaveText('0');806 dir.changeDetectorRef.markForCheck();807 cf.detectChanges();808 expect(compEl.nativeElement).toHaveText('0');809 });810 it('should inject ViewContainerRef', () => {811 TestBed.configureTestingModule({declarations: [NeedsViewContainerRef]});812 const el = createComponent('<div needsViewContainerRef></div>');813 expect(el.children[0].injector.get(NeedsViewContainerRef).viewContainer.element.nativeElement)814 .toBe(el.children[0].nativeElement);815 });816 it('should inject ViewContainerRef', () => {817 @Component({template: ''})818 class TestComp {819 constructor(public vcr: ViewContainerRef) {}820 }821 @NgModule({822 declarations: [TestComp],823 entryComponents: [TestComp],824 })825 class TestModule {826 }827 const testInjector = <Injector>{828 get: (token: any, notFoundValue: any) =>829 token === 'someToken' ? 'someNewValue' : notFoundValue830 };831 const compFactory = TestBed.configureTestingModule({imports: [TestModule]})832 .get(ComponentFactoryResolver)833 .resolveComponentFactory(TestComp);834 const component = compFactory.create(testInjector);835 expect(component.instance.vcr.parentInjector.get('someToken')).toBe('someNewValue');836 });837 it('should inject TemplateRef', () => {838 TestBed.configureTestingModule({declarations: [NeedsViewContainerRef, NeedsTemplateRef]});839 const el =840 createComponent('<ng-template needsViewContainerRef needsTemplateRef></ng-template>');841 expect(el.childNodes[0].injector.get(NeedsTemplateRef).templateRef.elementRef)842 .toEqual(el.childNodes[0].injector.get(NeedsViewContainerRef).viewContainer.element);843 });844 it('should throw if there is no TemplateRef', () => {845 TestBed.configureTestingModule({declarations: [NeedsTemplateRef]});846 expect(() => createComponent('<div needsTemplateRef></div>'))847 .toThrowError(/No provider for TemplateRef!/);848 });849 it('should inject null if there is no TemplateRef when the dependency is optional', () => {850 TestBed.configureTestingModule({declarations: [OptionallyNeedsTemplateRef]});851 const el = createComponent('<div optionallyNeedsTemplateRef></div>');852 const instance = el.children[0].injector.get(OptionallyNeedsTemplateRef);853 expect(instance.templateRef).toBeNull();854 });855 });856 describe('pipes', () => {857 it('should instantiate pipes that have dependencies', () => {858 TestBed.configureTestingModule({declarations: [SimpleDirective, PipeNeedsService]});859 const el = createComponent(860 '<div [simpleDirective]="true | pipeNeedsService"></div>',861 [{provide: 'service', useValue: 'pipeService'}]);862 expect(el.children[0].injector.get(SimpleDirective).value.service).toEqual('pipeService');863 });864 it('should overwrite pipes with later entry in the pipes array', () => {865 TestBed.configureTestingModule(866 {declarations: [SimpleDirective, DuplicatePipe1, DuplicatePipe2]});867 const el = createComponent('<div [simpleDirective]="true | duplicatePipe"></div>');868 expect(el.children[0].injector.get(SimpleDirective).value).toBeAnInstanceOf(DuplicatePipe2);869 });870 it('should inject ChangeDetectorRef into pipes', () => {871 TestBed.configureTestingModule({872 declarations: [SimpleDirective, PipeNeedsChangeDetectorRef, DirectiveNeedsChangeDetectorRef]873 });874 const el = createComponent(875 '<div [simpleDirective]="true | pipeNeedsChangeDetectorRef" directiveNeedsChangeDetectorRef></div>');876 const cdRef = el.children[0].injector.get(DirectiveNeedsChangeDetectorRef).changeDetectorRef;877 expect(el.children[0].injector.get(SimpleDirective).value.changeDetectorRef).toEqual(cdRef);878 });879 modifiedInIvy('Pure pipes are instantiated differently in view engine and ivy')880 .it('should cache pure pipes', () => {881 TestBed.configureTestingModule({declarations: [SimpleDirective, PurePipe]});882 const el = createComponent(883 '<div [simpleDirective]="true | purePipe"></div><div [simpleDirective]="true | purePipe"></div>' +884 '<div *ngFor="let x of [1,2]" [simpleDirective]="true | purePipe"></div>');885 const purePipe1 = el.children[0].injector.get(SimpleDirective).value;886 const purePipe2 = el.children[1].injector.get(SimpleDirective).value;887 const purePipe3 = el.children[2].injector.get(SimpleDirective).value;888 const purePipe4 = el.children[3].injector.get(SimpleDirective).value;889 expect(purePipe1).toBeAnInstanceOf(PurePipe);890 expect(purePipe2).toBe(purePipe1);891 expect(purePipe3).toBe(purePipe1);892 expect(purePipe4).toBe(purePipe1);893 });894 it('should not cache impure pipes', () => {895 TestBed.configureTestingModule({declarations: [SimpleDirective, ImpurePipe]});896 const el = createComponent(897 '<div [simpleDirective]="true | impurePipe"></div><div [simpleDirective]="true | impurePipe"></div>' +898 '<div *ngFor="let x of [1,2]" [simpleDirective]="true | impurePipe"></div>');899 const impurePipe1 = el.children[0].injector.get(SimpleDirective).value;900 const impurePipe2 = el.children[1].injector.get(SimpleDirective).value;901 const impurePipe3 = el.children[2].injector.get(SimpleDirective).value;902 const impurePipe4 = el.children[3].injector.get(SimpleDirective).value;903 expect(impurePipe1).toBeAnInstanceOf(ImpurePipe);904 expect(impurePipe2).toBeAnInstanceOf(ImpurePipe);905 expect(impurePipe2).not.toBe(impurePipe1);906 expect(impurePipe3).toBeAnInstanceOf(ImpurePipe);907 expect(impurePipe3).not.toBe(impurePipe1);908 expect(impurePipe4).toBeAnInstanceOf(ImpurePipe);909 expect(impurePipe4).not.toBe(impurePipe1);910 });911 });912 describe('view destruction', () => {913 @Component({selector: 'some-component', template: ''})914 class SomeComponent {915 }916 @NgModule(917 {declarations: [SomeComponent], exports: [SomeComponent], entryComponents: [SomeComponent]})918 class SomeModule {919 }920 @Component({selector: 'listener-and-on-destroy', template: ''})921 class ComponentThatLoadsAnotherComponentThenMovesIt {922 constructor(923 private viewContainerRef: ViewContainerRef,924 private componentFactoryResolver: ComponentFactoryResolver) {}925 ngOnInit() {926 // Dynamically load some component.927 const componentFactory =928 this.componentFactoryResolver.resolveComponentFactory(SomeComponent);929 const componentRef =930 this.viewContainerRef.createComponent(componentFactory, this.viewContainerRef.length);931 // Manually move the loaded component to some arbitrary DOM node.932 const componentRootNode =933 (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;934 document.createElement('div').appendChild(componentRootNode);935 // Destroy the component we just moved to ensure that it does not error during936 // destruction.937 componentRef.destroy();938 }939 }940 it('should not error when destroying a component that has been moved in the DOM', () => {941 TestBed.configureTestingModule({942 imports: [SomeModule],943 declarations: [ComponentThatLoadsAnotherComponentThenMovesIt],944 });945 const fixture = createComponentFixture(`<listener-and-on-destroy></listener-and-on-destroy>`);946 fixture.detectChanges();947 // This test will fail if the ngOnInit of ComponentThatLoadsAnotherComponentThenMovesIt948 // throws an error.949 });950 });951});952class TestValue {953 constructor(public value: string) {}...

Full Screen

Full Screen

injection-tokens.spec.ts

Source:injection-tokens.spec.ts Github

copy

Full Screen

...11const PLATFORM_WORKER_APP_ID: string = 'browserWorkerApp';12const PLATFORM_WORKER_UI_ID: string = 'browserWorkerUi';13describe('SESSION_STORAGE_TOKEN', () => {14 it('should contain the sessionStorage object on platform browser', () => {15 TestBed.configureTestingModule({16 providers: [{ provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID }],17 });18 expect(TestBed.inject(SESSION_STORAGE_TOKEN)).toBe(sessionStorage);19 });20 it('should contain undefined on platform server', () => {21 TestBed.configureTestingModule({22 providers: [{ provide: PLATFORM_ID, useValue: PLATFORM_SERVER_ID }],23 });24 expect(TestBed.inject(SESSION_STORAGE_TOKEN)).toBeUndefined();25 });26 it('should contain undefined on platform worker app', () => {27 TestBed.configureTestingModule({28 providers: [{ provide: PLATFORM_ID, useValue: PLATFORM_WORKER_APP_ID }],29 });30 expect(TestBed.inject(SESSION_STORAGE_TOKEN)).toBeUndefined();31 });32 it('should contain undefined on platform worker ui', () => {33 TestBed.configureTestingModule({34 providers: [{ provide: PLATFORM_ID, useValue: PLATFORM_WORKER_UI_ID }],35 });36 expect(TestBed.inject(SESSION_STORAGE_TOKEN)).toBeUndefined();37 });38});39describe('LOCAL_STORAGE_TOKEN', () => {40 it('should contain the localStorage object on platform browser', () => {41 TestBed.configureTestingModule({42 providers: [{ provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID }],43 });44 expect(TestBed.inject(LOCAL_STORAGE_TOKEN)).toBe(localStorage);45 });46 it('should contain undefined on platform server', () => {47 TestBed.configureTestingModule({48 providers: [{ provide: PLATFORM_ID, useValue: PLATFORM_SERVER_ID }],49 });50 expect(TestBed.inject(LOCAL_STORAGE_TOKEN)).toBeUndefined();51 });52 it('should contain undefined on platform worker app', () => {53 TestBed.configureTestingModule({54 providers: [{ provide: PLATFORM_ID, useValue: PLATFORM_WORKER_APP_ID }],55 });56 expect(TestBed.inject(LOCAL_STORAGE_TOKEN)).toBeUndefined();57 });58 it('should contain undefined on platform worker ui', () => {59 TestBed.configureTestingModule({60 providers: [{ provide: PLATFORM_ID, useValue: PLATFORM_WORKER_UI_ID }],61 });62 expect(TestBed.inject(LOCAL_STORAGE_TOKEN)).toBeUndefined();63 });64});65describe('FORMS_MANAGER_STORAGE', () => {66 it('should contain the LOCAL_STORAGE_TOKEN by default', () => {67 TestBed.configureTestingModule({});68 expect(TestBed.inject(FORMS_MANAGER_STORAGE)).toBe(TestBed.inject(LOCAL_STORAGE_TOKEN));69 });70});71describe('FORMS_MANAGER_SESSION_STORAGE_PROVIDER', () => {72 it('should provide SESSION_STORAGE_TOKEN', () => {73 TestBed.configureTestingModule({ providers: [FORMS_MANAGER_SESSION_STORAGE_PROVIDER] });74 expect(TestBed.inject(FORMS_MANAGER_STORAGE)).toBe(TestBed.inject(SESSION_STORAGE_TOKEN));75 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { configure } from '@storybook/angular';2const req = require.context('../src/stories', true, /\.stories\.ts$/);3function loadStories() {4 req.keys().forEach(filename => req(filename));5}6configure(loadStories, module);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { configureTestingModule } from 'storybook-root';2configureTestingModule({3 imports: [TestModule],4});5import { configureTestingModule } from 'storybook-root';6configureTestingModule({7 imports: [TestModule],8});9import { configureTestingModule } from 'storybook-root';10configureTestingModule({11 imports: [TestModule],12});13import { configureTestingModule } from 'storybook-root';14configureTestingModule({15 imports: [TestModule],16});17import { configureTestingModule } from 'storybook-root';18configureTestingModule({19 imports: [TestModule],20});21import { configureTestingModule } from 'storybook-root';22configureTestingModule({23 imports: [TestModule],24});25import { configureTestingModule } from 'storybook-root';26configureTestingModule({27 imports: [TestModule],28});29import { configureTestingModule } from 'storybook-root';30configureTestingModule({31 imports: [TestModule],32});33import { configureTestingModule } from 'storybook-root';34configureTestingModule({35 imports: [TestModule],36});37import { configureTestingModule } from 'storybook-root';38configureTestingModule({39 imports: [TestModule],

Full Screen

Using AI Code Generation

copy

Full Screen

1import { configureTestingModule } from 'storybook-root-provider';2import { AppModule } from '../app/app.module';3import { AppComponent } from '../app/app.component';4import { Component } from '@angular/core';5import { Story, Meta } from '@storybook/angular/types-6-0';6import { AppModule } from '../app/app.module';7import { AppComponent } from '../app/app.component';8import { configureTestingModule } from 'storybook-root-provider';9import { RouterTestingModule } from '@angular/router/testing';10import { Router } from '@angular/router';11import { Location } from '@angular/common';12import { Router } from '@angular/router';13import { Location } from '@angular/common';14import { RouterTestingModule } from '@angular/router/testing';15export default {16 (story) => {17 const storyModuleMetadata = {18 imports: [19 RouterTestingModule.withRoutes([20 { path: 'test', component: AppComponent },21 };22 return configureTestingModule(storyModuleMetadata)(story);23 },24} as Meta;25const Template: Story<AppComponent> = (args: AppComponent) => ({26});27export const RouterTest = Template.bind({});28RouterTest.args = {29};30 (story) => {31 const storyModuleMetadata = {32 imports: [33 RouterTestingModule.withRoutes([34 { path: 'test', component: AppComponent },35 };36 return configureTestingModule(storyModuleMetadata)(story);37 },38];39import { Component } from '@angular/core';40import { Router } from '@angular/router';41import { Location } from '@angular/common';42@Component({43})44export class AppComponent {45 title = 'app';46 constructor(private router: Router, private location: Location) {}47 navigate() {48 this.router.navigate(['test']);49 }50 back() {51 this.location.back();52 }53}54 <button (click)="navigate()">Navigate</button>55 <button (click)="back()">Back</button>56import { TestBed, async } from '@angular/core

Full Screen

Using AI Code Generation

copy

Full Screen

1import { configureTestingModule } from 'storybook-root';2import { TestBed } from '@angular/core/testing';3import { MockComponent } from 'ng-mocks';4import { MyComponent } from './my-component';5import { MyOtherComponent } from './my-other-component';6import { MyService } from './my-service';7import { MyPipe } from './my-pipe';8import { MyDirective } from './my-directive';9import { MyModule } from './my-module';10import { MyPipeModule } from './my-pipe-module';11describe('MyComponent', () => {12 beforeEach(() => {13 configureTestingModule({14 MockComponent(MyOtherComponent),15 MockComponent({ selector: 'my-selector' }),16 MockComponent({ selector: 'my-selector', inputs: ['myInput'] }),17 { provide: MyService, useValue: {} },18 { provide: MyService, useClass: MyService },19 { provide: MyService, useFactory: () => {} },20 imports: [MyModule, MyPipeModule, MockModule(MyModule)],21 });22 });23 it('should work', () => {24 const fixture = TestBed.createComponent(MyComponent);25 const component = fixture.componentInstance;26 expect(component).toBeDefined();27 });28});29import { Component, Input } from '@angular/core';30import { MyOtherComponent } from './my-other-component';31import { MyService } from './my-service';32import { MyPipe } from './my-pipe';33import { MyDirective } from './my-directive';34import { MyModule } from './my-module';35@Component({36 <my-other-component [myInput]="myInput" (myOutput)="myOutput($event)"></my-other-component>

Full Screen

Using AI Code Generation

copy

Full Screen

1import { configureTestingModule } from 'storybook-root';2configureTestingModule({3 imports: [MyModule]4});5import { configureTestingModule } from '@storybook/angular';6export function configureTestingModule(config) {7 configureTestingModule(config);8}9import { configureTestingModule } from 'storybook-root';10configureTestingModule({11 imports: [MyModule]12});13import { configureTestingModule } from '@storybook/angular';14export function configureTestingModule(config) {15 configureTestingModule(config);16}17import { configureTestingModule } from 'storybook-root';18configureTestingModule({19 imports: [MyModule]20});21import { configureTestingModule } from '@storybook/angular';22export function configureTestingModule(config) {23 configureTestingModule(config);24}25import { configureTestingModule } from 'storybook-root';26configureTestingModule({27 imports: [MyModule]28});29import { configureTestingModule } from '@storybook/angular';30export function configureTestingModule(config) {31 configureTestingModule(config);32}33import { configureTestingModule } from 'storybook-root';34configureTestingModule({35 imports: [MyModule]36});37import { configureTestingModule } from '@storybook/angular';38export function configureTestingModule(config) {39 configureTestingModule(config);40}41import { configureTestingModule } from 'storybook-root';42configureTestingModule({43 imports: [MyModule]44});45import { configureTestingModule } from '@storybook/angular';46export function configureTestingModule(config) {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { configureTestingModule } from './storybook-root';2export default {3};4export const MyComponentStory = () => configureTestingModule(MyComponent, {5 props: { ... }6});7import { configure, addDecorator } from '@storybook/angular';8import { withKnobs } from '@storybook/addon-knobs';9import { withA11y } from '@storybook/addon-a11y';10import { withConsole } from '@storybook/addon-console';11import { withPerformance } from 'storybook-addon-performance';12import { withTests } from '@storybook/addon-jest';13import { setConsoleOptions } from '@storybook/addon-console';14import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport';15import { addParameters } from '@storybook/angular';16import { INITIAL_VIEWPORTS as INITIAL_VIEWPORTS_ANGULAR } from '@storybook/addon-viewport';17import { BrowserAnimationsModule } from '@angular/platform-browser/animations';18import { HttpClientModule } from '@angular/common/http';19import { FormsModule, ReactiveFormsModule } from '@angular/forms';20const req = require.context('../projects', true, /\.stories\.ts$/);21function loadStories() {22 req.keys().forEach(filename => req(filename));23}24addParameters({25 viewport: {26 viewports: {27 }28 }29});30addDecorator(withKnobs);31addDecorator(withA11y);32addDecorator(withPerformance);33addDecorator(34 withConsole({35 })36);37setConsoleOptions({38});39configure(loadStories, module);40export function configureTestingModule<T>(

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful