【问题标题】:Error: [$injector:unpr] Unknown provider - I think I've checked the obvious stuff错误:[$injector:unpr] Unknown provider - 我想我已经检查了明显的东西
【发布时间】:2015-01-06 17:43:45
【问题描述】:

有效地在我的单元测试之前每个我都有

var moduleName = 'gameModel';
var providerName = 'gameConstants';
angular.module(moduleName);
inject(function($injector) {
    $injector.get(providerName);
});

我已经从模块和常量实现本身复制粘贴了模块名称和提供程序名称,所以我很确定这不是名称中的拼写错误。 Karma 正在按此顺序加载文件:

  1. 角度
  2. 角度模拟
  3. 包含模块“gameModel”的 js 文件 - 没有依赖项
  4. 包含常量提供程序“gameConstants”的 js 文件 - 没有依赖项
  5. 单元测试文件.js。

认为这涵盖了明显的东西(我认为我对 angular 还很陌生) - 名称似乎没问题,在它应该注入之前没有任何东西应该尝试注入。但我仍然收到未知提供程序异常。

我已经研究了几个小时,发现了我不明白的奇怪之处:

var moduleName = 'gameModel';
var providerName = 'gameConstants';
angular.module(moduleName);
inject(function($injector){
    console.log('Inject method, injector has provider: ', $injector.has(providerName));
    console.log('First provider name: ', angular.module(moduleName)._invokeQueue[0][2][0]);
});

var fooInjector =  angular.injector([moduleName]);
console.log('Explicitly rolled injector has provider: ', fooInjector.has(providerName));

has 方法通过注入方法返回 false,但奇怪的是 我可以从模块本身中获取提供程序名称。如果我推出自己的注射器(inject 方法之外的代码),那么has 可以工作,我什至可以找到提供者。任何人都可以解释为什么会发生这种情况 - 在我看来,我好像在为 $injectfooInjector 换一个不同的注射器

【问题讨论】:

    标签: angularjs mocha.js karma-runner


    【解决方案1】:

    简答

    我相信您的问题是您使用的是angular.module 而不仅仅是moduleangular.mock.module

    长答案

    Angular 模拟库创建一个模拟模块和注入函数。它必须作为模块的非模拟版本执行此操作,并且注入必须仍然能够正常运行,以便您可以实际运行和测试您的 Angular 代码。

    因此,当您将$injector 服务注入模拟注入函数时,模拟库不知道'gameConstants' 常量,因为您实际上并没有告诉模拟模块'gameModel' 模块。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-02
      • 2016-11-12
      • 2015-08-26
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      • 2019-09-18
      • 1970-01-01
      相关资源
      最近更新 更多