[英]Difference between fake, spy, stub and mock of sinon library ( sinon fake vs spy vs stub vs mock )
我試圖理解 sinon 庫的 fake、spy、stub 和 mock 之間的區別,但無法清楚地理解它。
任何人都可以幫助我了解它嗎?
只是為了理解目的調用
FuncInfoCollector = 是一個 Function,它記錄 arguments、返回值、this(context) 的值以及所有調用的異常拋出(如果有的話)。 (這個 FuncInfoCollector 是我給的虛擬名稱,它不存在於 SINO 庫中)
Fake
= FuncInfoCollector + 只能創建一個假的 function,它不能包裝一個已經存在於被測系統中的 function
假貨是不可變的:一旦創建,行為就無法改變。
var fakeFunc = sinon.fake.returns('foo');
fakeFunc();
// have call count of fakeFunc ( It will show 1 here)
fakeFunc.callCount;
Spy
= FuncInfoCollector + can create new function + 它可以包裝一個已經存在於被測系統中的 function。
當測試的目標是驗證某事發生時,Spy 是一個不錯的選擇。
// Can be passed as a callback to async func to verify whether callback is called or not?
const spyFunc = sinon.spy();
// Creates spy for ajax method of jQuery lib
sinon.spy(jQuery, "ajax");
// will tell whether jQuery.ajax method called exactly once or not
jQuery.ajax.calledOnce
Stub
= 間諜 + 它存根原始 function(可用於更改原始函數的行為)
var err = new Error('Ajax Error');
// So whenever jQuery.ajax method is called in a code it throws this Error
sinon.stub(jQuery, "ajax").throws(err)
// Here we are writing assert to check where jQuery.ajax is throwing an Error or not
sinon.assert.threw(jQuery.ajax(), err);
Mock
= 存根 + 預編程的期望
var mk = sinon.mock(jQuery)
// Should be called atleast 2 time and almost 5 times
mk.expects("ajax").atLeast(2).atMost(5);
// It throws the following exception when called ( assert used above is not needed now )
mk.expects("ajax").throws(new Error('Ajax Error'))
// will check whether all above expectations are met or not, hence assertions aren't needed
mk.verify();
只是為了向其他好的答案添加更多信息,由於其他原始 API(Stub 和 Spy)的缺點,我們將 Fake API 添加到 Sinon。 這些 API 可鏈接的事實導致了不斷的設計問題和反復出現的用戶問題,並且它們被臃腫以迎合相當不重要的用例,這就是為什么我們選擇創建一個新的不可變 API,它更易於使用、更少歧義和維護成本更低。 它建立在 Spy 和 Stub API 之上,讓 Fakes 在某種程度上具有可識別性,並具有用於替換對象上的 props 的顯式方法( sinon.replace(obj,'prop',fake)
)。
假貨基本上可以在任何可以使用存根或間諜的地方使用,因此我自己在 3-4 年內沒有使用過舊的 API,因為使用更有限的假貨的代碼對其他人來說更容易理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.