简体   繁体   English

如何在Angular中对嵌套的订阅方法进行单元测试?

[英]How to unit test nested subscribe methods in Angular?

MethodToBeTested() {
  this.serviceA.methodA1().subscribe((response) => {
   if (response.Success) {
     this.serviceA.methodA2().subscribe((res) => {
        this.serviceB.methodB1();
      })
    }
  });
}

Here is the scenario. 这是场景。

Things to test: 要测试的东西:

  1. serviceA.methodA1(). was called. 被称为。
  2. if response.Success then check if serviceA.methodA2() was called 如果响应成功,则检查是否调用了serviceA.methodA2()
  3. check if serviceB.methodB1() was called when serviceA.methodA2() received value. 检查serviceA.methodA2()收到值时是否调用了serviceB.methodB1()

first, one is easy to test. 首先,一个很容易测试。

let spy = spyOn(serviceA, 'methodA1');
expect(spy).toHaveBeenCalled();

But does one test 2 and 3? 但是一个测试2和3吗?

 let spy= spyOn(serviceA, 'methodA1').and.returnValue({subscribe: () => {success:true}});
subject.MethodToBeTested();

something like that? 这样的东西?

It would be better to not use a nested subscribe. 最好不要使用嵌套订阅。

Something like this could be a sollution: 这样的事情可能是解决方案:

let $obs1 = this.serviceA.methodA1().pipe(share());
let $obs2 = $obs1.pipe(switchMap(x => this.serviceA.methodA2()));

$obs1.subsribe(logic1 here...);
$obs2.subsribe(logic2 here...);

Alright, so I figured out what I am looking for is callFake 好了,所以我知道我要寻找的是callFake

it('should test inside of subscribe', () => {
    let spy = spyOn(serviceA, 'methodA1').and.callFake(() => {
      return of({ success: true });
    });
    let spy2 = spyOn(serviceA, 'methodA2').and.callFake(() => {
      return of({ success: true });
    });
    let spy3 = spyOn(serviceB, 'methodB1').and.returnValue(of({ success: true }));
     subject.MethodToBeTested();
    expect(spy3).toHaveBeenCalled();
  });

I learned that returnValue won't actually execute the inside of the subscribe while callFake will with the data you provide inside it. 我了解到returnValue实际上不会在订阅内部执行,而callFake将使用您在订阅内部提供的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM