Simplest AngularJS Service and a Jasmine unit test

The syntax for creating an AnguarJS service is rather alien to me as a Java developer, so I struggled to get this right, despite looking at and trying a number of different examples from different articles and howtos.

I think I’ve got this distilled to a simplest possible example now, so for future reference, this is a bare minimum service:

[code language=”javascript”]

angular.module(‘AppName.services’, [])
.factory(‘exampleService’, function () {

var serviceImpl = {};

//methods on service here

return serviceImpl;
});

[/code]

The syntax for implementing methods on the Service is like this (insert into where the comment is in the above example:

[code]

return {
exampleMethod: function (exampleParam1) {
var result;

//do something here

return result;
}
};

[/code]

A simple Jasmine test for a Service looks like this:

[code]

describe(‘Example service’, function () {
var exampleService;

it("Should be something here", function () {

var $injector = angular.injector([ ‘AppName.services’ ]);

exampleService = $injector.get( ‘exampleService’ );
var result = exampleService.exampleMethod(1);
expect(result).toBe(1);
});

});
[/code]