Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: [$injector:unpr] Unknown provider: in AngularJS Service Test

I am having a lot of trouble getting dependencies provided properly for an AngularJS service.

I see a number of other posts with similar errors here on StackOverflow but none of them seem to resolve the issue.

Here is the app code:

cm.modules.app = angular.module('myApp', ['ngRoute', 'ngAnimate']);
myServiceName = function($http) {
    // do stuff
};
myServiceName.prototype.value = 1;

cm.modules.app.service('defaultAlertFactoryA', myServiceName);

Here is the test code:

describe('test alertFactoryA', function() {
  var $provide;
  var mAlertFactoryA;

  beforeEach(module(cm.modules.app));

  beforeEach(angular.mock.module(function(_$provide_) {
    $provide = _$provide_;
  }));

  beforeEach(function() {
    inject(function($injector) {
      mAlertFactoryA = $injector.get('defaultAlertFactoryA');
    });
  });

  it('should work', function() {
    expect(true).toBe(true);
  });
});

Here is the error:

Error: [$injector:unpr] Unknown provider: defaultAlertFactoryAProvider <- defaultAlertFactoryA http://errors.angularjs.org/1.2.0-rc.2/$injector/unpr?p0=defaultAlertFactoryAProvider%20%3C-%20defaultAlertFactoryA

Question: How do I fix this so the test passes?

like image 995
eb80 Avatar asked Jan 06 '14 18:01

eb80


3 Answers

In order to bootstrap your module you need to provide its name

beforeEach(module('myApp'));

Demo

like image 134
Eitan Peer Avatar answered Oct 27 '22 00:10

Eitan Peer


The following is what I used to get it working (finally)

 beforeEach(function() {
    module(cm.modules.app.name);

    module(function($provide) {
      $provide.service('defaultAlertFactoryA', myServiceName);
    });

    inject(function($injector) {
      defaultAlertFactory = $injector.get('defaultAlertFactoryA');
    });
 });
like image 24
eb80 Avatar answered Oct 26 '22 23:10

eb80


Sounds like you need to include the service files in your karma.conf.js file

files: [

  'app/bower_components/angular/angular.js',
  'app/bower_components/angular-mocks/angular-mocks.js',
  'app/bower_components/angular-ui-router/release/angular-ui-router.js',
  'app/app.js',
  'app/controllers/*.js',
  'app/services/*.js',
  'tests/**/*.js'
],

If the are not included here they can't be accessed in the unit tests

like image 28
Dave Keane Avatar answered Oct 27 '22 01:10

Dave Keane