mercredi 2 septembre 2015

How to test function out of scope and this in AngularJS Unit Testing

I need to apply testing to a particular controller.

Testing this controller is ok:

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'd like to test:

angular.module('app', []).controller('PasswordController', function PasswordController($scope) {

    $scope.password = '';

    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 code below:

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 : Expected function not to throw, but it threw TypeError: 'undefined' is n ot a function (evaluating 'MainCtrl.grade()').

This stackOverflow Question help me to apply testing to function inside 'this'. But I want to test functions out of $scope and 'this'...

Any Idea how to apply unit testing to this controller?

Aucun commentaire:

Enregistrer un commentaire