javascript - AngularJS:如何 Jasmine 测试指令中的回调函数?

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

到目前为止,我的 Jasmine 测试是:

'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) 调用在 div 中放置了一个 SVG,我的第二个测试对此进行了测试并且工作正常。然而回调函数不在我的测试范围内,我如何接触回调函数?回调函数由 elem.highcharts 函数调用,所以我的直觉是我注入(inject)了一个 Jasmin Spy 作为伪造的“highcharts”函数……但是,由于这是一个指令,我不知道该怎么做。

最佳答案

在测试中创建一个类

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%!

关于javascript - AngularJS:如何 Jasmine 测试指令中的回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25501135/

相关文章:

jQuery 验证器和 bootstrap.js - 通知/错误

javascript - 如何使用 javascript/jquery 从数组中获取最大和最小日期?

javascript - Angular 指令将 ngmodel 值从 null 更改为未定义会破坏验证

javascript - 如何使用 ng-class 渲染这个 Angular 变量

javascript - jQuery slideToggle - 仅 slideUp Action 的回调函数

javascript - 单击时将类 "active"应用于导航链接?

jquery - 获取错误 : Uncaught TypeError: undefined is not a function bootstrap. js :29 (anonymous function) bootstrap. js:29(匿名函数)

angularjs - 如何在 Angular ui-router 中使用继承的参数?

javascript - 接连播放音频

javascript - 对大多数请求使用 socket.io 是不好的还是我应该只使用它来将数据推送到客户端?