我一直在为一些Angular组件编写测试,使用我刚才在google上找到的语法:
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(); }); });
我的问题是关于_ $compile_的注入.它与$compile有什么不同.我为什么要这样做呢?为什么$compile被重新定义,为什么我不能简单地编译我注入的$compile?
解决方法
从
Angular official tutorial(测试部分):
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.
在您的示例中,您可以将变量$compile重命名为编译,然后从参数名称中删除下划线.事实上,你这样做的范围是因为$rootScope仍然没有下划线.
我个人喜欢在测试中保留Angular内置服务的名称,以便在浏览代码时轻松发现它们.