我正在尝试为 Controller 编写一些测试,但所有关于此的文档/教程/等都在 $scope 上演示了函数和变量。如果你想测试不在 $scope 上的东西怎么办?
例如:
app.controller('fakeCtrl', function($scope) {
var foo = 'bar';
function fooBar() {
console.log('foo bar');
}
});
有什么方法可以对 foo
或 fooBar()
进行单元测试吗?
这是行不通的:
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');
});
});
...
最佳答案
你不能。变量 foo
和函数 fooBar
在 Controller 构造函数的范围之外是不可访问的。但是,您可以这样做:
app.controller('fakeCtrl', function($scope) {
this.foo = 'bar';
this.fooBar() {
console.log('foo bar');
}
});
比:
(...)
describe('foo property', function() {
it('is bar', function() {
var controller = $controller('fakeCtrl', { $scope: $scope });
expect(controller.foo).toEqual('bar');
});
});
在测试中,您将 foo
描述为一个属性,但在您的 Controller 中,foo
只是变量而非属性。
编辑:检查https://docs.angularjs.org/api/ng/directive/ngController和 controller as
语法。
关于javascript - Angular 单元测试 : how to test controller properties without scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28319879/