【问题标题】:Angular - spy on method inside subscribe blockAngular - 监视订阅块内的方法
【发布时间】:2020-08-17 23:59:56
【问题描述】:

我有一个具有以下 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 操作符的订阅函数中被调用?

【问题讨论】:

  • 您很可能还必须对 observables 进行存根。它现在可能不起作用,因为它们异步发出值。您是否考虑过使用 spyOn(comp, 'observable1').and.returnValue(of('dummy data')) 之类的东西?

标签: angular rxjs angular-test


【解决方案1】:

第一个问题是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);
}));

【讨论】:

    猜你喜欢
    • 2019-06-15
    • 2021-07-22
    • 2020-10-11
    • 2020-02-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    相关资源
    最近更新 更多