Angular - 监视订阅块中的方法。

问题描述 投票:0回答:1

我有一个组件,它的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, 它似乎没有等到两个观测值都发出来.

我的问题是如何测试这样的代码?如何测试一个方法是在一个async rxjs操作符的订阅函数里面被调用的?

angular rxjs angular-testing
1个回答
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);
}));
© www.soinside.com 2019 - 2024. All rights reserved.