【问题标题】:SinonJS 101 errorSinonJS 101 错误
【发布时间】:2013-10-27 05:51:44
【问题描述】:

我正在尝试学习这项技术,但不知何故被卡在了开头。

请告诉我为什么这个测试不起作用。我错过了什么明显的事情?

var myfunc = function() {
    alert('hello');
}

test("should spy on myfunc", function() {
    var mySpy = sinon.spy(myfunc);
    myfunc();
    sinon.assert.calledOnce(mySpy);

});

【问题讨论】:

  • 这对我来说是正确的。你得到什么输出?

标签: qunit sinon


【解决方案1】:

这是 myfunc 的范围。这有效:

var o = {
    myfunc: function() {
        alert('hello');
    }
};

test("should spy on myfunc", function() {
    var mySpy = sinon.spy(o, "myfunc");
    o.myfunc();
    sinon.assert.calledOnce(mySpy);
    ok(true); 
});

【讨论】:

    【解决方案2】:

    您的测试不起作用的原因是您没有调用间谍,而是调用原始函数。

    @carbontax 的示例之所以有效,是因为在这种情况下,o.myfunc 会自动被间谍替换;所以当你调用o.myfunc时,你实际上是在调用间谍。

    【讨论】:

      【解决方案3】:

      正如 Mrchief 所说,您不是在调用 spy,而是在调用 myfunc();,您应该调用 spy 之类的东西。

      test("should spy on myfunc", function() {
          var mySpy = sinon.spy(myfunc);
          mySpy(); // <= should called instead of myfunc()
          sinon.assert.calledOnce(mySpy);
      });
      

      【讨论】:

        猜你喜欢
        • 2011-07-08
        • 1970-01-01
        • 1970-01-01
        • 2015-12-29
        • 1970-01-01
        • 1970-01-01
        • 2012-12-11
        • 2010-11-09
        • 1970-01-01
        相关资源
        最近更新 更多