[英]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.