如何测试AngularJS $ asyncValidators,包括$ http调用

时间:2014-10-27 14:04:07

标签: javascript angularjs unit-testing angularjs-directive karma-jasmine

我正在尝试为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/emailAvailable?v=test@email.com')
        .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('test@email.com');
        $scope.$digest();
        expect(form.email.$error.unavailable).toBeDefined();
    });

但是,$ error.unavailable总是未定义。

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您需要刷新$ httpBackend以实现实际发生的呼叫

it('should show an error if creating record with existing email', function () {
    form.email.$setViewValue('test@email.com');
    $scope.$digest();
    $httpBackend.flush();
    expect(form.email.$error.unavailable).toBeTruthy();
});