angularjsjasminekarma-jasmineangular-mock

How to unit test module with provider dependencies?


I have an existing angular app. Now I want to start with some unit tests. I use jasmine and karma to test my services. My problem is that I am not able to test a service with the $stateProvider dependency. What I am using: - angularjs 1.5.8 - angular mocks 1.5.8

My code:

angular.module('starter.start', []).config(function ($stateProvider) {
          // ...
}).factory('MyService', function() {
          // ...
});

The test:

describe('MyServiceSpec', function() {
    var MyService;
    beforeEach(angular.mock.module('starter.start'));
    beforeEach(inject(function(_MyService_) {
        MyService= _MyService_;
    }));

    it('should exist', function() {
        expect(MyService).toBeDefined();
    });
});

I get the error Unknown provider: $stateProvider. In my research I found out that I need to do something with $provide but I am not sure how to do this.


Solution

  • you need to add $stateProvider in your config file

    next you need to inject ui.router before your main app

    beforeEach(angular.mock.module('ui.router'));
    beforeEach(angular.mock.module('starter.start'));
    

    and then you need to call service