-1

I am unable to unsubscribe in my tests. Anyone else having this problem?? (am I doing anything wrong?)

Basic test:

describe('ngOnDestroy()', () => {
  it('should unsubscribe if isLoggedInSub is defined', async(() => {
    comp.ngOnInit();
    fixture.detectChanges();
    comp.ngOnDestroy();
    fixture.detectChanges();
    expect(comp.isLoggedInSub).not.toBeDefined();
  }));
});

console error:

Uncaught Expected Subscriber({ closed: true, _parent: null, _parents: null, _subscriptions: null, syncErrorValue: null, syncErrorThrown: false, syncErrorThrowable: false, isStopped: true, destination: SafeSubscriber({ closed: false, _parent: null, _parents: null, _subscriptions: null, syncErrorValue: null, syncErrorThrown: false, syncErrorThrowable: false, isStopped: false, destination: Object({ closed: true, next: Function, error: Function, complete: Function }), _parentSubscriber: <circular reference: Object>, _context: <circular reference: Object>, _next: Function, _error: undefined, _complete: undefined }) }) not to be defined.
at Object.testing_3.async
cuznerdexter
  • 586
  • 5
  • 21
  • 1
    How are you creating `isLoggedInSub`? What does your `ngOnDestroy` method look like? – vince Dec 13 '17 at 15:11
  • `isLoggedInSub: Subscription;` `isLoggedInSub = someObservableFunction.subscribe(() => {});` `ngOnDestroy() { isLoggedInSub.unsubscribe() }` – cuznerdexter Jan 05 '18 at 12:14

1 Answers1

0

if you have a subject and you are directly trying to unsubscribe in any of the above methods then we face this kind of errors. Example :

//AppComponent.ts

export class AppComponent implements OnDestroy{
 appSubject:new Subject();
 appSubject.subscribe(()=>...)
 ngOnDestroy() {
   appSubject.unsubscribe(); // If your subject is passing the next value from a 
                         different component
 }
}

This would usually cause this error as another component has a reference to the Subject.

The better way to do it would be

export class AppComponent implements OnDestroy{
 appSubject:new Subject();
 $subjectSubscription:Subscription = appSubject.subscribe(()=>...)
 ngOnDestroy() {
   $subjectSubscription.unsubscribe();
 }
}