Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 684
Kenneth Lynne Avatar asked Mar 10 '13 02:03

Kenneth Lynne


People also ask

What does underscore mean in AngularJS?

Updated on July 03, 2019. The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.

Is AngularJS code unit testable?

AngularJS is written with testability in mind, but it still requires that you do the right thing. We tried to make the right thing easy, but if you ignore these guidelines you may end up with an untestable application.

Which of the following can be used to run unit tests in Angular?

Jasmine is the default test framework used with Angular.


1 Answers

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

like image 109
Josh David Miller Avatar answered Oct 02 '22 16:10

Josh David Miller