wlingke
wlingke

Reputation: 4799

Using Jasmine to spy on a private function in an AngularJS service

I have a factory myFactory that has a private function foo The factory returns an object with two properties: foo - which is set to the private function, and foo_alias which is set to function(){ foo() }

I am attempting to use Jasmine Spies to spy on the private function foo through: spyOn(myFactory, 'foo') and seeing whether or not it was called via foo_alias. I thought since everything is pointing back to the original private function foo, that calling the alias should trigger the spy - ie expect(myFactory.foo).toHaveBeenCalled() but this does not work.

A plunkr showing this question is here: http://plnkr.co/edit/i032kHYToe5sGml0Mnqn?p=preview

I would really appreciate some help on this and any suggestions for testing a private function through an alias. Specifically, I have a bunch of convenience methods that I want to make sure are calling the internal function with the right parameters.

Upvotes: 1

Views: 8167

Answers (1)

Ye Liu
Ye Liu

Reputation: 8986

To achieve what you want, you just need to make foo_alias call this.foo().

The reason is that after spyOn() is called, myFactory.foo has been wrapped and replaced by the wrapper function, i.e. myFactory.foo === wrapped_fn. The "wrapped_fn" is used by jasmine to "spy" on a function. However, myFactory.foo_alias is still calling the original foo(), not the spied function. Thus, expect(myFactory.foo).toHaveBeenCalled() raises error.

If you make foo_alias call this.foo() instead, it will then call the correct version of myFactory.foo().

Upvotes: 9

Related Questions