I've created directive which create link for images if the src of the image wasn't available as following:
var app = angular.module('myApp', []);
app.directive('defaultImage', function() {
return {
restrict: 'EA',
link: function(scope, element, attrs) {
var url = 'http://placehold.it/' + element.attr('default-image');
element.bind('error', function() {
element.addClass('default-image');
element.attr('src', url);
})
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<img ng-src="/logo.jpg" default-image="103x89" alt="Logo!" />
</div>
It works as expected, but what I want is to make a test unit for this directive, I tried many ways but I couldn't manage to make the test working correctly, the test code as follow:
'use strict';
describe('Directive: defaultImage', function () {
var element, compile, scope;
// load the directive's module
beforeEach(module('myApp'));
beforeEach(inject(function ($rootScope, $compile) {
scope = $rootScope;
compile = $compile;
}));
function compileImage(markup, scope){
var el = compile(markup)(scope);
scope.$digest();
return el;
}
it('should make image with default image src link', inject(function () {
var image = compileImage('<img ng-src="/logo.jpg" default-image="200x48" alt="Default Image!" class="img"/>', scope);
expect(image.attr('src')).toEqual('http://placehold.it/200x48');
}));
});
Thanx for any advice,