2013-08-27 24 views
24

我正在使用jasmine进行angularJS测试。在我的意见,我使用的“控制器”语法:如何在Jasmine中使用范围变量与“Controller as”语法?

<div ng-controller="configCtrl as config"> 
    <div> {{ config.status }} </div> 
</div> 

我怎样才能在茉莉花使用这些“范围”变量? “控制器”是指什么? 我的测试看起来如下:

describe('ConfigCtrl', function(){ 
    var scope; 

    beforeEach(angular.mock.module('busybee')); 
    beforeEach(angular.mock.inject(function($rootScope){ 
     scope = $rootScope.$new(); 

     $controller('configCtrl', {$scope: scope}); 
    })); 

    it('should have text = "any"', function(){ 
     expect(scope.status).toBe("any"); 
    }); 
}); 

调用scope.status两端,可以肯定,出现错误:

Expected undefined to be "any". 

UPDATE:控制器(从打字稿编译的JavaScript)是这样的:

var ConfigCtrl = (function() { 
    function ConfigCtrl($scope) { 
     this.status = "any"; 
    } 
    ConfigCtrl.$inject = ['$scope']; 
    return ConfigCtrl; 
})(); 
+0

至少,你应该做'期待(scope.config.status).toBe( “任何”);' – zsong

+0

请提供'configCtrl'的作为语法几乎是像做'$范围的代码。 config = this;'并执行'this.status =“any”;'。 –

+0

它工作,如果我在我的控制器中手动定义'$ scope.config = this;'。但我认为这不是它应该的方式,不是吗? – 3x14159265

回答

46

解决方案是在测试中实例化控制器时使用“controller as”语法。具体来说:

$ controller('configCtrl as config',{$ scope:scope});

expect(scope.config.status).toBe(“any”);

下,现在应该通过:

describe('ConfigCtrl', function(){ 
    var scope; 

    beforeEach(angular.mock.module('busybee')); 
    beforeEach(angular.mock.inject(function($controller,$rootScope){ 
     scope = $rootScope.$new(); 

     $controller('configCtrl as config', {$scope: scope}); 
    })); 

    it('should have text = "any"', function(){ 
     expect(scope.config.status).toBe("any"); 
    }); 
}); 
+0

不幸的是,这并不适合我。我得到错误'错误:参数'configCtrl作为配置'不是一个函数,得到了路径/到/ angular.js(行1039)''在行'$控制器('configCtrl as配置',{$范围:范围});' – 3x14159265

+0

应该可以工作,请参阅AngularJS自己的测试代码“控制器为”功能在这里https://github.com/angular/angular.js/blob/v1.2.0-rc.3/test/ng/ controllerSpec.js#L112 – Beyers

+0

@ 3x14159265另外两件事要检查/尝试:(1)注入$ controller,例如'beforeEach(inject(function($ controller,$ rootScope){'。and(2)确保你的模块在configCtrl被定义的地方被加载了,我在AngularJS 1.2.0 RC3中使用了这个语法,没有任何错误 – Beyers

15

当我们使用的是controller as语法,应该没有需要注入$ rootScope到我们的测试。以下应该工作得很好。

describe('ConfigCtrl', function(){ 
    beforeEach(module('busybee')); 

    var ctrl; 

    beforeEach(inject(function($controller){ 
     ctrl = $controller('ConfigCtrl'); 
    })); 

    it('should have text = "any"', function(){ 
     expect(ctrl.status).toBe("any"); 
    }); 
}); 
+7

有时你仍然需要访问控制器内的$ scope,即使你使用'controller as' – Beyers