AngularJS directory reference function not called in jasmine test

I create an element directive that calls the service in my link function:

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

The service is trivial:

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

I am trying to write a test that ensures that depositService.getDeposits() is called with the correct status value.

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

The test failed because the time === 0. This code works fine in the browser, but in the test the link function and the service are never called. Any thoughts?

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

+8
javascript angularjs jasmine
source share
1 answer

You are missing $httpBackend.flush() , which tells mock $httpBackend to return the template. The template never loaded, so the directory link function had nothing to do with it.

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

the code:

 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); })); }); 
+14
source share

All Articles