6

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?

4

1 回答 1

12

来自Angular 官方教程(测试部分):

注入器在这里忽略前导和尾随下划线(即$httpBackend)。这允许我们注入服务,然后将其附加到与服务同名的变量。

在您的示例中,您可以将变量重命名$compile为,例如,compile然后从参数名称中删除下划线。事实上,你这样做是为了scope保持$rootScope没有下划线。

就我个人而言,我喜欢在我的测试中保留 Angular 内置服务的名称,以便在浏览代码时轻松发现它们。

于 2013-08-01T04:43:22.753 回答