2013-03-10 61 views
74

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

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

}); 

什么是约定我错过了更好的解释?

回答

102

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

也就是说,如果我们做不到这一点,我们必须使用一些其他的名字为本地服务:

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

相关问题