2014-06-24 19 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

这帮了我很多,谢谢! –