Sinon Spy not working with Javascript call or apply

眉间皱痕 提交于 2019-12-12 01:47:40

问题


I'm trying to use sinon.spy to check if the play function is being called for a component. The problem is that the spy counter is not updating, even though I've confirmed that my component's function is indeed being called.

I've tracked it down to the use of Javascript's call function:

handleDone: function(e) {
  for (var i = 0; i < this.components.length; i++) {
    if (this.components[i].element === e.target) {
      if (this.components[i].hasOwnProperty("play")) {
        // This won't trigger the spy.
        this.components[i]["play"].call(this.components[i].element);
      }
      break;
    }
  }
}

A similar thing happens when swapping call for apply.

[UPDATED] Here is the relevant test:

var page = document.getElementById("page"),
  demo = document.getElementById("demo"),
  playSpy;

suiteSetup(function() {
  playSpy = sinon.spy(demo, "play");
});

suiteTeardown(function() {
  demo.play.restore();
});

suite("done", function() {
  test("rise-component-done fired from element with play property", function() {
    assert(playSpy.notCalled);  //true
    demo.sendDone();
    assert(playSpy.calledOnce); //false
  });
});

And the play and sendDone functions in the demo component:

play: function() {
  console.log("play");
},

sendDone: function() {
  this.dispatchEvent(new CustomEvent("rise-component-done", { "bubbles": true }));
}

The page component is registered to listen for this event:

this.addEventListener("rise-component-done", this.handleDone);

Anyone know of a workaround?

Thx.


回答1:


So the problem wasn't actually related to the call method at all as Ben illustrated. After much tinkering, I realized I had to change this line:

playSpy = sinon.spy(demo, "play");

to this:

playSpy = sinon.spy(page.components[0], "play");

Now my tests pass. Hooray! I just wish it hadn't taken me the better part of a day to debug.



来源:https://stackoverflow.com/questions/29370799/sinon-spy-not-working-with-javascript-call-or-apply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!