[英]Unable to spy on existing function
我無法監視node.js
當前范圍內的現有功能:
function myFunc() {console.log("Spy on me and I'll have you arrested"};
sinon.spy(myFunc);
myFunc.restore(); // throws an error: myFunc.restore is not a function
但是,我可以監視作為對象成員的函數:
var anObject = {
myFunc: function() {console.log('Being spied on turns me on');}
};
sinon.spy(anObject, 'myFunc');
sinon.myFunc.restore(); // smooth sailing
根據文檔 ,在我看來,這應該可以正常工作。 我該如何完成?
在JavaScript中,將function
作為參數傳遞時,它是按值傳遞的引用,如下所示:
function foo() { console.log("foo"); } // func1, referenced by `foo`
function bar() { console.log("bar"); } // func2, referenced by `bar`
function mutate(func) {
func = bar;
}
mutate( foo );
foo();
這將打印出"foo"
,而不是"bar"
,因為mutatate
不會更改foo
對func1
的引用。
這是Sinon的spy.js
的相關源代碼: https : //github.com/sinonjs/sinon/blob/master/lib/sinon/spy.js
create
函數查看第一個參數是否為函數,如果是,則將其包裝在代理中( create: function create(func, spyLength) {
,第148行)。 然后,它返回代理。
因此,您需要用新的代理替換myFunc
:
function myFunc() {console.log("Spy on me and I'll have you arrested"};
myFunc = sinon.spy(myFunc); // here
但是,您不能使用myFunc.restore()
撤消間諜,因為.restore
無法更改myFunc
引用的目標。 請注意, restore
也不返回值,因此您必須自己跟蹤myFunc
:
function myFuncOriginal() {console.log("Spy on me and I'll have you arrested"};
var myFunc = sinon.spy(myFuncOriginal);
myFunc = myFuncOriginal; // instead of `myFunc.restore();`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.