本文介绍了Sinon Spy 无法使用 Javascript 调用或应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 sinon.spy 来检查是否正在为组件调用 play 函数.问题是间谍计数器没有更新,即使我已经确认我的组件的函数确实被调用了.

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.

我已经追踪到它使用了 Javascript 的 call 函数:

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;
    }
  }
}

call 换成 apply 时也会发生类似的事情.

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
  });
});

以及demo组件中的playsendDone函数:

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

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

page 组件已注册以侦听此事件:

The page component is registered to listen for this event:

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

有人知道解决方法吗?

谢谢.

推荐答案

因此问题实际上与 Ben 说明的 call 方法完全无关.经过多次修修补补,我意识到我必须改变这一行:

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");

为此:

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.

这篇关于Sinon Spy 无法使用 Javascript 调用或应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:56