Fedy2
Fedy2

Reputation: 3207

How to inject references in angularjs unit test

I saw two different ways of injecting references in unit tests.

Underscore Wrapping

beforeEach( inject( function(_myService_){
  myService = _myService_;
}));

or

$injector injection

beforeEach(inject(function($injector) {
  myService = $injector.get('myService');
}));

What are the differences? Which one is the best practice?

Upvotes: 1

Views: 105

Answers (1)

ken4z
ken4z

Reputation: 1390

Both will work. The same option is available to you in a controller or service as well, but you typically use the pattern that is more similar to"underscore wrapping" except for specific cases when it is insufficient.

The "underscore wrapping" is a little cleaner because you only have to inject one service myService as opposed to two services $injector and myService. In addition, the "$injector injection" depends on the "Underscore Wrapping" technique to get the $injector service anyhow. Finally, the examples from Jasmine and Angular use the "Underscore Wrapper" example.

The second one gives you flexibility if you has the service name as a string somewhere, then you would need to use "$injector injection" to inject the service.

Lastly, I use this helper library which actually uses the "$injector injection" approach for the reason I stated above. I have found it to be very clean. https://github.com/brianmcd/angular-test-helpers/blob/master/src/angular-test-helpers.js

Upvotes: 1

Related Questions