2014-06-24 17 views
8

我創建,在其link函數調用的服務的元素指令:AngularJS向鏈路功能茉莉測試不叫

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 
      }); 
     } 
    }; 
}]); 

服務是平凡的現在:

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

我我試圖編寫一個測試,確保使用正確的狀態值調用depositService.getDeposits()。因爲次=== 0。這個代碼運行在瀏覽器中細

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); 
    })); 
}); 

測試失敗,但在測試中link功能和服務似乎從來沒有被調用。有什麼想法嗎?

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

回答

14

你失蹤$httpBackend.flush(),它告訴模擬$httpBackend返回一個模板。該模板從不加載,所以指令鏈接函數沒有任何可鏈接的地方。

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

代碼:

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

我把我的方式太長時間才找到這條信息。謝謝! :) – Tudmotu

+0

這幫了我很多,謝謝! –