Adr*_*zio 5 unit-testing controller jasmine angularjs karma-jasmine
我需要将测试应用于特定的控制器.
测试这个控制器是好的:
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';
}
};
});
Run Code Online (Sandbox Code Playgroud)
但我想测试一下:
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';
}
};
});
Run Code Online (Sandbox Code Playgroud)
我尝试使用以下代码测试控制器:
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();
});
});
Run Code Online (Sandbox Code Playgroud)
但是我得到了这个错误: 期望函数不抛出,但它抛出TypeError:'undefined'不是一个函数(评估'MainCtrl.grade()').
这个stackOverflow问题帮助我应用测试来在'this'里面运行.但我想测试$ scope和'this'中的函数...
任何想法如何将单元测试应用于此控制器?