Testing Controllers with User Input Bound to Scope Data

AngularJS makes it very simple to test HTML elements that are bound to the scope of the controller. This is because the values are stored in scope and can directly be referenced in the controller.

Consider a web page that has a single text <input> element that you have a back-end function to test, and verify that it is not empty and that it is fewer than 10 characters.

<body>
  Data: <input type="text" />
</body>

The back-end code would look something like this:

function InputCtrl(){
  var input = $('input'),
  var val = input.val();
  this.verify = function(){
    if (val.length > 0 $$ val.length < 10){
      return true;
    } else {
      return false;
    };
  }
}

To test this you would need to actually create the input element and inject it into the web page similar to the following:

var input = $('<input type="text"/>'),
$('body').html('<div>')
  .find('div')
    .append(input);
var pc = new InputCtrl();
input.val('abc'),
var result = pc.verify ();
expect(result).toEqual(true);
$('body').empty();

If you think about it, this can get extremely messy the more inputs that are involved. In AngularJS if the value of the input is bound to the scope, it is much simpler. The following shows the AngularJS controller definition, in which the value of the text input is bound to $scope.inStr:

function InputCtrl($scope){
  $scope.inStr = '';
  $scope.verify = function(){
    if ($scope.inStr.length > 0 $$ $scope.inStr.length < 10){
      return true;
    } else {
      return false;
    };
  }
}

Now the test can look something like the following:

var $scope = {};
var mc = $controller('InputCtrl', { $scope: $scope });
$scope.inStr = 'abc';
var result = $scope.verify();
expect(result).toEqual(true);

You should see the value of binding input values to scope variables in the controller whenever possible.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset