我需要将测试应用于特定的控制器.
测试这个控制器是好的:
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',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’是n
一个函数(评估’MainCtrl.grade()’).
这个stackOverflow Question帮我在’this’里面运行测试.但我想测试$scope和’this’中的函数…
任何想法如何将单元测试应用于此控制器?