angularjs – 是否可以在测试中覆盖模块配置函数的常量?

前端之家收集整理的这篇文章主要介绍了angularjs – 是否可以在测试中覆盖模块配置函数的常量?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我花了相当长的时间敲打我的头,试图覆盖提供给模块的配置功能的注入的常量。我的代码看起来像
common.constant('I18n',<provided by server,comes up as undefined in tests>);
common.config(['I18n',function(I18n) {
  console.log("common I18n " + I18n)
}]);

我们通常的方式来保证I18n在我们的单元测试中被注入

module(function($provide) {
  $provide.constant('I18n',<mocks>);
});

这对我的控制器工作正常,但是似乎配置函数没有看到在模块外部提供的$。而不是获取嘲笑的值,它获取作为模块一部分定义的早期值。 (在我们的测试的情况下未定义;在下面的空格中,“foo”)。

下面是一个工作空间(看控制台);有谁知道我做错了什么?

http://plnkr.co/edit/utCuGmdRnFRUBKGqk2sD

首先:茉莉花似乎在你的plunkr中不能正常工作。但我不太确定 – 也许有人可以再次检查。然而,我已经创建了一个新的plunkr( @L_403_1@),并按照这些说明: https://github.com/searls/jasmine-all

你会看到你的beforeEach代码永远不会运行。你可以查看这个:

module(function($provide) {
  console.log('you will never see this');
  $provide.constant('I18n',{ FOO: "bar"});
});

你需要两件事情

>一个真正的测试在它的功能 – expect(true).toBe(true)是足够好的
>您必须在测试中的某处使用注入,否则将不会调用提供给模块的函数,并且不会设置常量。

如果你运行这个代码,你会看到“绿色”:

var common = angular.module('common',[]);

common.constant('I18n','foo');
common.config(['I18n',function(I18n) {
  console.log("common I18n " + I18n)
}]);

var app = angular.module('plunker',['common']);
app.config(['I18n',function(I18n) {
  console.log("plunker I18n " + I18n)
}]);

describe('tests',function() {

  beforeEach(module('common'));
  beforeEach(function() {
    module(function($provide) {
      console.log('change to bar');
      $provide.constant('I18n','bar');
    });
  });
  beforeEach(module('plunker'));    

  it('anything looks great',inject(function($injector) {
      var i18n = $injector.get('I18n');
      expect(i18n).toBe('bar');
  }));
});

我希望它会按照你的期望工作!

原文链接:https://www.f2er.com/angularjs/144596.html

猜你在找的Angularjs相关文章