Home > Blockchain >  How test an Angular (v11) component that loads components dynamically
How test an Angular (v11) component that loads components dynamically

Time:02-23

In my code I'm following Angular v11 guide for that

@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);
 }

My unit test

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();
  });

the error says

Cannot read properties of undefined (reading 'ngModule') pointing to this line viewContainerRef.createComponent(componentFactory);

CodePudding user response:

You need to mock ViewContainerRef.

https://angular.io/guide/testing-components-basics

CodePudding user response:

I fixed it removing the ComponentFactoryResolver from providers, and it worked

  • Related