2014-06-24 14 views
8

Tworzę dyrektywę element, który wywołuje usługę w swojej link funkcję:angularjs dyrektywa Link funkcja nazywa się w teście jaśminowym

app.directive('depositList', ['depositService', function (depositService) { 
    return { 
     templateUrl: 'depositList.html', 
     restrict: 'E', 
     scope: { 
      status: '@status', 
      title: '@title' 
     }, 
     link: function (scope) { 
      scope.depositsInfo = depositService.getDeposits({ 
       status: scope.status 
      }); 
     } 
    }; 
}]); 

Usługa jest trywialne teraz:

app.factory('depositService', function(){ 
    return { 
    getDeposits: function(criteria){ 
     return 'you searched for : ' + criteria.status; 
    } 
    }; 
}); 

I próbuję napisać test, który zapewnia, że ​​depositService.getDeposits() jest wywoływana z poprawną wartością statusu.

describe('Testing the directive', function() { 
    beforeEach(module('plunker')); 
    it('should query for pending deposits', inject(function ($rootScope, $compile, $httpBackend, depositService) { 

     spyOn(depositService, 'getDeposits').and.callFake(function(criteria){ 
     return 'blah'; 
     }); 

     $httpBackend.when('GET', 'depositList.html') 
      .respond('<div></div>'); 

     var elementString = '<deposit-list status="pending" title="blah"></deposit-list>'; 
     var element = angular.element(elementString); 
     var scope = $rootScope.$new(); 
     $compile(element)(scope); 
     scope.$digest(); 

     var times = depositService.getDeposits.calls.all().length; 
     expect(times).toBe(1); 
    })); 
}); 

test nie powiedzie się, ponieważ czasy === 0. Ten kod działa poprawnie w przeglądarce, ale w teście funkcja link i obsługa nigdy nie wydają się być wywołana. jakieś pomysły?

plunker: http://plnkr.co/edit/69jK8c

Odpowiedz

14

Ty brakowało $httpBackend.flush(), która opowiada mock $httpBackend aby powrócić do szablonu. Szablon nigdy nie był ładowany, więc funkcja linku dyrektywy nie miała nic do połączenia.

Fixed plunker: http://plnkr.co/edit/ylgRrz?p=preview

Kod:

describe('Testing the directive', function() { 
    beforeEach(module('plunker')); 
    it('should query for pending deposits', inject(function ($rootScope, $compile, $httpBackend, depositService) { 

     spyOn(depositService, 'getDeposits').and.callFake(function(criteria){ 
     return 'blah'; 
     }); 

     $httpBackend.when('GET', 'depositList.html') 
      .respond('<div></div>'); 

     var elementString = '<deposit-list status="pending" title="blah"></deposit-list>'; 
     var element = angular.element(elementString); 
     var scope = $rootScope.$new(); 
     $compile(element)(scope); 
     scope.$digest(); 

     $httpBackend.flush(); 

     var times = depositService.getDeposits.calls.all().length; 
     expect(times).toBe(1); 
    })); 
}); 
+0

wziąłem mnie zbyt długo, aby znaleźć tę informację. Dzięki! :) – Tudmotu

+0

Bardzo mi to pomogło, dzięki! –

Powiązane problemy