[英]Angular unit testing: how to test controller properties without scope
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. 我正在尝试为控制器编写一些测试,但所有文档/教程/等都在$ scope上演示了函数和变量。 What if you want to test something NOT on $scope?
如果你想测试不在$ 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()
? 有没有办法单元测试
foo
或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. 变量
foo
和函数fooBar
在控制器构造函数范围之外是不可访问的。 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. 在测试中,您将
foo
描述为属性,但在您的控制器中, foo
只是变量而不是属性。
Edit: Check https://docs.angularjs.org/api/ng/directive/ngController and controller as
syntax. 编辑:检查https://docs.angularjs.org/api/ng/directive/ngController和
controller as
语法。
There is no way in javascript to access local(declared inside function) function or variable from outside scope. 在javascript中无法从外部作用域访问本地(声明的函数内部)函数或变量。 You have some options to test this:
你有一些选择来测试这个:
I prefer to move such functions/variables to angular services, but it depends on their purpose. 我更喜欢将这些函数/变量移动到角度服务,但这取决于它们的用途。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.