Basel Zarka
Basel Zarka

Reputation: 23

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

Upvotes: 1

Views: 4513

Answers (2)

Anudeep
Anudeep

Reputation: 289

component.subscription = new Subscription();
const subscription = spyOn(component.subscription, 'unsubscribe');

component.ngOnDestroy();

expect(subscription).toHaveBeenCalledTimes(1);

Upvotes: 4

Chamindu
Chamindu

Reputation: 26

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.

Upvotes: 1

Related Questions