Testing directive that uses bootstrap popover

回眸只為那壹抹淺笑 提交于 2019-12-24 10:35:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!