Sifis
Sifis

Reputation: 653

Spy on a local function Angular Service

I have an Angular Service using a local function and doing the following work:

function myService($http,$q){

var myService = {};

var _localService = function (Table) {
    return Table.something;
}

var _getSomething = function () {
    return _localService('someTable');
}

var _getSomethingElse = function () {
    return _localService('someTable2');
}

myService.getSomething  = _getSomething ;
myService.getSomethingElse  = _getSomethingElse ;

return myService ; }

Now i want to test my service with jasmine and i want to test if localService have been called. Something like this:

spyOn(myService,"_localService");
myService.getSomething();
expect(myService._localService).toHaveBeenCalled();

How can i do that, please help.

Upvotes: 0

Views: 1246

Answers (1)

Boris Charpentier
Boris Charpentier

Reputation: 3545

You have to expose _localService in your service or else the spy can't find it.

Because in fact you made it private by returning myService without a _localService function.

So you can keep it private, or make it public, if it's public, it will work as is.

If you want to keep it private, then,

you shouldn't test private function, instead test what you expect as a result to the call of the public function. It will allow to refactor inner implementation and still have test to check that your code works.

Upvotes: 1

Related Questions