I've been writing tests for some Angular components, using a syntax that I found on google a while ago:
describe('Directive: myDir', function () {
beforeEach(module('myApp'));
beforeEach(module('app/views/my_template.html'));
beforeEach(inject(function ($rootScope, _$compile_, $templateCache) {
$templateCache.put('views/my_template.html', $templateCache.get('app/views/my_template.html'));
var scope, $compile;
scope = $rootScope;
$compile = _$compile_;
element = angular.element("<div my-dir class='my-dir'></div>");
}));
it('does things', function () {
$compile(element)(scope);
scope.$digest();
});
});
My question is specifically about the injection of _$compile_
. How is it different from just $compile
. Why would I need to do it this way? Why does $compile get redefined, why can't I simply compile with a $compile I inject?
From the Angular official tutorial (Test section):
The injector ignores leading and trailing underscores here (i.e. $httpBackend). This allows us to inject a service but then attach it to a variable with the same name as the service.
In your example, you could rename the variable $compile
as, say, compile
and then remove the underscores from the parameter name. In fact, you did that to scope
so $rootScope
remained underscore-free.
Personally I like to keep the name of Angular built-in services in my tests so they can be easily spotted while skimming through the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With