Unit test, which depends on form validation in AngularJS

In my controller, I want to trigger an action (for example, pressing Tab) only if the form is valid. I also need to clear the form as soon as the form is submitted successfully. 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 would like to check this out, but it looks like I need to create this $scope.contactForm manually and drown the $setPristine() function.

Is there any other way to test this? I mean, can I somehow get an instance of the underlying FormController in my test?

How do you handle such cases?

+8
javascript angularjs validation
source share
2 answers

Setting the form to untouched will affect the state of the form, but will not reset the form for the default values โ€‹โ€‹(if you provided them). Instead, you can use the DOM element's reset () method.

Something like that:

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

or, since angular JS and jQuery play well, you can use the css selector (especially useful if you have several forms that you want to clear at once.

So something like:

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

There are pure javascript ways to do this as well: http://www.javascript-coder.com/javascript-form/javascript-reset-form.phtml

--- Thus, you do not need to use specific methods for this, just use the DOM, jQuery or pure javascript methods. Google is likely to come out with this path to do so soon. Hope this helps.

+1
source share

@grafthez I have the same problem when an attempt to validate a form is valid in my controller on $ scope.myForm. $ valid.

I found a solution on https://stackoverflow.com/a/464210/ ... You can try to compile $ then, then $ compile (yourFormTemplate) ($ scope).

0
source share

All Articles