我创建了一个基本页面,用于验证输入。
如何进行单元测试表单验证?
这是我的代码:
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 :(得分: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()
});