I dynamically create components using ComponentFactoryResolver and also dynamically pass them using ReflectiveInjector.
It looks like
@ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef; let inputProviders = [{ provide: 'injectedInput', useValue: inputValue }]; let resolvedInputs = ReflectiveInjector.resolve(inputProviders); let injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.container.parentInjector); let factory = componentInfo.factory.resolveComponentFactory(componentInfo.component); let component = factory.create(injector); this.container.insert(component.hostView);
Then the dynamically created component is as follows:
import {Component, Injector} from '@angular/core'; @Component({ selector: 'mycomponent' }) export class MyComponent { private id: string; constructor(private injector: Injector) { this.id = injector.get('injectedInput'); } }
I am trying to write unit tests for this component that uses the main Injector module. I get the following error:
Error: no provider for injectedInput!
My spec file looks like this:
import { MyComponent } from 'here'; describe('MyComponent', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ MyComponent ] }); }); let component: MyComponent; beforeEach(inject([RigTransferSpeedPeriodComponent], _component => { component = _component; })); {...my tests...} });
I tried a bunch of things and searched everywhere, but could not find those who had done this before.
Any idea?
Thanks a lot!
Philip
source share