[英]Restore spied/stubbed function with Sinon sandbox
Sinon沙箱(或sinon
實例)從外部傳遞到腳本范圍。 內部函數(不是方法)可以選擇使用Sinon沙箱進行間諜/存根。
Sinon參與了某種猴子修補(不是單元測試).Sinon沙盒概念非常適合用例 - 直到這一刻。
我從函數間諜不能被方法間諜取代的事實出發。 這不是一個完美的場景,但設計無法改變。
const originalCallback = callback;
callback = sinonSandbox.spy(callback);
thirdPartyFn(callback);
// how can this be achieved?
// sinonSandbox.onRestore(() => thirdPartyFn(originalCallback));
如何在恢復沙箱恢復間諜功能時通知應用程序? 是否有關於'恢復'事件的啟動? 是否有可能有幫助的第三方Sinon擴展?
我會模擬/存根恢復功能:
var originalRestore = sinonSandbox.restore;
sinonSandBox.restore = () => {
originalRestore();
// insert code here
};
最初,sinon不會發布任何事件或提供任何鈎子,但你可以創建一個:
var spyInstance = sinonSandbox.spy(callback);
(function (original) {
spyInstance.restore = function() {
original.apply(this, arguments); // call the original restore function
events.publish("sinon", "restore-end"); // publish the event to decouple this module from receiving module
}
})(spyInstance.restore);
然后,在另一個模塊的某個地方:
events.subscribe("sinon", "restore-end", function() {
// call some code to execute when the sinon spy is restored
});
events對象只是你的全局pub / sub模塊或類似的東西。
如圖所示,Sinon沒有沙箱恢復通知機制。 由於sandbox.restore()
的工作是在每個偽造的函數上調用restore
方法 ,我最后修補了假的自己的restore
作為最合適的解決方案:
const originalCallback = callback;
callback = sinonSandbox.spy(callback);
const originalRestore = callback.restore;
callback.restore = function (...args) {
originalRestore.apply(this, args);
thirdPartyFn(originalCallback);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.