2015-12-21 37 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._; 
}); 

希望能幫助別人。