How to Unit test an angular directive that has a binding ('error', function () {})?
I have an angular directive that replaces the src image of an element if the file doesn't exist and a 404 is returned. Here it is:
myApp.directive('fallBackSrc', function() {
var fallBackSrc = {
link: function postLink(scope, element, attrs) {
element.bind('error', function () {
angular.element(this).attr("src", '/images/image-not-available.png');
});
}
}
return fallBackSrc;
}]);
This works as expected, but now I am trying to unit test this directive, how can I cause an "error" associated with this function in jasmine?
source to share
To test this, you need to spyOn the element.bind with Jasmine and also use the Jasmines 2.0 done function.
So, in my example in jsfiddle, I added the place owner image as a placeholder image to stop it from throwing an error.
angular.module('components', [])
.directive('fallBackSrc', function() {
var fallBackSrc = {
link: function postLink(scope, element, attrs) {
element.bind('error', function () {
angular.element(this).attr("src", 'http://placehold.it/350x150');
});
}
}
return fallBackSrc;
});
and in the test we can spyOn
element.bind
and return error
when it is called
spyOn(element, 'bind').and.returnValue('error');
We also need to use the executed function to run specifications that require testing asynchronous operations by passing it to a test for use in setTimeOut
.
describe('Directive: fallBackSrc', function() {
describe('if the image does not exist it', function() {
var element, scope;
beforeEach(module('components'));
beforeEach(inject(function($rootScope, $compile) {
element = angular.element('<img fall-back-src src="images/no-image.jpg" />');
spyOn(element, 'bind').and.returnValue('error');
scope = $rootScope;
$compile(element)(scope);
scope.$digest();
}));
it("should contain the place holder img src", function(done) {
setTimeout(function(){
console.log(element.attr('src'));
expect(element.attr('src')).toEqual('http://placehold.it/350x150');
done();
}, 2000);
});
});
});
source to share