Testing Angular component with unsubscribe Error during cleanup of component

后端 未结 10 1655
梦毁少年i
梦毁少年i 2021-01-30 10:37

I\'m testing a component which subscribe router params. Every test pass and everything works fine. But if I look in the console, I can see an error:

Error

10条回答
  •  [愿得一人]
    2021-01-30 11:11

    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.

提交回复
热议问题