How do I test an AngularJS service with Jasmine?

The problem is that the factory method, that instantiate the service, is not called in the example above (only creating the module doesn’t instantiate the service).

In order to the service to be instantiated angular.injector has to be called with the module where our service is defined. Then, we can ask to the new injector object for the service and its only then when the service is finally instantiated.

Something like this works:

describe('myService test', function(){
    describe('when I call myService.one', function(){
        it('returns 1', function(){
            var $injector = angular.injector([ 'myModule' ]);
            var myService = $injector.get( 'myService' );
            expect( myService.one ).toEqual(1);
        })

    })

});

Another way would be passing the service to a function using ‘invoke’:

describe('myService test', function(){
    describe('when I call myService.one', function(){
        it('returns 1', function(){

            myTestFunction = function(aService){
                expect( aService.one ).toEqual(1);
            }

            //we only need the following line if the name of the 
            //parameter in myTestFunction is not 'myService' or if
            //the code is going to be minify.
            myTestFunction.$inject = [ 'myService' ];

            var myInjector = angular.injector([ 'myModule' ]);
            myInjector.invoke( myTestFunction );
        })

    })

});

And, finally, the ‘proper’ way to do it is using ‘inject’ and ‘module’ in a ‘beforeEach’ jasmine block.
When doing it we have to realize that the ‘inject’ function it’s not in the standard angularjs package, but in the ngMock module and that it only works with jasmine.

describe('myService test', function(){
    describe('when I call myService.one', function(){
        beforeEach(module('myModule'));
        it('returns 1', inject(function(myService){ //parameter name = service name

            expect( myService.one ).toEqual(1);

        }))

    })

});

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)