Testing Angular component with unsubscribe Error during cleanup of component

后端 未结 10 1777
梦毁少年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:06

    As explained by @randomPoison, the error is triggered when the component that uses unsubscribe is not initialised. However, calling fixture.detectChanges() is a solution for when the error is in the spec file of the respective component.

    But we might also be dealing with a FooComponent that creates BarComponent and BarComponent uses unsubscribe in its ngOnDestroy. Proper mocking must be done.

    I'd suggest a different approach to the subscription cleanup, one that is declarative and won't trigger such problems. Here's an example:

    export class BazComponent implements OnInit, OnDestroy {
      private unsubscribe$ = new Subject();
    
      ngOnInit(): void {
        someObservable$
          .pipe(takeUntil(this.unsubscribe$))
          .subscribe(...);
      }
    
      ngOnDestroy(): void {
        this.unsubscribe$.next();
        this.unsubscribe$.complete();
      }
    }
    

    More on this approach here

提交回复
热议问题