Angular - Testing - Cannot initialize sub component

67 Views Asked by At

I am trying to test a sub component that extends a base component. SubComponent overrides ngOnInit() from parent component, whereas Base comp contains some logic inside ngOnit and ngOnDestroy methods. The error I am getting is the following

component threw errors during cleanup

Could anyone address how I can test the sub component in isolation and initialize it properly?

SubComponent:

@Component({
  selector: '',
  templateUrl: '',
})
export class SubComponent
  extends BaseComponent<any>
  implements OnInit, AfterViewInit
{

  constructor(
    protected override service1: Service1<any>,
    protected override service2: Service2,
  ) {
    super(service1, service2, true);
  }

  override ngOnInit(): void {
    super.ngOnInit();
  }
}

BaseComponent:

@Component({
  selector: 'base',
  standalone: true,
  template: '',
})
export class BaseDialogComponent<T> implements OnInit, OnDestroy {
  

  constructor(
    protected service1: Service1<T>,
    protected service2: Service2,
    @Inject(DIALOG_CLOSING_CONFIG) dialogClosingConfig: boolean
  ) {
    this.enableDialogClosing = dialogClosingConfig;
  }

  @HostListener('window:popstate', ['$event'])
  onPopState(event: any) {
    .....
  }

  ngOnInit() {
    ....
  }

  ngOnDestroy() {
    this.service2.something();
  }
}

SubComponent.spec

describe('SubComponent', () => {
  let component: SubComponent;
  let fixture: ComponentFixture<SubComponent>;
  let someSubComponentService: SubComponentService;
  let subComponentServiceStub: Partial<any>;

  const createComponent = () => {
    fixture = TestBed.createComponent(SubComponent);
    fixture.detectChanges();
    return fixture;
  };

  beforeEach(async () => {
    subComponentServiceStub= {
      initialize: () => {},
    };

    await TestBed.configureTestingModule({
      imports: [TestModule],
      declarations: [SubComponent],
      providers: [
        {
          provide: SubComponentService,
          useValue: subComponentServiceStub,
        },
      ],
    }).compileComponents();

    component = createComponent().componentInstance;

    someSubComponentService= TestBed.inject(
      SubComponentService
    );
    spyOn(someSubComponentService, 'initialize');    
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });  
});
1

There are 1 best solutions below

0
On

Actually, the problem was caused by some dependent service action ('service2.something()') defined inside ngOnDestroy() of base component. After providing this service to testbed module, the problems is gone and the component is initialized corrently.