ashwin
ashwin

Reputation: 21

provider not found for underscore

i have an angularjs factory to which i am injecting underscore and application is working fine but when i try to write jasmine test cases on it i am getting an error underscore provider is not found i have my factory like

angular.module("sample")
.factory("example", example);
 example.$inject = ["$document", "$compile", "$rootScope", "$timeout", "$q", "underscore"];
function example($document, $compile, $rootScope, $timeout, $q, _) {

}

and i have my module defined as

(function(){
angular.module(samlple,[]);
})();

and my test case is as

beforeEach(module('sample'));
beforeEach(module('ionic'));
beforeEach(inject(function ($document, $compile, $rootScope, $timeout,underscore,example) {

}

its giving error Error: [$injector:unpr] Unknown provider: underscoreProvider <- underscore

Upvotes: 2

Views: 923

Answers (2)

Bakhtier Gaibulloev
Bakhtier Gaibulloev

Reputation: 159

Add import underscore in your index.html, then add it as a service.

var underscore = angular.module('underscore', []);
    underscore.factory('_', function() {
        return window._; // assumes underscore has already been loaded on the page
    });  

And

//Now we can inject underscoreJS in the controllers
function MainCtrl($scope, _) {
  //using underscoreJS method
  _.max([1,2,3,4]); //It will return 4, which is the maximum value in the array
}

But I recommend you to use lodash! It has more cool functions. Information about how to use lodash with Angular you can find here .

Upvotes: 1

Will Lovett
Will Lovett

Reputation: 1251

Piggybacking on @Bakhtier's answer, I used the following to get Karma/Jasmine to recognize lodash so I could use it in my services, as well as the rest of my app.

angular.module('app', ['app.services', 'lodash']);
angular.module('app.services', ['lodash']).factory('MyService', ['_', function (_){
    // your code bits
}]);
angular.module('lodash', []).factory('_', function() {
    return window._;
});

Hope that helps someone out.

Upvotes: 0

Related Questions