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

标签 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/<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/

相关文章:

javascript - 打开 fancybox div 后加载 flexslider

javascript - react-native-bluetooth-escpos-printer 编码土耳其语字符问题

javascript - 单击 href 链接时下载文件?

html - 不需要结束标记的自定义 Angular 指令?

javascript - 单元测试 jQuery document.ready 函数

javascript - Module.export-ing 一个新实例

javascript - Bootstrap 选项卡,如何在页面加载时设置选定的选项卡?

javascript - 预期响应包含一个对象,但在 Angular js 中出现数组错误

reactjs - 我怎样才能让 Jest 静静地测试抛出的错误

c# - 如何从代码覆盖率中测试或排除私有(private)无法访问的代码