我正在尝试测试动态组件创建代码。我从组件ts文件中分离了代码,并投入使用。这样我就可以在所有模块中使用相同的代码。 我试图初始化viewContainerRef
import { ComponentFactoryResolver, Injectable } from '@angular/core';
import { DynamicComponentDirective } from '../directive/dynamic-component.directive';
import { AddComponent, HandleOverlayEventEmitter } from '../models/load-component.model';
@Injectable({
providedIn: 'root'
})
export class LoadComponentService {
componentRef: any;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
loadComponent(modalComponent: HandleOverlayEventEmitter, addComponent: DynamicComponentDirective): void {
const adItem = new AddComponent(modalComponent.modalName, modalComponent.data);
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);
const viewContainerRef = addComponent.viewContainerRef;
viewContainerRef.clear();
this.componentRef = viewContainerRef.createComponent(componentFactory);
this.componentRef.instance.data = adItem.data;
}
destroyComponent(): void {
this.componentRef.destroy();
}
}
上述服务的测试用例。当我尝试执行loadComponent方法时,我没有获取ViewContainerRef的实例。规格在
处失败 **viewContainerRef.clear();**
import { CommonModule } from '@angular/common';
import { Component, CUSTOM_ELEMENTS_SCHEMA, NgModule, ViewChild, ViewContainerRef, ApplicationRef } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { LoadComponentService } from './load-component.service';
import { DynamicComponentDirective } from '../directive/dynamic-component.directive';
@Component({
template: `
<test-comp datacloud-ui-dynamic-component></test-comp>
`
})
class TestComponent {
// @ViewChild(DynamicComponentDirective) dynamicComponentDirective: DynamicComponentDirective;
constructor(public viewContainerRef: ViewContainerRef) {}
}
@NgModule({
imports: [
CommonModule
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
declarations: [TestComponent],
entryComponents: [TestComponent],
exports: [TestComponent]
})
class TestModule { }
describe('LoadComponentService', () => {
let loadComponentService: LoadComponentService;
let viewContainerRef: ViewContainerRef;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TestModule],
declarations: [],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
});
loadComponentService = TestBed.get(LoadComponentService);
});
beforeEach(() => {
const appRef = TestBed.get(ApplicationRef) as ApplicationRef;
const fixture = TestBed.createComponent(TestComponent);
appRef.components.push(fixture.componentRef);
const de = fixture.debugElement;
fixture.detectChanges();
});
it('should be created', () => {
expect(loadComponentService).toBeTruthy();
});
it('loadComponent, should be created', () => {
const modalCompoent = {
modalName: TestComponent,
data: {}
};
const dynamicComponentDirective= new DynamicComponentDirective(viewContainerRef);
loadComponentService.loadComponent(modalCompoent, dynamicComponentDirective);
expect(loadComponentService.loadComponent).toBeTruthy();
});
});
预期:测试用例应该运行时没有错误。
实际:无法读取未定义的属性“清除”