Search code examples
javascriptangulartypescriptsubscriptionunsubscribe

How to test that I have unsubscribed using ngx-auto-unsubscribe?


Is there a way in which I can write a unit test to check whether I have unsubscribed successfully from my Observable subscription?

I am using ngx-auto-unsubscribe.

example:

@AutoUnsubscribe()
@Component
// Template and style urls

export class MyComp implements OnInit, OnDestroy {

   mySub: Subscription;

   constructor(private myService: MyService) { }

   ngOnInit() {
      this.myService.doSomething.subscribe(res => {
         console.log(res);
      })
   }

   ngOnDestroy() {
     // Only used for AOT (ahead of time) compilation
   }
}

Solution

  • Yes there's a way (even though I don't think it's necessary to test that).

    I'm not going to write the whole test for you but here's the logic:

    • Create a parent component (let's call it MockComponent) in your test with a basic ngIf condition to display your MyComp or not
    • Mock the observable from your service using another observable that you built like that:

    .

    const obsCleanUpFunction = jasmine.createSpy();
    
    const obs$ = new Observable(observer => {
      //following will be called when/if the observable if completed
      return obsCleanUpFunction;
    });
    
    • Create the component MockComponent with the MyComp in it
    • Run a change detection to pass within the ngOnInit and subscribe to it
    • On the component MockComponent, set the condition to display MyComp to false --> it'll be destroyed by the ngIf evaluating to false
    • Expect the jasmine spy toHaveBeenCalled