Testing Angular component with unsubscribe Error during cleanup of component

混江龙づ霸主 提交于 2019-12-02 16:13:16

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.

You need to refactor your method ngOnDestroy as below :

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

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

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

Adding to @David Brown's response the code below is what worked for me.

      .subscribe(res => {
          ...
        },
        error => Observable.throw(error)
      )

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

You have to do 2 things, to solve this error.

1- add fixture.detectChanges(); in beforeEach()
2 - you need to add below, so that component can be clear.

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

Well in my case the error was in the template. There was error in the child component ngDestroy ,which wasn't getting destroyed as i was trying to set readonly property. It would be worth your time checking your child components whether they are getting destroyed properly.

For me what fixed this error was inside of my component's ngOnDestroy, I wrapped my store dispatch and my unsubscribe in a try catch.

ngOnDestroy(): void {
 try {
  this.store.dispatch(new foo.Bar(this.testThing()));
  if(this.fooBarSubscription) {
   this.fooBarSubscription.unsubscribe();
  }
 } catch (error) {
   this.store.dispatch(new foo.Bar(this.testThing()));
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!