1

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)
ABX
  • 1,173
  • 2
  • 22
  • 39
  • getBoundingClientRect is not part of jquery so you wont be able to do it like that. why not pass the document.querySelector("#test") ? – karthick Feb 14 '18 at 17:52
  • Did you check `spyOn($('#test')[0], 'getBoundingClientRect').and.returnValue([myObj]);` – Ashish Feb 14 '18 at 19:29
  • Yes I checked pyOn($('#test')[0], 'getBoundingClientRect').and.returnValue([myObj]);, gives another error 'Error: : could not find an object to spy upon for getBoundingClientRect()' – ABX Feb 14 '18 at 19:45
  • @karthick yes, thanks , switched to document.querySelector and everything is fine. – ABX Feb 14 '18 at 20:15
  • @ABX. Great. Including my comment as answer. – karthick Feb 14 '18 at 20:19

1 Answers1

2

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]);
karthick
  • 11,998
  • 6
  • 56
  • 88
  • You can mock `element[0]` (and thus getBoundingClientRect, by putting a spy on jQuery.prototype.init, see https://stackoverflow.com/a/36356692/3731501 ), but this is unnecessary. Mocking getBoundingClientRect directly will work here. – Estus Flask Feb 14 '18 at 20:31