【发布时间】: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