javascript - Angular 单元测试: How to unit test subscription inside ngOnInIt()?

标签 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

   });

最佳答案

您不必编写那么多步骤来作为 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);
   });

关于javascript - Angular 单元测试: How to unit test subscription inside ngOnInIt()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56688964/

相关文章:

javascript - Mootools放大时出现问题

javascript - 将上下文变量作为参数传递给 onclick 事件处理程序

javascript - Jquery 表单未提交或验证

javascript - 检查另一个数组中的任何数组是否包含另一个数组中的值

angular - 当另一个 Observable(通知程序)发出时,从源 Observable 发出下一个值

unit-testing - 如何在 Monodevelop 中运行 xUnit.NET 单元测试?

java - 在 JUnit 4 中重用测试实现?

带有 x-www-form-urlencoded 数据的 Angular 6 http post 请求

html - Angular 2 : Pass boolean through routerLink

angular - 无法读取未定义的属性 'pipe' - Angular 6