【发布时间】:2017-03-18 10:53:17
【问题描述】:
我正在使用 ComponentFactoryResolver 动态创建组件,并使用 ReflectiveInjector 动态地传递它们的输入。
这个好像
@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);
那么动态创建的组件是这样的
import {Component, Injector} from '@angular/core';
@Component({
selector: 'mycomponent'
})
export class MyComponent {
private id: string;
constructor(private injector: Injector) {
this.id = injector.get('injectedInput');
}
}
我正在尝试为使用核心 Injector 模块的组件编写单元测试。我收到以下错误:
错误:没有注入输入的提供者!
我的规范文件如下所示:
import { MyComponent } from 'here';
describe('MyComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
MyComponent
]
});
});
let component: MyComponent;
beforeEach(inject([RigTransferSpeedPeriodComponent], _component => {
component = _component;
}));
{...my tests...}
});
我尝试了很多东西并到处搜索,但找不到以前这样做过的人。
有什么想法吗?
非常感谢!
菲利普
【问题讨论】:
-
不明白你为什么要做这一切......但对我来说,看起来你的 parentInjector 创建了组件。所以组件本身也使用了 parentInjector,而 parentInjector 不知道注入的Input。也许你应该描述你的意图,也许还有另一种解决方法,而不是重新连接整个注入逻辑
标签: unit-testing angular