Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

unit testing - What does the underscores in _servicename_ mean in AngularJS tests?

In the following example test, the original provider name is APIEndpointProvider, but for injection and service instantiation the convention seems to be it has to be injected with underscores wrapping it. Why is that?

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

});

What is the convention I'm missing a better explanation to?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...