javascript - How to test AngularJS $asyncValidators including a $http call -
javascript - How to test AngularJS $asyncValidators including a $http call -
i'm trying write jasmine test angularjs email availability checker, uses angular latest feature - $asyncvalidators pipeline. here directive:
au_helper.directive('recordavailabilityvalidator', ['$http', function ($http) { homecoming { require: 'ngmodel', link: function (scope, element, attrs, ngmodel) { var apiurl = attrs.recordavailabilityvalidator; var ownid = attrs.recordavailabilityid; ngmodel.$asyncvalidators.unavailable = function(value) { homecoming $http({method: 'get', url: apiurl, params: {v: value, id: ownid}}); }; } } }]);
in test seek setup backend response so:
$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;
and test it:
it('should show error if creating record existing email', function () { form.email.$setviewvalue('test@email.com'); $scope.$digest(); expect(form.email.$error.unavailable).tobedefined(); });
however, $error.unavailable undefined.
thanks help!
you need flush $httpbackend phone call happen
it('should show error if creating record existing email', function () { form.email.$setviewvalue('test@email.com'); $scope.$digest(); $httpbackend.flush(); expect(form.email.$error.unavailable).tobetruthy(); });
javascript angularjs unit-testing angularjs-directive karma-jasmine
Comments
Post a Comment