问题
I have directive that uses bootstrap's popover. It becomes popover when variable is set:
if (newValue.show === true) {
element.popover('show');
}
How can I make spy test with karma/jasmine tests?
I tried this:
spyOn(element, 'popover');
it('should call bootstrap method popover', function () {
$scope.$apply(function() {
$scope.value.show = true;
});
expect(element.popover).toHaveBeenCalled()
});
But I get error:
Expected spy popover to have been called.
Error: Expected spy popover to have been called.
回答1:
I am not convinced this is the best way to do this, but I was able to get it to work by storing the element on the scope and spying on it that way.
In your directive
scope.element = element;
if (newValue.show === true) {
scope.element.popover('show');
}
In your spec
spyOn(scope.element, 'popover')
...
it('should call bootstrap method popover', function () {
$scope.value.show = true;
$scope.$digest();//Or use your $scope.$apply
expect(scope.element.popover).toHaveBeenCalledWith('show');
});
Hope that helps.
UPDATE
popover is a jQuery plugin attached to $.fn
so we can spy on it.
https://gist.github.com/danmillar/1930277#file-bootstrap-popover-js-L160
it('should call bootstrap method popover', function () {
spyOn($.fn, 'popover');
$scope.value.show = true;
$scope.$digest();//Or use your $scope.$apply
expect($.fn.popover).toHaveBeenCalledWith('hide');
});
This is a nice explanation of why you can't listen on element https://stackoverflow.com/a/6198122/3403178
来源:https://stackoverflow.com/questions/24272107/testing-directive-that-uses-bootstrap-popover