Reputation: 1952
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,
Upvotes: 2
Views: 188
Reputation: 3565
You are binding to the error event in your directive
element.bind('error', function() {
element.addClass('default-image');
element.attr('src', url);
})
The above piece of code however never gets triggered in your test, hence it will always fail. Just triggering an error manually in your test will fix the problem.
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);
image.error(); // Trigger the error manually
expect(image.attr('src')).toEqual('http://placehold.it/200x48');
}));
You can debug your karma tests from any browser
http://localhost:9876/debug.html
(default karma configuration, may vary)With this approach you can narrow down any problems in your tests more easily.
Cheers
Upvotes: 1