问题描述
我试图写一个控制器的一些测试,但都在这个文档/教程/等与$范围函数和变量展示。如果你想测试的范围$东西呢?
例如:
app.controller('fakeCtrl',函数($范围){ 无功富='吧'; FOOBAR功能(){
的console.log('富巴');
}});
有什么办法进行单元测试富
或 foobar的()
?
下面就是不起作用:
描述(假控制器功能(){ beforeEach(模块(应用)); 变量$控制器; beforeEach(注(功能(_ $ controller_,$ rootScope){
$控制器= _ $ controller_;
$范围= $ rootScope $新的()。
})); 描述('富财产',函数(){
它('是吧',函数(){
VAR控制器= $控制器('fakeCtrl',{$范围:$范围});
期待(controller.foo).toEqual('巴');
});
});
...
您不能。变量富
及功能 foobar的
都无法访问你的控制器构造的范围之内。然而,你可以做这样的事情:
app.controller('fakeCtrl',函数($范围){
this.foo ='吧';
this.fooBar(){
的console.log('富巴');
}
});
和比:
(...)
描述('富财产',函数(){
它('是吧',函数(){
VAR控制器= $控制器('fakeCtrl',{$范围:$范围});
期待(controller.foo).toEqual('巴');
});
});
在你所描述的测试富
作为一个属性,但在你的控制器富
只是变量未财产
编辑:检查和控制器
语法。
I'm trying to write some tests for a controller, but ALL the documentation/tutorials/etc on this demonstrate with functions and variables on $scope. What if you want to test something NOT on $scope?
Ex:
app.controller('fakeCtrl', function($scope) {
var foo = 'bar';
function fooBar() {
console.log('foo bar');
}
});
Is there any way to unit test foo
or fooBar()
?
Here's what DOESN'T work:
describe("fake controller", function(){
beforeEach(module('app'));
var $controller;
beforeEach(inject(function(_$controller_, $rootScope){
$controller = _$controller_;
$scope = $rootScope.$new();
}));
describe('foo property', function() {
it('is bar', function() {
var controller = $controller('fakeCtrl', { $scope: $scope });
expect(controller.foo).toEqual('bar');
});
});
...
You can not. Variable foo
and function fooBar
are inaccessible outside the scope of your controller constructor. You can however do something like that:
app.controller('fakeCtrl', function($scope) {
this.foo = 'bar';
this.fooBar() {
console.log('foo bar');
}
});
And than:
(...)
describe('foo property', function() {
it('is bar', function() {
var controller = $controller('fakeCtrl', { $scope: $scope });
expect(controller.foo).toEqual('bar');
});
});
In the test you have described foo
as a property, but in your controller foo
is just variable not property.
Edit: Check https://docs.angularjs.org/api/ng/directive/ngController and controller as
syntax.
这篇关于角单元测试:如何在不测试范围控制器属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!