我有一个非常简单的指令来创建 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/