How to test a function out of scope, and this is in UnitularJS Unit Testing

I need to apply testing to a specific controller.

Testing this controller is fine:

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'; } }; }); 

But I would like to check:

 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'; } }; }); 

I tried to test the controller using the following code:

 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(); }); }); 

But I get this error: the expected function is not to be thrown, but it selected TypeError: 'undefined' - n from the function (evaluation "MainCtrl.grade ()").

This https://stackoverflow.com/a/4646262/2326323 helps me apply testing to work inside 'this'. But I want to test functions from $ scope and 'this' ...

Any idea how to apply unit testing to this controller?

+5
source share
1 answer

The evaluation method is not tied to the controller;

 vm.grade = grade; 

Working plunkr

+1
source

All Articles