【问题标题】:Testing directive that uses bootstrap popover使用引导弹出窗口的测试指令
【发布时间】:2014-06-17 19:45:31
【问题描述】:

我有使用引导程序弹出框的指令。设置变量时会弹出:

if (newValue.show === true) {
     element.popover('show');
}

如何使用 karma/jasmine 测试进行间谍测试?

我试过了:

    spyOn(element, 'popover');



    it('should call bootstrap method popover', function () {
    $scope.$apply(function() {
        $scope.value.show = true;
    });
    expect(element.popover).toHaveBeenCalled()
});

但我得到错误:

    Expected spy popover to have been called.
    Error: Expected spy popover to have been called.

【问题讨论】:

    标签: angularjs twitter-bootstrap unit-testing jasmine karma-runner


    【解决方案1】:

    我不相信这是最好的方法,但我能够通过将元素存储在范围内并以这种方式监视它来使其工作。

    在你的指令中

    scope.element = element;
    if (newValue.show === true) {
     scope.element.popover('show');
    }
    

    在你的规范中

    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');
    });
    

    希望对您有所帮助。

    更新

    popover 是一个附加到$.fn 的 jQuery 插件,因此我们可以监视它。 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');
    });
    

    这是一个很好的解释为什么你不能听元素 https://stackoverflow.com/a/6198122/3403178

    【讨论】:

    • 当我尝试以这种方式创建间谍 - spyOn($.fn, 'popover') 时,出现错误 - Chrome 51.0.2704 (Windows 7 0.0.0) ERROR Uncaught TypeError: $(.. .).popover 不是函数。我应该在 beforeEach() 中注入任何依赖项吗?
    • 你包含插件了吗?它不是核心 jQuery 库的一部分。
    • 感谢您回来。是的,popover() 是 bootstrap.js 的一部分,所以我必须在浏览器依赖项下的 karma.conf.js 中包含 bootstrap.js。解决了!
    • 很高兴听到修复它!
    猜你喜欢
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    相关资源
    最近更新 更多