I'm trying to unit test a simple directive which looks as follows:
angular.module('blog').directive('imageOnLoad', function() {
return {
restrict: 'A',
link: function(scope, element, attrs, fn) {
element.bind('load', function() {
scope.$emit('resizeContent');
});
}
};
});
The two things I can see that I need to test here are that it binds to the image load event, which in turn emits the resizeContent event.
I have the following in my unit test - currently just testing the event binding:
describe('imageOnLoad', function() {
beforeEach(module('blog'));
var scope,compile, element;
beforeEach(inject(function($rootScope,$compile) {
scope = $rootScope.$new();
compile = $compile;
var elementString = '<img ng-src="123.jpg" image-on-load />';
element = $compile(elementString)(scope);
}));
it('should bind to the load event of the image', function() {
spyOn(element, 'bind').andCallThrough();
expect(element.bind).toHaveBeenCalled();
});
});
My problem: The load event never seems to fire. My first guess is that it's because the 123.jpg image doesn't exist - and if so, my question is how to go about mocking that so I don't have to carry a physical image file in there.
element = $compile(elementString)(scope);
Try right after that line - that should work:
element.trigger('load');
Testing jQuery noodles is not much good idea btw.