angulartesting

Angular testing - Do you have to import tested component upon calling configureTestingModule


See examples here: https://angular.dev/guide/testing/components-scenarios, they all have imports: [BannerComponent]. Is it necessary? Tests seem to run fine without it. I am assuming that the component is standalone

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [BannerComponent], // Can this line be deleted?
    });
    fixture = TestBed.createComponent(BannerComponent);
    component = fixture.componentInstance;
    h1 = fixture.nativeElement.querySelector('h1');
  });

Solution

  • Imports are only necessary if the component is not standalone.

    If you read this example as being v19+, where standalone is implicit and doesn't require standalone: true anymore, then the following is enough.

    beforeEach(() => {
      fixture = TestBed.createComponent(BannerComponent);
      component = fixture.componentInstance;
      h1 = fixture.nativeElement.querySelector('h1');
    });