2

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,

0

    1 Answer 1

    1

    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

    • Open a browser and navigate to http://localhost:9876/debug.html (default karma configuration, may vary)
    • Start your developer tools and place breakpoints in the directive and the directive test
    • Refresh
    • Breakpoints will be hit

    With this approach you can narrow down any problems in your tests more easily.

    Cheers

    1
    • thanx man that fixed it, and now I have the directive and the unit test working perfectly
      – Ya Basha
      CommentedOct 17, 2014 at 13:17

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.