2016-10-13 68 views
0

我已经创建了一个验证输入的基本页面。如何用茉莉花单元测试角度表单验证

如何进行单元测试表单验证?

这里是我的代码:

JS

// create angular app 
var validationApp = angular.module('validationApp', []); 

// create angular controller 
validationApp.controller('mainController', function($scope) { 

var vm = this; 
// function to submit the form after all validation has occurred    
vm.submitForm = function() { 

    // check to make sure the form is completely valid 
    if ($scope.userForm.$valid) { 
    alert('our form is amazing'); 
    } 

}; 

HTML

<form name="userForm" ng-submit="vm.submitForm()" novalidate> 

     <!-- NAME --> 
     <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }"> 
      <label>Name</label> 
      <input type="text" name="name" class="form-control" ng-model="user.name" required> 
      <p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">You name is required.</p> 
     </div> 

     <!-- USERNAME --> 
     <div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$pristine }"> 
      <label>Username</label> 
      <input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8"> 
      <p ng-show="userForm.username.$error.minlength" class="help-block">Username is too short.</p> 
      <p ng-show="userForm.username.$error.maxlength" class="help-block">Username is too long.</p> 
     </div> 

     <!-- EMAIL --> 
     <div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$pristine }"> 
      <label>Email</label> 
      <input type="email" name="email" class="form-control" ng-model="user.email"> 
      <p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p> 
     </div> 

     <button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Submit</button> 

</form> 

回答

0

我们可以做如下的方式。 这仅用于表单验证。但在此之前,我们需要配置karma-ng-html2js-preprocessor

var scope, htmlForm; 

beforeEach(function() { 
    module('module'); 

}); 

beforeEach(inject($rootScope, $controller, $templateCache, $compile) { 
    scope = $rootScope.$new() 

    templateHtml = $templateCache.get('sample/sample.html') 
    formElement = angular.element("<div>" + templateHtml + "</div>") 
    $compile(formElement)(scope) 
    htmlForm= scope.htmlForm 

    scope.$apply() 
} 

it('should not allow an invalid `width`', function() { 
    expect(htmlForm.$valid).toBeTruthy(); 
    htmlForm.number.$setViewValue('LORA'); 
    expect(htmlForm.number.$valid).toBeFalsy() 
}); 
+0

我不知道如何在我的项目实现这一点,这将是有益的,如果你可以更新plunker。 – ankitd