我正在尝试为 AngularJS 电子邮件可用性检查器编写一个 Jasmine 测试,它使用 Angular 最新功能 - $asyncValidators 管道。这是我的指令:
au_helper.directive('recordAvailabilityValidator',
['$http', function ($http) {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
var apiUrl = attrs.recordAvailabilityValidator;
var ownId = attrs.recordAvailabilityId;
ngModel.$asyncValidators.unavailable = function(value) {
return $http({method: 'GET', url: apiUrl, params: {v: value, id: ownId}});
};
}
}
}]);
在我的测试中,我尝试像这样设置后端响应:
$httpBackend.when('GET', 'api/users/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="046169656d684572656d68656668613b723970617770446169656d682a676b69" rel="noreferrer noopener nofollow">[email protected]</a>')
.respond(400, {flash: 'not available'});
$scope.user = {email: null};
var element = angular.element(
'<form name="form">' +
'<input ng-model="user.email" name="email" record-availability-validator="api/users/emailAvailable" />' +
'</form>'
);
$compile(element)($scope);
form = $scope.form;
然后测试它:
it('should show an error if creating record with existing email', function () {
form.email.$setViewValue('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a3e2f393e0a2f272b232664292527" rel="noreferrer noopener nofollow">[email protected]</a>');
$scope.$digest();
expect(form.email.$error.unavailable).toBeDefined();
});
但是,$error.unavailable 始终未定义。
感谢您的帮助!
最佳答案
您需要刷新 $httpBackend 才能真正发生调用
it('should show an error if creating record with existing email', function () {
form.email.$setViewValue('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9aeeffe9eedafff7fbf3f6b4f9f5f7" rel="noreferrer noopener nofollow">[email protected]</a>');
$scope.$digest();
$httpBackend.flush();
expect(form.email.$error.unavailable).toBeTruthy();
});
关于javascript - 如何测试 AngularJS $asyncValidators 包括 $http 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26589328/