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

时间:2019-06-20 15:09:31

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

要测试的组件:

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

   });

1 个答案:

答案 0 :(得分: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);
   });