2016-07-02 36 views
2

根據sinon.js的文檔,我可以這樣做:var spy = sinon.spy(myFunc);,但它不起作用。這是我的努力:Sinon間諜功能不起作用

var sinon = require("sinon"); 

describe('check bar calling', function(){ 
    it('should call bar once', function() { 
    var barSpy = sinon.spy(bar); 

    foo("aaa"); 

    barSpy.restore(); 
    sinon.assert.calledOnce(barSpy); 
    }); 
}); 

function foo(arg) { 
    console.log("Hello from foo " + arg); 
    bar(arg); 
} 

function bar(arg) { 
    console.log("Hellof from bar " + arg); 
} 
+0

[驗證函數調用和檢查參數使用興農間諜]的可能的複製(https://stackoverflow.com/questions/29800733/verifying-function-call-and-inspecting-arguments-using-sinon-spies ) –

回答

2

Sinon包裝的調用它不補丁所有引用。返回值是一個封裝的函數,您可以對其進行斷言。它記錄所有對它的調用,而不是它所包裝的功能。修改foo使調用者提供一個函數,允許間諜被注入,並允許調用間諜。

var sinon = require("sinon"); 

describe('check bar calling', function(){ 
    it('should call bar once', function() { 
    var barSpy = sinon.spy(bar); 

    foo("aaa", barSpy); 

    barSpy.restore(); 
    sinon.assert.calledOnce(barSpy); 
    }); 
}); 

function foo(arg, barFn) { 
    console.log("Hello from foo " + arg); 
    barFn(arg); 
} 

function bar(arg) { 
    console.log("Hellof from bar " + arg); 
} 
+0

謝謝,它的工作原理,但沒有'barSpy.restore();' –