I'm creating an element directive that calls a service in its 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 for now:
app.factory('depositService', function(){
return {
getDeposits: function(criteria){
return 'you searched for : ' + criteria.status;
}
};
});
I am trying to write a test that ensures that the 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 fails because times === 0. This code runs fine in the browser, but in the test the link
function and the service never seem to be called. Any thoughts?
plunker: http://plnkr.co/edit/69jK8c
You were missing $httpBackend.flush()
, which tells the mock $httpBackend
to return a template. The template was never loading, so the directive link function had nothing to link against.
Fixed plunker: http://plnkr.co/edit/ylgRrz?p=preview
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);
}));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With