Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test controller that depends on form validation in AngularJS

In my controller I want to invoke an action (say on Tab press) only when form is valid. Also I need to clear form as soon as form gets submitted succesfully. I have something like this

app.controller('CommentFormController', function($scope) {
  $scope.submit = function() {
    if($scope.commentForm.$valid) {
      // submit form
      $scope.comment = '';
      $scope.commentForm.$setPristine();
    }
  }
});

I'd like to test this, but it looks like I have to create this $scope.contactForm by hand and stub out $setPristine() function.

Is there any other way to test it? I mean can I somehow get instance of underlying FormController in my test?

How do you handle such cases?

like image 378
grafthez Avatar asked Oct 03 '13 10:10

grafthez


People also ask

Which of the following CSS classes are added by NG model to allow styling of form as well as controls?

To allow styling of form as well as controls, ngModel adds these CSS classes: ng-valid : the model is valid. ng-invalid : the model is invalid. ng-valid-[key] : for each valid key added by $setValidity.


1 Answers

Setting the form to pristine will affect the state of the form but won't reset the form to your defaults values (if you've provided them). Instead you can use the DOM element method reset().

Something like this:

document.getElementById("yourform").reset();

or, since angularJS and jQuery play nicely, you can use css selectors (especially useful if you have multiple forms you want to clear at once.

So something like:

$("#yourform")[0].reset();

There are pure javascript ways to do it also: http://www.javascript-coder.com/javascript-form/javascript-reset-form.phtml

--- So in summary, you don't need to use specific methods to do this, simply use the DOM methods, jQuery, or pure javascript. Google will probably come out with a way to do this soon. Hope this helps.

like image 143
Zimon Avatar answered Oct 20 '22 01:10

Zimon