Search code examples
angularjasmine

How to mock a function call chained by properties


I am writing unit tests and was wondering if it was possible to mock the return value of the getCurrentAccountInfo function. I'm having issues because getCurrentAccountInfo is chained by Portal.Account

setAccountInfo(window: any) {
  this.accountInfo = window.Portal.Account.getCurrentAccountInfo();
}

I tried passing the window to my function, so I could test it, and ended up doing something like:

const window = jasmine.createSpyObj('window', ['getCurrentAccountInfo']);
window.getCurrentAccountInfo.and.returnValue({ name: 'My Account' });

component.setAccountInfo(window);
expect(component.accountInfo).toEqual({ name: 'My Account' });

But couldn't get it to work.


Solution

  • window is expected to have a Portal property. Try this instead:

    const Account = jasmine.createSpyObj(
      'window.Portal.Account',
      ['getCurrentAccountInfo']
    );
    const expected = { name: 'My Account' };
    Account.getCurrentAccountInfo.and.returnValue(expected);
    const window = {
      Portal: {
        Account
      }
    };
    
    component.setAccountInfo(window);
    expect(component.accountInfo).toEqual(expected);