如果我通過var a = sinon.createStubInstance(MyContructor)
創建實例。使用Sinon時,如何替換存根實例中的存根函數?
我該如何更換var stub = sinon.stub(object, "method", func);
之類的殘存功能之一。
主要的原因,我這樣做是想實現多回調的解決方法爲this mentioned
如果我通過var a = sinon.createStubInstance(MyContructor)
創建實例。使用Sinon時,如何替換存根實例中的存根函數?
我該如何更換var stub = sinon.stub(object, "method", func);
之類的殘存功能之一。
主要的原因,我這樣做是想實現多回調的解決方法爲this mentioned
我不認爲這確實讓很多的意義,因爲如果你用另一個存根替換存根..那你爲什麼不用第一個存根來實現你想要做的第二個存根。
反正,所述sinon.stub(object, "method", func)
將執行以下操作,根據該文檔:
替換
object.method
與func
,包裹在間諜。像往常一樣,object.method.restore()
;可以用來恢復原來的方法。
所以,如果你想更換一個存根實例的存根功能,那麼你爲什麼不這樣做:
var a = sinon.createStubInstance(MyConstructor);
a.method = sinon.spy(function() { return "Foo Bar"; });
或者,如果你想創建一個間諜代替存根:
var a = sinon.createStubInstance(MyConstructor);
a.method = sinon.stub();
磕碰使用sinon.createStubInstance(MyConstructor)
或整個對象後sinon.stub(obj)
只能通過兩種分配一個新的存根屬性(如@ g00glen00b描述)或重新磕碰之前恢復存根更換存根。
var a = sinon.createStubInstance(MyConstructor);
a.method.restore();
sinon.stub(object, "method", func);
這樣做的好處是,您仍然可以調用a.method.restore()
預期的行爲。
如果Stub API有一個.call(func)
方法覆蓋存根後由存根調用的函數將會更方便。
在調用a.method = sinon.stub()之前,調用a.method.restore()很重要。 – Ajitesh
這個答案讓我走上了正軌。雖然這是回答'sinon.stub(object,「method,fn)'已被棄用。我們現在可以使用'sinon.stub(object,「method」)。callsFake(function(){// do stuff});'See [here](http://sinonjs.org/releases/v2.3.1/stubs #stubcallsfakefakefunction) _Edit:fixed url_ –
@PhilD。你是對的,但問題本身是要求'sinon.stub(object,「method」,fn)',所以我認爲我不會在答案中包含這些信息。 – g00glen00b