在 AngularJS 测试中,在_servicename_中下划线是什么意思?

在下面的示例测试中,原始的提供程序名称是 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);
});


});

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

10877 次浏览

The underscores are a convenience trick we can use to inject a service under a different name so that we can locally assign a local variable of the same name as the service.

That is, if we couldn't do this, we'd have to use some other name for a service locally:

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

The $injector used in testing is able to just remove the underscores to give us the module we want. It doesn't do anything except let us reuse the same name.

Read more in the Angular docs