代码之家  ›  专栏  ›  技术社区  ›  Kenneth Lynne

_servicename_中的下划线在AngularJS测试中意味着什么?

  •  76
  • Kenneth Lynne  · 技术社区  · 13 年前

    在下面的示例测试中,原始的提供程序名称是APIEndpointProvider,但对于注入和服务实例化,约定似乎是必须注入下划线来包装它。为什么?

    'use strict';
    
    describe('Provider: APIEndpointProvider', function () {
    
      beforeEach(module('myApp.providers'));
    
      var APIEndpointProvider;
      beforeEach(inject(function(_APIEndpointProvider_) {
        APIEndpointProvider = _APIEndpointProvider_;
      }));
    
      it('should do something', function () {
        expect(!!APIEndpointProvider).toBe(true);
      });
    
    });
    

    我缺少的更好的解释是什么?

    1 回复  |  直到 12 年前
        1
  •  109
  •   isherwood    10 年前

    下划线是一个方便的技巧,我们可以使用它以不同的名称注入服务,这样我们就可以在本地分配一个与服务同名的本地变量。

    也就是说,如果我们不能做到这一点,我们将不得不在本地为服务使用其他名称:

    beforeEach(inject(function(APIEndpointProvider) {
      AEP = APIEndpointProvider; // <-- we can't use the same name!
    }));
    
    it('should do something', function () {
      expect(!!AEP).toBe(true);  // <-- this is more confusing
    });
    

    这个 $injector 在测试中使用的是能够删除下划线,为我们提供我们想要的模块。事实并非如此 除了让我们重复使用相同的名称之外,其他任何东西都可以。

    Read more in the Angular docs