最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to spy on jQuery's append function Sinon - Stack Overflow

programmeradmin3浏览0评论

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.

Share Improve this question edited Jul 22, 2013 at 12:30 davy asked Jul 22, 2013 at 10:05 davydavy 4,56210 gold badges50 silver badges72 bronze badges 1
  • 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
Add a ment  | 

4 Answers 4

Reset to default 14

Sinon.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})
发布评论

评论列表(0)

  1. 暂无评论