【发布时间】:2016-05-11 09:23:15
【问题描述】:
如何用注入测试一个AngularJS控制器,例如:
angular.module('app', []).controller('PasswordController', passwordController);
passwordController.$inject = ['$scope'];
//does not exist in the documentation angularjs
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';
}
};
}
我无法在测试写作中获得控制器
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 });
// TypeError: 'undefined' is not a function (evaluating '$controller('PasswordController');
$scope.password = 'longerthaneightchars';
$scope.grade();
expect($scope.strength).toEqual('strong');
});
});
});
使用 AngularJS 文档的控制器模型,我设法运行了测试:https://docs.angularjs.org/guide/unit-testing
【问题讨论】:
标签: angularjs unit-testing controller