3

如何测试私有变量方法的调用?当调用 ngOnDestroy 时,我必须测试取消订阅方法的调用。

有我的代码

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

2 回答 2

0

放在anyspyOn 之前可以欺骗 Typescript 编译器。

spyOn<any>(component['subscription'], 'unsubscribe')

于 2021-10-26T14:07:47.647 回答
0

实际上类似的事情对我有用

spyOn(loginComponent['loaderSubscription'], 'unsubscribe');
loginComponent.ngOnDestroy();
expect(loginComponent['loaderSubscription'].unsubscribe).toHaveBeenCalled();
于 2020-04-15T12:17:55.163 回答