I am trying to use sinon.js
to create a spy on the jQuery.append
function.
I tried: var spy = sinon.spy($, "append");
and got the following error: TypeError: Attempted to wrap undefined property append as function
.
I then amended to: var spy = sinon.spy($.fn, "append");
which seems better, but spy.called
is false.
I am trying to use sinon.js
to create a spy on the jQuery.append
function.
I tried: var spy = sinon.spy($, "append");
and got the following error: TypeError: Attempted to wrap undefined property append as function
.
I then amended to: var spy = sinon.spy($.fn, "append");
which seems better, but spy.called
is false.
- I moved some of this question to a new, hopefully clearer question - thanks to all those who tried to help me. Please see: stackoverflow./questions/17787893/… – davy Commented Jul 22, 2013 at 12:43
4 Answers
Reset to default 14Sinon.spy(object, "method")
expects an object for first parameter, but $
is a function. You should spy on $.prototype
like this:
var spy = sinon.spy($.prototype, "append");
fiddle: http://jsfiddle/RZ825/
or you can just spy single object like this:
var spy = sinon.spy($("body"), "append");
fiddle: http://jsfiddle/G5J8H/
I realize this question is old but I had a similar problem and found a solution to it.
I tried one of the anwsers suggested above.
var spy = sinon.spy($("body"), "append");
my version:
var spy = sinon.spy($("#id"), "function");
However this did not work and it took me some time to figure out why. Turns out that you need to access the array after the jQuery object.
Like this:
var spy = sinon.spy($("#id")[0], "function");
Sinon does not do anything with the jQuery object itself because it can contain multiple values and it doesn't know which one you want (even if there is just one).
PS: I've noticed this does not work for all jquery functions. For me it worked for "focus". PPS: This might not be relevant for this question. But what I've been trying to do is trigger a focus event within karma-runner. So far I've been unsuccesful (click event does work however). I will post a question on StackOverflow for this.
I think You can't spy for jQuery functions - they are binded to every object. It works like this:
- You call method on jQuery object.
- jQuery check for it in own $.fn.
- jQuery check for it in plugins.
And if found - return it. If not - error. Sinon wouldn't work here.
You have to spy on $
and return an object that has the append function as a spy
var spy = jasmine.createSpy();
sinon.spy(window, "$").returns({append: spy})