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

时间:2014-01-10 18:57:04

标签: angularjs angularjs-module

我花了很长时间才试图覆盖提供给模块配置功能的注入常量。我的代码看起来像

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>);
});

这适用于我的控制器,但似乎配置功能不会查看模块外部的$provide d。它不是获取模拟值,而是将早期值定义为模块的一部分。 (在我们的测试中未定义;在下面的plunker中,'foo'。)

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

http://plnkr.co/edit/utCuGmdRnFRUBKGqk2sD

5 个答案:

答案 0 :(得分:26)

首先:茉莉花似乎在你的傻瓜中不能正常工作。但我不太确定 - 也许其他人可以再次检查这个。不过我已经创建了一个新的plunkr(http://plnkr.co/edit/MkUjSLIyWbj5A2Vy6h61?p=preview)并按照这些说明操作:https://github.com/searls/jasmine-all

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

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

你需要两件事:

  1. it函数中的真实测试 - expect(true).toBe(true)足够好了

  2. 您必须在测试中的某处使用inject,否则将不会调用提供给module的函数,并且不会设置常量。

  3. 如果您运行此代码,您将看到“绿色”:

    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');
      }));
    });
    

    我希望它能像你期望的那样工作!

答案 1 :(得分:5)

我认为根本问题是您在配置块之前定义常量,因此每次加载模块时,将覆盖可能存在的任何模拟值。我的建议是将常量和配置分离成单独的模块。

答案 2 :(得分:4)

虽然看起来你不能改变AngularJS常量在定义之后引用的对象,但你可以改变对象本身的属性。

因此,在您的情况下,您可以像其他任何依赖项一样注入I18n,然后在测试之前更改它。

var I18n;

beforeEach(inject(function (_I18n_) {
  I18n = _I18n_;
});

describe('A test that needs a different value of I18n.foo', function() {
  var originalFoo;

  beforeEach(function() {
    originalFoo = I18n.foo;
    I18n.foo = 'mock-foo';
  });

  it('should do something', function() {
    // Test that depends on different value of I18n.foo;
    expect(....);
  });

  afterEach(function() {
    I18n.foo = originalFoo;
  });
});

如上所述,您应该保存常量的原始状态,并在测试后将其恢复,以确保此测试不会干扰您现在或将来可能拥有的任何其他测试。

答案 3 :(得分:3)

您可以覆盖模块定义。我只是将其作为另外一种变体抛弃。

angular.module('config', []).constant('x', 'NORMAL CONSTANT');

// Use or load this module when testing
angular.module('config', []).constant('x', 'TESTING CONSTANT');


angular.module('common', ['config']).config(function(x){
   // x = 'TESTING CONSTANT';
});

重新定义模块将消除以前定义的模块,通常是在意外时完成的,但在这种情况下可以利用您的优势(如果您想要以这种方式打包)。请记住,该模块上定义的任何其他内容也将被删除,因此您可能希望它只是一个常量模块,这对您来说可能有点过分。

答案 4 :(得分:1)

作为一系列带注释的测试,我将通过一个更糟糕的解决方案。这是针对情况的解决方案,其中模块覆盖不是一个选项。这包括原始常量配方和配置块属于同一模块的情况,以及提供者构造函数使用常量的情况。

你可以在SO上内联运行代码(太棒了,这对我来说很新!)

请注意在规范之后恢复之前状态的警告。除非你们(a)都对Angular模块的生命周期有很好的理解,并且(b)确定你不能以任何其他方式测试某些东西,否则我不推荐这种方法。模块的三个队列(调用,配置,运行)不被视为公共API,但另一方面,它们在Angular的历史上是一致的。

可能有更好的方法来解决这个问题 - 我真的不确定 - 但这是我迄今为止找到的唯一方法。

angular
  .module('poop', [])
  .constant('foo', 1)
  .provider('bar', class BarProvider {
    constructor(foo) {
      this.foo = foo;
    }

    $get(foo) {
      return { foo };
    }
  })
  .constant('baz', {})
  .config((foo, baz) => {
    baz.foo = foo;
  });

describe('mocking constants', () => {
  describe('mocking constants: part 1 (what you can and can’t do out of the box)', () => {
    beforeEach(module('poop'));
  
    it('should work in the run phase', () => {
      module($provide => {
        $provide.constant('foo', 2);
      });

      inject(foo => {
        expect(foo).toBe(2);
      });
    });

    it('...which includes service instantiations', () => {
      module($provide => {
        $provide.constant('foo', 2);
      });

      inject(bar => {
        expect(bar.foo).toBe(2);
      });
    });

    it('should work in the config phase, technically', () => {
      module($provide => {
        $provide.constant('foo', 2);
      });

      module(foo => {
        // Code passed to ngMock module is effectively an added config block.
        expect(foo).toBe(2);
      });

      inject();
    });

    it('...but only if that config is registered afterwards!', () => {
      module($provide => {
        $provide.constant('foo', 2);
      });
  
      inject(baz => {
        // Earlier we used foo in a config block that was registered before the
        // override we just did, so it did not have the new value.
        expect(baz.foo).toBe(1);
      });
    });
  
    it('...and config phase does not include provider instantiation!', () => {
      module($provide => {
        $provide.constant('foo', 2);
      });
  
      module(barProvider => {
        expect(barProvider.foo).toBe(1);
      });
  
      inject();
    });
  });

  describe('mocking constants: part 2 (why a second module may not work)', () => {
    // We usually think of there being two lifecycle phases, 'config' and 'run'.
    // But this is an incomplete picture. There are really at least two more we
    // can speak of, ‘registration’ and ‘provider instantiations’.
    //
    // 1. Registration — the initial (usually) synchronous calls to module methods
    //    that define services. Specifically, this is the period prior to app
    //    bootstrap.
    // 2. Provider preparation — unlike the resulting services, which are only
    //    instantiated on demand, providers whose recipes are functions will all
    //    be instantiated, in registration order, before anything else happens.
    // 3. After that is when the queue of config blocks runs. When we supply
    //    functions to ngMock module, it is effectively like calling
    //    module.config() (likewise calling `inject()` is like adding a run block)
    //    so even though we can mock the constant here successfully for subsequent
    //    config blocks, it’s happening _after_ all providers are created and
    //    after any config blocks that were previously queued have already run.
    // 4. After the config queue, the runtime injector is ready and the run queue
    //    is executed in order too, so this will always get the right mocks. In
    //    this phase (and onward) services are instantiated on demand, so $get
    //    methods (which includes factory and service recipes) will get the right
    //    mock too, as will module.decorator() interceptors.
  
    // So how do we mock a value before previously registered config? Or for that
    // matter, in such a way that the mock is available to providers?
    
    // Well, if the consumer is not in the same module at all, you can overwrite
    // the whole module, as others have proposed. But that won’t work for you if
    // the constant and the config (or provider constructor) were defined in app
    // code as part of one module, since that module will not have your override
    // as a dependency and therefore the queue order will still not be correct.
    // Constants are, unlike other recipes, _unshifted_ into the queue, so the
    // first registered value is always the one that sticks.

    angular
      .module('local-mock', [ 'poop' ])
      .constant('foo', 2);
  
    beforeEach(module('local-mock'));
  
    it('should still not work even if a second module is defined ... at least not in realistic cases', () => {
      module((barProvider) => {
        expect(barProvider.foo).toBe(1);
      });
  
      inject();
    });
  });

  describe('mocking constants: part 3 (how you can do it after all)', () => {
    // If we really want to do this, to the best of my knowledge we’re going to
    // need to be willing to get our hands dirty.

    const queue = angular.module('poop')._invokeQueue;

    let originalRecipe, originalIndex;

    beforeAll(() => {
      // Queue members are arrays whose members are the name of a registry,
      // the name of a registry method, and the original arguments.
      originalIndex = queue.findIndex(([ , , [ name ] ]) => name === 'foo');
      originalRecipe = queue[originalIndex];
      queue[originalIndex] = [ '$provide', 'constant', [ 'foo', 2 ] ];
    })

    afterAll(() => {
      queue[originalIndex] = originalRecipe;
    });

    beforeEach(module('poop'));

    it('should work even as far back as provider instantiation', () => {
      module(barProvider => {
        expect(barProvider.foo).toBe(2);
      });
  
      inject();
    });
  });

  describe('mocking constants: part 4 (but be sure to include the teardown)', () => {
    // But that afterAll is important! We restored the initial state of the
    // invokeQueue so that we could continue as normal in later tests.

    beforeEach(module('poop'));

    it('should only be done very carefully!', () => {
      module(barProvider => {
        expect(barProvider.foo).toBe(1);
      });
  
      inject();
    });
  });
});
<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link href="style.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.5.2/jasmine.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.5.2/jasmine-html.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.5.2/boot.js"></script>
    <script src="https://code.angularjs.org/1.6.0-rc.2/angular.js"></script>
    <script src="https://code.angularjs.org/1.6.0-rc.2/angular-mocks.js"></script>
    <script src="app.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.5.2/jasmine.css">
  </head>

  <body>
  </body>

</html>

现在,您可能想知道为什么一开始就会做这些。 OP实际上描述了Angular + Karma + Jasmine无法解决的一个非常常见的场景。场景是有一些窗口配置的配置值决定了应用程序的行为 - 比如说,启用或禁用'调试模式' - 你需要测试不同灯具会发生什么,但是那些通常用于配置的值是需要的早点。我们可以将这些窗口值作为夹具提供,然后将它们通过module.constant配方路由到'angularize'它们,但我们只能一次,因为Karma / Jasmine通常不会给我们一个新鲜的每次测试的环境甚至是每个规格。当值将在运行阶段使用时,这是可以的,但实际上,90%的时间,这样的环境标志在配置阶段或提供者中都会引起关注。

您可以将此模式抽象为更强大的辅助函数,以减少弄乱基线模块状态的可能性。