AngularJS:如何在指令中测试jasmine测试回调函数?

时间:2014-08-26 08:21:01

标签: javascript jquery angularjs highcharts jasmine

我有一个非常简单的指令,可以创建一个HighCharts图。我只包含了这个问题最重要的内容:

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);
    }
};
}]);

到目前为止,我的茉莉花测试是:

'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 () {
        // ?????????????
    });
});
});

elem.highcharts(configuration)调用将一个SVG放入div中,我的第二个测试测试了这个并且它工作正常。然而,我的测试不涉及回调功能,如何触摸回调功能?回调函数由elem.highcharts函数调用,所以我的直觉是我将一个Jasmin Spy注入假的&#39; highcharts&#39;功能...但是,因为这是一个指令,我不知道如何做到这一点。

1 个答案:

答案 0 :(得分:0)

在测试中创建一个类

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

并在单元测试中添加

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

测试回调函数,覆盖率为100%!