Jasmine spyOn function within function and return mock value from last fn call

Viewed 187

I'm trying to write a Jasmine test where I got an object structure as follows:

class User {
   public getData(): void {
      return {
         getPersonalInfo: () => {
            ...
         }
      }
   }
}

Normally, I would call this as user.getData().getPersonalInfo(). Now, I would like to spyOn this call and return a mocked info response when calling getPersonalInfo().

What I attempted doing:

spyOn(user.getData, "getPersonalInfo").and.returnValue(...)

spyOn(user, "getData").and.callThrough().and.callFake(() => {... fake data ...} )

spyOn(user, "getPersonalInfo").and.callFake(() => {... fake data ...} )

But no matter what I have tried thus far, it's not working.

How can I achieve this?

1 Answers

You can archive it like this:

const getPersonalInfoSpy = jasmine.createSpy('getPersonalInfoSpy');
getPersonalInfoSpy.and.returnValue({}); // provide mock here
spyOn(user, "getData").and.returnValue({ getPersonalInfo: getPersonalInfoSpy})

Don't forget to provide a proper mock for getPersonalInfoSpy;

Related