How to test AngularJs Providers with Jasmine

I want to share with you a simple strategy to test AngularJS Providers by using well known Jasmine test frameworks.

For me test a provider means have been able to test both its configuration features (during angular.config) and its instance features (after the angular injection of the provider instance, usually inside a controller).

The Provider

Let's define a very simple provider, that exposes a simple method to set the value of the provider (in config phase) and returns the value previously set when it was injected.

var myapp = angular.module("myapp",[]);

myapp.provider('hello',function(){  
    var hello;
    this.set = function(_hello){
        hello = _hello;
    }
    this.$get = [function(){
      return hello  
    }];
});

This is the provider code loaded with JsFiddle. In the example I have defined a simple controller (and some html) to test the provider configuration and usage.

Test the Provider

To test the provider we can use a very simple strategy (and clean code) thanks to Jasmine and Angular Mocks (to define and inject our provider).

// Define test
describe("Angular Simple Provider test",function(){

  var helloProvider;
  var hello;

  // load the main app
  beforeEach(function () {
    module('myapp');
  });

  // load the provider with module to be able to call its configuration methods
  beforeEach(function () {
    module(['helloProvider', function (_helloProvider) {
      helloProvider = _helloProvider; // to use the provider in other parts
      helloProvider.set("Hello");
    }]);
  });

  beforeEach(function () {
    inject(['hello', function (_hello) {
      hello = _hello;    // to use the instance in other parts
    }]);
  });

  it('should set the value for hello using the config Provider and get its value using the provider instance',function(){
      expect(hello).toEqual("Hello");
  });

});

This is the provider test code loaded with JsFiddle. In the example I have defined again the provider (now without specify any config or controller). Then I have used jasmine to define my test.

SOME CONSIDERATIONS

The provider I've defined is very simple. It is a simple constant congigurable with angular.config. However it may store any kind of javascript data value (strings, numbers, objects, functions and so on).

Moreover I've used JSFiddle to run my code and tests, in a real development environment you could use Karma test runner.

If you have problems to test your provider or want some other help feel free to comment below (or contact me @h4t0n)

Andrea Tarquini

IT Geek, Full Stack Developer, Programming Language Polyglot and IT security fan.

https://github.com/h4t0n https://twitter.com/h4t0n