Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Providing "entryComponents" for a TestBed

I have a component which receives a component class of component to dynamically create as a child.

let componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentToCreate); this.componentReference = this.target.createComponent(componentFactory); 

I'm trying to write a unit test and pass some TestComponent for it to create & render.

TestBed   .configureTestingModule(<any>{     declarations: [MyAwesomeDynamicComponentRenderer, TestHostComponent],     entryComponents: [TestComponent],   }); 

There is casting to "any" because configureTestingModule expects TestModuleMetadata which doesn't have entryComponents but I get error: "No component factory found for TestComponent".

How can I provide the entryComponents to a TestBed?

like image 379
Pavel Staselun Avatar asked Jan 05 '17 11:01

Pavel Staselun


People also ask

What is the use of entryComponents?

The entryComponents array is used to define only components that are not found in html and created dynamically. Angular requires this hint to find entry component and compile them.

What is entryComponents?

An entry component is any component that Angular loads imperatively, (which means you're not referencing it in the template), by type. You specify an entry component by bootstrapping it in an NgModule, or including it in a routing definition.


2 Answers

You can also do it into your test file directly if you want :

import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing'; // DO not forget to Import  TestBed.configureTestingModule({   declarations: [ MyDynamicComponent ], }).overrideModule(BrowserDynamicTestingModule, {   set: {     entryComponents: [ MyDynamicComponent ],   } }); 
like image 120
Alex Avatar answered Sep 17 '22 23:09

Alex


Okay, I figured it out. In the test you should define new module where you declare your mock component and specify it as an entryComponent too.

@NgModule({   declarations: [TestComponent],   entryComponents: [     TestComponent,   ] }) class TestModule {} 

And import it into TestBed

TestBed   .configureTestingModule({     declarations: [ValueComponent, TestHostComponent],     imports: [TestModule],   }); 

I hope it will help someone :]

like image 32
Pavel Staselun Avatar answered Sep 18 '22 23:09

Pavel Staselun