2
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
  3. check if serviceB.methodB1() was called when serviceA.methodA2() received value.

first, one is easy to test.

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

But does one test 2 and 3?

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

something like that?

2 Answers 2

3

Alright, so I figured out what I am looking for is 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.

Sign up to request clarification or add additional context in comments.

Comments

1

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...);

1 Comment

Let's say, it's somebody else's existing code. And I can't change the code. But I have to write tests.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.