Search code examples
angulartypescriptangular-test

spyOn a Subscription.unsubscribe() - testing angular


I'm trying to test if a subscription unsubscribe method is called and I'm getting an error.

My component looks like this:

import { Component, OnInit } from '@angular/core'; import {
 Subscription } from 'rxjs/Subscription'; import { LoaderService } from
 '@core/components/loaders/services/loader.service';

 @Component({   selector: 'loader-mask',   templateUrl:
 './loader-mask.component.html',   styleUrls:
 ['./loader-mask.component.css'] })

 export class LoaderMaskComponent implements OnInit {

  subscription: Subscription;

   ngOnDestroy() {
      this.subscription.unsubscribe();
    } 
    }

and my test looks like this

it('should call unsubscribe() on ngOnDestroy', ()
=> {

 let spy = spyOn(component['subscription'], 'unsubscribe').and.callFake( () => {});
    component.ngOnDestroy();

    expect(spy).toHaveBeenCalled();   });

but I'm getting this error

Error: <spyOn> : could not find an object to spy upon for unsubscribe()

Solution

  • const spy = spyOn(
      (component as any).subscription,
      'unsubscribe'
    ).and.callThrough()
    component.ngOnDestroy();
    expect(spy).toHaveBeenCalled();
    

    Try this, I had the same problem and as far as i remember i used above way to solve it. Please check and verify.