【问题标题】:Angular Unit Testing: How to unit test subscription inside ngOnInIt()?Angular 单元测试:如何在 ngOnInIt() 中对订阅进行单元测试?
【发布时间】:2019-08-22 23:32:01
【问题描述】:

要测试的组件:

export class ComponentDetailsComponent implements OnInit {
     ngOnInit() {

            this.componentDetailsService.currentProperties.subscribe((data) => {
                this.loader.hideLoader();    
                 this.showPopup = data.showPopup;
         .....more code....
    }

规格:

class ComponentDetailsServiceStub {
  defaultProperties ={       
    showToolbar: false,        
    showPopup: true, //show popup is set to true here       
    refresh: false,
  };

    propertiesSource = new BehaviorSubject(this.defaultProperties);
  currentProperties = this.propertiesSource.asObservable();

  setDefaultCancelClicked(){}
}


it('should set showPopup to correct value', () => {

    componentDetailsService.propertiesSource.next({         
      showToolbar: true,         
      showPopup: false, // show popup is set to false          
      refresh: false,

    }); 

    expect(subject.showPopup).toBe(true) ///this always passes

   });

【问题讨论】:

  • 请给minimal reproducible example;这是怎么接线的?我不会测试showPopup 属性,我会测试弹出窗口是否显示。你也可能需要detectChanges。

标签: javascript angular unit-testing jasmine karma-jasmine


【解决方案1】:

你不必写那么多步骤就可以像 Observable 一样通过。

import { of } from 'rxjs';
....

class ComponentDetailsServiceStub {
  defaultProperties ={       
    showToolbar: false,        
    showPopup: true, //show popup is set to true here       
    refresh: false,
  };
  currentProperties = of(defaultProperties); // will convert to Observable
  setDefaultCancelClicked(){}
}

你的测试用例可以是:

it('should set showPopup to correct value', () => {
    subject.ngOnInit(); // jasmine will internally call subscribe on stub service created and return the stub value assigned.
    expect(subject.showPopup).toBe(true);
   });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 2020-08-08
    • 2019-11-02
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多