【问题标题】:spyOn a Subscription.unsubscribe() - testing angularspyOn a Subscription.unsubscribe() - 测试角度
【发布时间】:2019-05-03 01:24:31
【问题描述】:

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

我的组件如下所示:

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

【问题讨论】:

  • 组件调用this.subscription.unsubscribe(),你测试component['wizardSubscription'].unsubscribe ...
  • 也不应该从取消订阅回调中调用取消订阅。

标签: angular typescript angular-test


【解决方案1】:
component.subscription = new Subscription();
const subscription = spyOn(component.subscription, 'unsubscribe');

component.ngOnDestroy();

expect(subscription).toHaveBeenCalledTimes(1);

【讨论】:

    【解决方案2】:
    const spy = spyOn(
      (component as any).subscription,
      'unsubscribe'
    ).and.callThrough()
    component.ngOnDestroy();
    expect(spy).toHaveBeenCalled();
    

    试试这个,我有同样的问题,据我记得我用上面的方法来解决它。请检查并验证。

    【讨论】:

    • 这对我不起作用。 “无法监视原始”,但@Anudeep 的答案适用于如何创建订阅
    猜你喜欢
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 2020-09-09
    • 2020-11-14
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 2019-02-15
    相关资源
    最近更新 更多