2016-10-13 151 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