2015-09-02 1 views
0

Я не уверен, как я могу проверить эту директиву, может ли кто-нибудь предоставить фрагмент кода? Вот моя директива:Как проверить директиву с жестко закодированным звонком AJAX?

.directive('checkUnique', ['$http', function($http) { 
    return { 
     require: 'ngModel', 
     link: function(scope, ele, attrs, c) { 
      var origonalVal = attrs.ignoreUniqueValue; 

      scope.$watch(attrs.ngModel, function() { 
       var toURL= 'to/an/api';     
       $http({ 
        method: 'GET', 
        url: toURL 
       }).success(function(isUnique,status,headers,cfg) { 
        var iu = isUnique == 'true' ? true : false; 
        c.$setValidity('unique', iu); 
       }).error(function(data,status,headers,cfg) { 
        c.$setValidity('unique', false); 
       }); 
      }); 
     } 
    } 
}]) 
+0

Используйте $ httpBackend подделать вызов сервера и предоставить свой собственный ответ. –

+1

Не очень хорошая идея делать запросы в этой директиве в первую очередь. – dfsq

ответ

2

Прежде всего, это нехорошо иметь эту логику в функции связи вашей директивы. Вот подстава, что я хотел бы использовать (упрощенный и не тестировался):

var myApp = angular.module('myApp', []); 

myApp.factory('dataService', function($q, $http){ 
    return { 
     isUnique: function(){ 
      return $q(function(resolve, reject){ 
       $http({ 
        method: 'GET', 
        url: 'to/an/api' 
       }).success(function(isUnique,status,headers,cfg) { 
        resolve(isUnique == 'true'); 
       }).error(function(data,status,headers,cfg) { 
        reject(); 
       }); 
      }); 
     } 
    } 
}); 

myApp.controller('UniqueController', function($scope, dataService){ 
    var vm = this, 
     unWatchNgModel; 

    unWatchNgModel = $scope.$watch('ngModel', onNgModelChanged); 
    $scope.$on('$destroy', onDestroy); 

    function onNgModelChanged(){ 
     dataService.isUnique().then(function(unique){ 
      vm.ngModelCtrl.$setValidity('unique', unique); 
     }); 
    }  

    function onDestroy(){ 
     unWatchNgModel(); 
    } 
}); 

myApp.directive('checkUnique', ['$http', function($http) { 
    return { 
     require: ['checkUnique', 'ngModel'], 
     scope: { 
      ngModel: '=' 
     } 
     controller: 'UniqueController', 
     controllerAs: 'unique', 
     bindToController: true 
     link: link 
    }; 

    function link(scope, ele, attrs, ctrls) { 
     var checkUniqueCtrl = ctrls[0], 
      ngModelCtrl = ctrls[1]; 

     checkUniqueCtrl.ngModelCtrl = ngModelCtrl; 
    } 
}]); 

Чтобы проверить это (АЯКС часть), используйте настройки, как это:

// Note that you need the 'ngMockE2E' module to have access to the $httpBackend service. 
describe('dataService', function() { 
    'use strict'; 

    var dataService; 

    beforeEach(function() { 

     module('myApp'); 

     inject(function($injector) { 
      dataService = $injector.get('dataService'); 
      $httpBackend = $injector.get('$httpBackend'); 
     }); 
    }); 

    describe('isUnique', function() { 

     it('should return true if the API returns true as value.', function() { 
      // Setup 
      var successSpy = jasmine.createSpy('success'); 

      $httpBackend.expectGET(endpoint).respond(200, 'true'); 

      // Execute 
      dataService.isUnique(successSpy); 
      $httpBackend.flush(); 

      // Test 
      expect(successSpy).toHaveBeenCalledWith(true); 
     }); 

     it('should return false if the API does not return true as value.', function() { 
      // Setup 
      var successSpy = jasmine.createSpy('success'); 

      $httpBackend.expectGET(endpoint).respond(200, 'bogus'); 

      // Execute 
      dataService.isUnique(successSpy); 
      $httpBackend.flush(); 

      // Test 
      expect(successSpy).toHaveBeenCalledWith(false); 
     }); 
    }); 

});