如果你正在做一些手工操作(超出默認的驗證規則,如輸入[數字],那麼你應該檢查你的驗證工作)。
如果使用默認的驗證,你還可以檢查用戶輸入一些無效數據後,您輸入的值是正確的。
實例:
describe('check default validation', function() {
var $scope, form;
beforeEach(module('exampleDirective'));
beforeEach(inject(function($compile, $rootScope) {
$scope = $rootScope;
var element = angular.element(
'<form name="form">' +
'<input ng-model="model.somenum" name="somenum" integer />' +
'</form>'
);
$scope.model = { somenum: null }
$compile(element)($scope);
form = $scope.form;
}));
describe('input type number should not accept string values', function() {
it('should pass with integer', function() {
form.somenum.$setViewValue('3');
$scope.$digest();
expect($scope.model.somenum).toEqual('3');
expect(form.somenum.$valid).toBe(true);
});
it('should not pass with string', function() {
form.somenum.$setViewValue('a');
$scope.$digest();
expect($scope.model.somenum).toBeUndefined();
expect(form.somenum.$valid).toBe(false);
});
});
});
用於定義驗證實施例:
var scope, form;
beforeEach(function() {
module('my-module');
module('templates');
});
beforeEach(inject($rootScope, $controller, $templateCache, $compile) {
scope = $rootScope.$new()
ctrl = $controller('MyController'), {
"$scope": scope
}
templateHtml = $templateCache.get('path/to/my/template.html')
formElem = angular.element("<div>" + templateHtml + "</div>")
$compile(formElem)(scope)
form = scope.form
scope.$apply()
}
it('should not allow an invalid `width`', function() {
expect(form.$valid).toBeTruthy();
form.number.$setViewValue('BANANA');
expect(form.number.$valid).toBeFalsy()
});