'AngularJS: How to jasmine test callback function in directive?

I have a very simple directive which creates a HighCharts graph. I have only included the most important for this question:

angular.module('myModule').directive('myDirective', [function () {
'use strict';

return {
    restrict: 'AE',
    transclude: true,
    replace: true,
    scope: {},
    template: '<div ng-transclude></div>',

    link: function (scope, elem, attrs) {

        var sampleInput= JSON.parse(attrs.sampleInput);

        var someCallback = function () {
            return this.series.name + '<b>' + this.y + '</b>';
        };


        var configuration = {
            tooltip: {
                enabled: true,
                text: sampleInput.a;
                formatter: someCallback
            }
        };

        elem.highcharts(configuration);
    }
};
}]);

My Jasmine test I have so far is:

'use strict';

describe('Given the myDirective directive', function () {
var rootScope, scope, compile, graphElement1,graphElement2, graphElement3;

beforeEach(inject(function ($compile, $rootScope, $window) {
    rootScope = $rootScope;
    scope = rootScope.$new();
    compile = $compile;

    scope.sampleInput11 = { a: 0, b: 1 };

    graphElement1 = angular.element( '<div my-directive sample-input="{{sampleInput11}}" />');

    compile(graphElement1)(scope);
    scope.$digest();
}));


describe('the directive', function () {
    it('should be defined', function () {
        expect(graphElement1).toBeDefined();
    });

    it('should generate SVG', function () {
        expect(graphElement1[0].getElementsByTagName('svg').length).toBeGreaterThan(0);
    });

    it('should call the tooltipHtml callback function', function () {
        // ?????????????
    });
});
});

The elem.highcharts(configuration) call puts a SVG in the div, my second test tests this and it works fine. The callback fucntion is however not covered by my tests, how can I touch the callback function? The callback function is called by the elem.highcharts function, so my gut feeling would be that I inject a Jasmin Spy as fake 'highcharts' function... however, since this is a directive I don't know how to do this.



Solution 1:[1]

In the test create a class

function FormatMock() { 
    this.series = {'name': "XXX"}; 
    this.y = 100; 
}

and in the unit test add

var myFormatter = new FormatMock(); 
myFormatter.formatter = graphElement1.highcharts.mostRecentCall.args[0].tooltip.formatter; 
var formatOutput = myFormatter.formatter();
expect(formatOutput).toStartWith('SERIE');` 

The callback function is tested and the coverage is 100%!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1