Angular-订阅块内部的方法的间谍

时间:2020-05-03 15:50:00

标签: angular rxjs angular-testing

我有一个具有以下ngOnInit()方法的组件:

ngOnInit() {
  combineLatest([
    this.observable1,
    this.observable2
  ])
  .pipe(takeUntil(this.unsubscribe$))
  .subscribe(([data1, data2]) => {
    this.processData(data1, data2);
  });
}

我想编写一个测试来验证是否调用了processData()方法。

我尝试过这样的事情:

it('should call processData', ()=> {
   ... make sure each observable1 and observable2 will emit a value
   spyOn(component, 'processData');
   fixture.detectChanges();
   expect(component.processData).toHaveBeenCalled();
}));

expect(component.processData).toHaveBeenCalled()将始终返回false,似乎没有等到两个可观察对象都发出值。

我的问题是如何测试这种代码?如何测试异步rxjs运算符的订阅函数内部是否调用了某个方法?

1 个答案:

答案 0 :(得分:0)

第一个问题是this.observable1this.observable2做什么?

要触发this.processData,它们两个都应该至少发射一次。 如果您可以共享测试的更多代码以及observable1observable2的创建方式,那么可能会很棒。

我建议将测试更改为下一个样式

it('should call processData', ()=> {
   // firstly set the spy
   spyOn(component, 'processData');

   // secondly we need to fake our observables
   component.observable1 = of(1);
   component.observable2 = of(2);

   // now we trigger the flow
   component.ngOnInit();

   // clean up
   component.unsubscribe$.next();
   component.unsubscribe$.complete();

   // assertions
   expect(component.processData).toHaveBeenCalledWith(1, 2);
}));