我有一个显示工具提示的指令,如下所示:
angular.module('cui.directives.cuiEllipsisTooltip', [])
.directive('cuiEllipsisTooltip', ['$compile', '$timeout',
function($compile, $timeout) {
'use strict';
return {
restrict: 'A',
scope: true,
link: function(scope, element, attrs) {
var raw = element[0];
var hasTooltip = false;
var leaveEventPromise = null;
element.on('mouseenter', function() {
if (raw.offsetWidth < raw.scrollWidth) {
if (hasTooltip) {
scope.enabled = true;
} else {
scope.tooltip = element.text();
scope.enabled = true;
element.attr('data-toggle', 'tooltip')
.attr('data-original-title', scope.tooltip)
.removeAttr('cui-ellipsis-tooltip');
$compile(element)(scope);
hasTooltip = true;
element.tooltip('show');
$timeout(function() {
element.trigger('mouseenter');
});
}
leaveEventPromise = null;
} else {
scope.enabled = false;
}
});
element.on('mouseleave', function() {
element.tooltip('hide');
if (leaveEventPromise === null) {
leaveEventPromise = $timeout(function() {
element.trigger('mouseleave');
}, 50);
}
});
scope.$watch(function() {
return element.text();
}, function(newVal, oldVal) {
if (newVal !== oldVal) {
scope.tooltip = newVal;
}
});
}
};
}
]);
我写了一个单元测试来测试指令,如下所示:
it('should show tooltip when the text is truncated', function() {
// Given
var text = 'testestestestestestestestestest';
element = angular.element('<div cui-ellipsis-tooltip style="width: 30px;">' + text + '</div>');
element.appendTo(document.body);
$compile(element)($scope);
$scope.$digest();
// When
element.trigger('mouseenter');
// $timeout.flush();
// Then
var tooltip = element.next();
expect(tooltip.length).toBe(1);
expect(tooltip.hasClass('tooltip')).toBe(true);
expect(tooltip.text().trim()).toEqual(text);
});
它给了我错误
TypeError: undefined is not a constructor (evaluating 'element.tooltip('show')').
我在StackOverflow上搜索并发现当您尝试调用未定义的函数时会发生此错误。所以这个function tooltip('show')
的JQuery不被Karma-Jasmine认可。我该怎么办?