spyOn a Subscription.unsubscribe() - 测试 angular

spyOn a Subscription.unsubscribe() - testing angular

我正在尝试测试是否调用了订阅取消订阅方法,但出现错误。

我的组件如下所示:

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

我的测试看起来像这样

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

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

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

但我遇到了这个错误

Error: <spyOn> : could not find an object to spy upon for unsubscribe()
const spy = spyOn(
  (component as any).subscription,
  'unsubscribe'
).and.callThrough()
component.ngOnDestroy();
expect(spy).toHaveBeenCalled();

试试这个,我遇到了同样的问题,据我所知我用上面的方法解决了它。请核实。

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

component.ngOnDestroy();

expect(subscription).toHaveBeenCalledTimes(1);