Testing Angular component with unsubscribe Error during cleanup of component

Solution 1:

The "Error during component cleanup" error message happens because when ngOnDestroy() is called, this.routeSubscription is undefined. This happens because ngOnInit() was never invoked, meaning that you never subscribed to the route. As described in the Angular testing tutorial, the component isn't initialized fully until you call fixture.detectChanges() the first time.

Therefore, the correct solution is to add fixture.detectChanges() to your beforeEach() block right after the createComponent is called. It can be added any time after you create the fixture. Doing so will ensure that the component is fully initialized, that way component cleanup will also behave as expected.

Solution 2:

You need to refactor your method ngOnDestroy as below :

ngOnDestroy() {
  if ( this.routeSubscription)
    this.routeSubscription.unsubscribe();
}

Solution 3:

In my case destroying the component after each test solved the problem. So you could try adding this to your describe function:

afterEach(() => {
  fixture.destroy();
})

Solution 4:

So my situation was similar, but not exactly the same: I'm just putting this here in case someone else finds it helpful. When unit testing with Jamine/Karma I was getting

 'ERROR: 'Error during cleanup of component','

It turns out that was because I wasn't properly handling my observables, and they didn't have an error function on them. So the fix was adding an error function:

this.entityService.subscribe((items) => {
      ///Do work
},
  error => {
    this.errorEventBus.throw(error);
  });

Solution 5:

I'm in a similar situation where I want to test a function in my component outside the context of the component itself.

This is what worked for me:

afterEach(() => {
  spyOn(component, 'ngOnDestroy').and.callFake(() => { });
  fixture.destroy();
});