2015-12-21 83 views
2

我有一个angularjs工厂,我注射了下划线和应用程序工作正常,但是当我尝试写茉莉花测试用例时,我得到一个错误下划线提供程序未找到 我有我的工厂像供应商找不到下划线

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

} 

和我有我的模块定义为

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

和我的测试用例是

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

} 

它给错误 错误:[$注射器:unpr]未知提供商:underscoreProvider < - 强调

+0

您的下划线服务在哪里定义?我假定它不在一个单独的模块中,因为你没有列出任何依赖关系...... –

+0

另外,在你的测试中使用inject()函数注入它们时,你的服务名应该被下划线包围(例如:_underscore_,_example_)。 –

回答

1

添加进口在您的index.html强调,然后将其添加为服务。

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

而且

//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 
} 

但我建议你使用lodash!它有更酷的功能。有关如何使用lodash与Angular的信息,你可以找到here

0

在@ Bakhtier的回答中捎带,我使用以下方法让Karma/Jasmine识别lodash,以便我可以在我的服务以及我的其他应用程序中使用它。

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

希望能帮助别人。