Angularjs 在依赖注入测试中,下划线的意义是什么
我目前正在编写一个教程,将angular JS集成到Rails应用程序中 测试设置如下:Angularjs 在依赖注入测试中,下划线的意义是什么,angularjs,testing,karma-runner,Angularjs,Testing,Karma Runner,我目前正在编写一个教程,将angular JS集成到Rails应用程序中 测试设置如下: describe( 'Club functionality', function() { // mock Application to allow us to inject our own dependencies beforeEach(angular.mock.module('league')); // create the custom mocks on the root scope
describe( 'Club functionality', function() {
// mock Application to allow us to inject our own dependencies
beforeEach(angular.mock.module('league'));
// create the custom mocks on the root scope
beforeEach(angular.mock.inject(function($rootScope, _$httpBackend_, $state){
//create an empty scope
scope = $rootScope.$new();
// we're just declaring the httpBackend here, we're not setting up expectations or when's - they change on each test
scope.httpBackend = _$httpBackend_;
scope.$state = $state;
}));
afterEach(function() {
scope.httpBackend.verifyNoOutstandingExpectation();
scope.httpBackend.verifyNoOutstandingRequest();
});
...
在完成了教程的这一部分并浏览了一些Angular文档之后,我仍然不清楚为什么在包含$httpBackend依赖项时使用下划线。为什么会这样嘲笑呢<代码>scope.httpBackend=$httpBackend代码>免责声明:我没有写这个答案。它是从我的书里抄来的 因此,“秘密”的关键在于: 基本上,
$injector
将在
检查函数的参数(以检索依赖项)。
这是一个很有用的技巧,因为我们可以做$rootScope=\uu$rootScope代码>和
然后,在稍后的测试中使用$rootScope
。从那以后看起来好多了
测试代码使用与控制器相同的变量。在
不知何故,使用前导的$
有助于记住这些是注入的
变量
当然我们可以这样做:rootScope=$rootScope但事实并非如此
显然是注射了根镜
这个比看起来简单。
为了方便起见,我们希望在测试套件中引用我们的服务/作用域,就像我们在应用程序中使用的那样。因此,我们需要将它们的引用保存在外部函数范围中
首先,我们需要注入它们,因此我们尝试在没有下划线的情况下这样做:
var $httpBackend;
beforeEach(angular.mock.inject(function( $httpBackend ){
问题是,内部函数范围变量$httpBackend
会遮挡外部函数范围变量$httpBackend
,因此我们无法在范围链上设置外部引用
要解决这个问题,我们必须为内部和外部范围变量指定不同的名称。下划线只是$injector提供的一点帮助,可以轻松完成此操作。可能重复的