【问题标题】:How to test jquery selector with jasmine如何用 jasmine 测试 jquery 选择器
【发布时间】:2018-02-14 17:41:14
【问题描述】:

我们需要测试一个评估元素顶部位置的函数。在下面的示例中,一个 id 为“test”的元素。

function xxx(){
    var element = $('#test');
    return element[0].getBoundingClientRect().top;
}

为了用茉莉花测试这个功能,我们尝试了以下测试方法:

var myObj = {
                name: 'test',
                getBoundingClientRect: function () {
                    return {top: 100}
                }
            }

spyOn($('#test'), 'getBoundingClientRect').and.returnValue([myObj]);

并得到错误:

Error: <spyOn> : getBoundingClientRect() method does not exist
    Usage: spyOn(<object>, <methodName>) (line 4740)

【问题讨论】:

  • getBoundingClientRect 不是 jquery 的一部分,所以你不能那样做。为什么不通过 document.querySelector("#test") ?
  • 你检查了吗spyOn($('#test')[0], 'getBoundingClientRect').and.returnValue([myObj]);
  • 是的,我检查了 pyOn($('#test')[0], 'getBoundingClientRect').and.returnValue([myObj]);,给出另一个错误'错误::可以找不到对象来监视 getBoundingClientRect()'
  • @karthick 是的,谢谢,切换到 document.querySelector,一切都很好。
  • @ABX。伟大的。包括我的评论作为答案。

标签: javascript angularjs jasmine


【解决方案1】:

包括我的评论作为答案。

getBoundingClientRect 不是 jquery 的一部分,因此当您监视它时,您将无法从中获取值。

相反,您可以直接传递元素 document.querySelector("#test")。

spyOn(document.querySelector("#test"), 'getBoundingClientRect').and.returnValue([myObj]);

【讨论】:

  • 您可以模拟element[0](因此可以通过在jQuery.prototype.init 上放置一个间谍来模拟getBoundingClientRect,参见stackoverflow.com/a/36356692/3731501),但这是不必要的。直接模拟 getBoundingClientRect 在这里可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-17
  • 1970-01-01
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
  • 2016-03-17
相关资源
最近更新 更多