[英]How test an Angular (v11) component that loads components dynamically
在我的代码中,我遵循 Angular v11 指南
@Directive({
selector: '[stepHostContent]',
})
export class StepHostContentDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
@Component({
selector: 'app-dialog-wizard',
templateUrl: './dialog-wizard.component.html',
styleUrls: ['./dialog-wizard.component.scss']
})
export class DialogWizardComponent implements OnInit, OnDestroy {
@ViewChild(StepHostContentDirective, { static: true }) stepHostContent: StepHostContentDirective;
constructor(
public readonly dialog: MatDialogRef<DialogJobsWizardComponent>,
@Inject(MAT_DIALOG_DATA) public readonly data: { theme: string, title: string },
public readonly componentFactoryResolver: ComponentFactoryResolver
) { }
...
private loadStepContentComponent(componentToLoad: Type<any>): void {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentToLoad);
const viewContainerRef = this.stepHostContent.viewContainerRef;
viewContainerRef.clear();
viewContainerRef.createComponent(componentFactory);
}
我的单元测试
describe('DialogWizardComponent', () => {
let component: DialogWizardComponent;
let fixture: ComponentFixture<DialogWizardComponent>;
let componentFactoryResolverSpy = jasmine.createSpyObj<ComponentFactoryResolver>('ComponentFactoryResolver', ['resolveComponentFactory'])
beforeEach(async () => {
componentFactoryResolverSpy = spyComponentFactoryResolverSpy();
await TestBed.configureTestingModule({
declarations: [
DialogsWizardComponent,
MockComponent(DialogBaseComponent),
MockComponent(StepTestAComponent),
MockComponent(StepTestBComponent),
StepHostContentDirective
],
providers: [
{ provide: MatDialogRef, useValue: { close: () => {} } },
{ provide: MAT_DIALOG_DATA, useValue: { theme: 'dark', title: 'Title' } },
{ provide: ComponentFactoryResolver, useValue: componentFactoryResolverSpy },
],
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(DialogWizardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
错误说
Cannot read properties of undefined (reading 'ngModule')
viewContainerRef.createComponent(componentFactory);
您需要模拟 ViewContainerRef。
我修复了它,从提供者那里删除了ComponentFactoryResolver ,并且它起作用了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.