简体   繁体   English

Angular单元测试:如何对ngOnInIt()中的订阅进行单元测试?

[英]Angular Unit Testing: How to unit test subscription inside ngOnInIt()?

Component to be tested: 要测试的组件:

export class ComponentDetailsComponent implements OnInit {
     ngOnInit() {

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

Spec: 规格:

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

   });

You don't have to write so many steps to pass as Observable. 您不必编写太多步骤即可通过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(){}
}

And your test case can be: 您的测试用例可以是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM