【发布时间】:2015-11-28 07:05:24
【问题描述】:
我需要对特定控制器进行测试。
测试这个控制器没问题:
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';
}
};
});
但我想测试一下:
angular.module('app', []).controller('PasswordController', function PasswordController($scope) {
var vm = this;
vm.password = '';
function grade() {
var size = vm.password.length;
if (size > 8) {
vm.strength = 'strong';
} else if (size > 3) {
vm.strength = 'medium';
} else {
vm.strength = 'weak';
}
};
});
我尝试使用以下代码测试控制器:
describe('Test', function () {
beforeEach(module('app'));
var MainCtrl, scope;
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MainCtrl = $controller('PasswordController', {
$scope: scope
});
}));
it('Should not throw Exception', function () {
scope.password = 'abc';
var call = function () {
MainCtrl.grade();
}
expect(call).not.toThrow();
});
});
但是我得到了这个错误:预期的函数不会抛出,但它抛出了 TypeError: 'undefined' is n ot 一个函数(评估 'MainCtrl.grade()')。
这个stackOverflow Question 帮助我将测试应用到“this”中的功能。但我想测试 $scope 和 'this' 之外的函数...
知道如何对这个控制器应用单元测试吗?
【问题讨论】:
标签: angularjs unit-testing controller jasmine karma-jasmine