我正在努力为这段代码编写单元测试:
export class mycomp{
currentComponent: any;
@ViewChild('modal', { read: ViewContainerRef }) modal: ViewContainerRef;
@Input() set componentData(data: any) {
if (!data) {
return;
}
const inputProviders = Object.keys(data.inputs).map((inputName) => {
return {provide: inputName, useValue: data.inputs[inputName]};
});
const resolvedInputs = ReflectiveInjector.resolve(inputProviders);
const injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.modal.parentInjector);
const factory = this.resolver.resolveComponentFactory(data.component);
const component = factory.create(injector);
this.modal.insert(component.hostView);
if (this.currentComponent) {
this.currentComponent.destroy();
}
this.currentComponent = component;
}
constructor(private resolver: ComponentFactoryResolver) {
}
}
我的单元测试是:
beforeEach(() => {
const injector = ReflectiveInjector.resolveAndCreate([
mycomp,
]);
comp = injector.get(mycomp);
});
describe('DataTableComponent: Isolated', () => {
const data = {component: modal, inputs: 'string'};
beforeEach(() => {
const factory = (comp as any).resolver.resolveComponentFactory(modal);
comp.moda.createComponent(factory);
});
describe('componentData()', () => {
it('should call ', () => {
comp.componentData = data;
});
});
});
如果我尝试创建组件,我得到的是:TypeError:无法读取未定义的属性“createComponent”
当我不这样做时,通过删除beforeEach,我得到:无法读取未定义的属性'parentInjector'
我该如何测试?