【问题标题】:provider not found for underscore未找到下划线的提供者
【发布时间】:2015-12-21 21:52:17
【问题描述】:

我有一个 angularjs 工厂,我正在向其中注入下划线,并且应用程序工作正常,但是当我尝试在其上编写 jasmine 测试用例时,我收到一个错误,找不到下划线提供程序 我有我的工厂

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) {

}

给出错误 错误:[$injector:unpr] 未知提供者:underscoreProvider

【问题讨论】:

  • 你的下划线服务是在哪里定义的?我假设它不在单独的模块中,因为您没有列出依赖项...
  • 此外,在使用您的文件中的 inject() 函数注入服务名称时,您的服务名称应该用下划线括起来(例如:underscoreexample)测试。

标签: angularjs ionic-framework angularjs-provider


【解决方案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!它有更酷的功能。有关如何在 Angular 中使用 lodash 的信息,您可以找到 here

【讨论】:

    【解决方案2】:

    根据@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._;
    });
    

    希望对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-08
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-31
      • 2017-09-20
      • 2018-11-10
      • 2016-12-10
      相关资源
      最近更新 更多