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
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