ABX
ABX

Reputation: 1149

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'.

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

In order to test this function with jasmine we tried the following test approach:

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)

Upvotes: 1

Views: 3041

Answers (1)

karthick
karthick

Reputation: 12176

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.

Instead you can pass the element directly document.querySelector("#test").

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

Upvotes: 2

Related Questions