简体   繁体   English

如何使用 jasmine 测试 jquery 选择器

[英]How to test jquery selector with jasmine

We need to test a function which evaluates the top position of an element.我们需要测试一个评估元素顶部位置的函数。 In the following example an element with an id 'test'.在下面的示例中,一个带有 id 'test' 的元素。

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

In order to test this function with jasmine we tried the following test approach:为了用 jasmine 测试这个功能,我们尝试了以下测试方法:

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

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

and get the error:并得到错误:

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

Including my comment as answer.包括我的评论作为答案。

getBoundingClientRect is not part of jquery so you wont be able to get the value from that when you spy on it. getBoundingClientRect 不是 jquery 的一部分,因此当您监视它时,您将无法从中获取值。

Instead you can pass the element directly document.querySelector("#test").相反,您可以直接传递元素 document.querySelector("#test")。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM