【发布时间】:2016-10-13 14:55:29
【问题描述】:
我有一个包含以下输入的表单:
<input type="email" name="email" ng-model="register.form.email" ng-pattern="emailRegex">
如果用户输入无效的电子邮件,我想测试该表单是否无效:
it('...', function() {
form.email.$setViewValue('invalid');
expect(form.email.$valid).toBeFalsy(); // OK
form.email.$setViewValue('invalid@');
expect(form.email.$valid).toBeFalsy(); // OK
form.email.$setViewValue('invalid@host');
expect(form.email.$valid).toBeFalsy(); // Not OK
});
最后一个期望失败,因为输入是有效的,尽管电子邮件正则表达式需要一个域。感觉好像在我的测试中没有使用该模式,因为当我将类型更改为文本时,它已经在第一个期望中失败了。如何确保在测试中采用该模式?
为了完整起见,这是正则表达式(不是我写的):
^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[_A-Za-z0-9]+[_A-Za-z0-9-]*[_A-Za-z0-9]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$
将类型更改为text 无效。
我正在使用 jasmine 2.4.1 和 angular 1.4.2。我正在使用 ngHtml2JsPreprocessor 解释 here 在我的测试中初始化表单。
编辑:
这是如何初始化表单的:
beforeEach(inject(function($rootScope, $templateCache, $compile) {
var $scope = $rootScope.$new();
vm = $controller('RegisterController', {$scope: $scope});
var templateHtml = $templateCache.get("register.html");
var template = angular.element("<div>" + templateHtml + "</div>");
$compile(template)($scope);
var form = $scope.registerForm;
$scope.$apply();
scope = $scope;
}));
【问题讨论】:
-
该测试能证明什么?
ng-pattern有效吗?是的 - 它有效,可能响应开发 AngularJS 的团队会在您之前发现该错误。你想测试正则表达式吗?提取它并在单元测试中测试它
标签: angularjs forms unit-testing jasmine