Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {


    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?

like image 704
Adriano Peluche Fazio Avatar asked Sep 02 '15 16:09

Adriano Peluche Fazio


People also ask

Is AngularJS code unit testable?

AngularJS is written with testability in mind, but it still requires that you do the right thing. We tried to make the right thing easy, but if you ignore these guidelines you may end up with an untestable application.

How does Scope work in AngularJS?

AngularJS ScopeThe scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.


1 Answers

The grade method is not being attached to the controller;

vm.grade = grade;

Working Plunkr

like image 61
Brandon Brooks Avatar answered Oct 04 '22 19:10

Brandon Brooks