【问题标题】:Angular testing spyOn on private variable对私有变量进行角度测试 spyOn
【发布时间】:2018-06-27 08:49:25
【问题描述】:

如何测试私有变量方法的调用? 我必须在调用 ngOnDestroy 时测试 unsubscribe 方法的调用。

这是我的代码

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 {

  show = false;
  private subscription: Subscription;

  constructor(private loaderService: LoaderService) { }

  ngOnInit() {
    this.subscription = this.loaderService.loaderState
      .subscribe((state: boolean) => {        
        this.show = state;
      });
  }

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

这是我的测试代码

it('should destroy the subscription when destroying', () => {
    const spyUnSubscribe = spyOn(component['subscription'], 'unsubscribe').and.callThrough();
    component.ngOnDestroy();  
    expect(spyUnSubscribe).toHaveBeenCalled();  
    expect(component['subscription']).toBeUndefined();
  });

有问题:

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

【问题讨论】:

  • 您正在订阅该服务,因此您可以模拟/监视该服务并控制返回的 observable 并对其进行监视。
  • 您根本无法访问私有属性。这就是为什么他们是private
  • 有什么答案吗?

标签: angular karma-jasmine angular-test


【解决方案1】:

any 放在 spyOn 之前以欺骗 Typescript 编译器。

spyOn&lt;any&gt;(component['subscription'], 'unsubscribe')

【讨论】:

    【解决方案2】:

    实际上类似的东西对我有用

    spyOn(loginComponent['loaderSubscription'], 'unsubscribe');
    loginComponent.ngOnDestroy();
    expect(loginComponent['loaderSubscription'].unsubscribe).toHaveBeenCalled();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      • 2019-07-13
      • 2020-09-09
      相关资源
      最近更新 更多