【发布时间】:2015-09-18 10:40:34
【问题描述】:
Jasmine 是以 BDD 方式对 javascript 代码进行单元测试的最广泛使用的测试框架之一。我尝试将它用于 AngularJS 组件测试。 AngularJS 文档提供了如下示例代码
describe('PasswordController', function() {
beforeEach(module('app'));
var $controller;
beforeEach(inject(function(_$controller_){
$controller = _$controller_;
}));
describe('$scope.grade', function() {
it('sets the strength to "strong" if the password length is >8 chars', function() {
var $scope = {};
var controller = $controller('PasswordController', { $scope: $scope });
$scope.password = 'longerthaneightchars';
$scope.grade();
expect($scope.strength).toEqual('strong');
});
});
});
所以上面的代码使用了 Angular 模拟库,并通过依赖注入通过控制器处理范围。现在我有一个范围对象,其中包含我的控制器分配给它的功能和对象。我可以很好地测试它。快乐。
现在有趣的部分是如果我想测试未链接到范围的函数。比如下面的doSomethingVeryCoolThatNeedsTesting函数
angular.module('app', [])
.controller('PasswordController', function PasswordController($scope) {
$scope.password = '';
$scope.grade = function() {
var size = $scope.password.length;
if (size > 8) {
$scope.strength = 'strong';
} else if (size > 3) {
$scope.strength = 'medium';
} else {
$scope.strength = 'weak';
}
function doSomethingVeryCoolThatNeedsTesting() {
....
}
};
});
似乎每当我使用$controller('PasswordController', { $scope: $scope }); 时,它都会返回一个填充的$scope 对象和undefined 控制器对象。
TL;DR
有没有一种方法可以测试未链接到范围的 Angular 控制器功能?
【问题讨论】:
标签: javascript angularjs unit-testing jasmine