【问题标题】:How to do Unit Testring of a BehaviourSubject variable in a service, it is an observable in a component如何对服务中的 BehaviorSubject 变量进行单元测试,它是组件中的可观察对象
【发布时间】:2021-04-25 22:32:32
【问题描述】:

我正在尝试为组件中的变量(masters)编写测试用例,它是服务中的BehaviorSubject 变量。我无法找到编写测试用例的方法。以下是详细内容

// component code
export class MastersComponent implements OnInit, OnDestroy {
  destroy$: Subject<boolean> = new Subject<boolean>();
  masters: any[] = [];

  constructor(private masterService: MasterService) { }

  ngOnInit(){
    //.... some code here

    this.masterService.masters.pipe(
      takeUntil(this.destroy$))
      .subscribe(result => {
        this.masters = result;
      });

    //....some code here
    this.getMasters();
  }

  // component method code
  getMasters() => {
    const paginationObject = {
      pageNo: this.pageIndex + 1,
      sizePerPage: this.sizePerPage,
      searchString: this.searchString,
      order: 'asc',
      orderBy: ['name'],
      repositoryId: this.repositoryId
    };
    this.masterService.getMasters(paginationObject, alertError);
  }

  ngOnDestroy() {
    this.masterService.masters.next([]);
    this.destroy$.next(true);
    this.destroy$.unsubscribe();
  }
}

// service method code
masters: BehaviorSubject<Master[]> = new BehaviorSubject([]);

getMasters = (paginationObject, fail) => {
    this.resources.getMasters(paginationObject,
      (response) => {
        this.masters.next(response);
      }, (response) => {
        this.masters.next([]);
        fail(response);
      });
  }

【问题讨论】:

  • 你到底想测试什么?
  • 嗨,迈克,感谢您的回复。我正在尝试为在 MastersComponent 中声明的 masters 变量编写测试用例。但是这个变量是一个可观察的,它会在服务方法中得到更新。

标签: angular unit-testing components observable


【解决方案1】:

我认为你在组件的字段和服务的 observable 之间混合使用。

作为初学者,我建议您测试 ngOnInit 方法。这是大纲:

  1. 为 MasterService 创建一个存根,它公开一个 masters Observable 和一个 getMasters 方法。这个存根方法实际上是作为 ngOnInit 的输入,所以你应该在其中放入任何你想测试的输入,例如空数据:“this.masters.next([])”
  2. 使用您的测试框架将此存根作为 MasterService 注入
  3. 调用 ngOnInit
  4. 断言该组件的 masters 变量等于 []

综上所述,我们设计了如下测试用例:给定空master作为外部服务输入,组件也用空master初始化。

的确,这是一个简单的测试(有些人会说没有必要),但它应该演示如何测试一个方法,该方法获取的输入不是作为参数(直接)而是作为依赖项(服务、间接)。

顺便说一句,服务也应该作为一个单独的单元进行测试:要模拟“资源”依赖项(间接输入),以便使用两个参数作为直接输入来测试 getMasters 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2021-09-29
    • 2018-04-28
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    相关资源
    最近更新 更多