Last Updated: January 03, 2018
·
405
· apelbaur

Test angular service

Ok. Let's talk about javascript real unit-testing...

Say you have a Service:

function MyService() {
   this.greet = function(name) {
       return 'hello ' + name;
   }
};

so, in order to test it you can access it from global scope:

it("test greet()", function() {
    var myService = new MyService();
    expect(myService.greet('bob')).toBe('hello bob');
});

https://jsfiddle.net/ronapelbaum/4uwetpy5/

OK, now let's take this service, and register it to angular.
Now we'd like to test it, using angular's DI mechanism:

var MyService;

beforeEach(module('MyModule'));

beforeEach(inject(function(_MyService_) {
    MyService = _MyService_;
}));

it("test greet()", function() {
    expect(MyService.greet('bob')).toBe('hello bob');
});

https://jsfiddle.net/ronapelbaum/m6Ltvh82/

So what do we have here?
we are using 2 method from ngMock:

  1. we tell angular what is the “namespace” that we will use with module()

  2. we inject service to our local var with inject()

Note that we don’t need to instansiate it since angular does it for us (services are singletons in angular).