Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript sinon库的假、间谍、存根和模拟之间的差异(sinon假、间谍、存根和模拟)_Javascript_Node.js_Jestjs_Mocha.js_Sinon - Fatal编程技术网

Javascript sinon库的假、间谍、存根和模拟之间的差异(sinon假、间谍、存根和模拟)

Javascript sinon库的假、间谍、存根和模拟之间的差异(sinon假、间谍、存根和模拟),javascript,node.js,jestjs,mocha.js,sinon,Javascript,Node.js,Jestjs,Mocha.js,Sinon,我试图理解西农图书馆的赝品、间谍、存根和仿制品之间的区别,但无法清楚地理解 有人能帮我了解一下吗?只是为了了解目的 FuncInfoCollector=是一个函数,它记录所有调用的参数、返回值、此(上下文)的值和引发的异常(如果有)。 (此FuncInfoCollector是我提供的假名称,在SINON库中不存在) Fake=FuncInfoCollector+只能创建一个Fake函数,它不能包装一个在测试系统中已经存在的函数 假冒是不可更改的:一旦创建,行为就无法更改 var fakeFunc

我试图理解西农图书馆的赝品、间谍、存根和仿制品之间的区别,但无法清楚地理解


有人能帮我了解一下吗?

只是为了了解目的

FuncInfoCollector=是一个函数,它记录所有调用的参数、返回值、此(上下文)的值和引发的异常(如果有)。 (此FuncInfoCollector是我提供的假名称,在SINON库中不存在)

Fake
=FuncInfoCollector+只能创建一个Fake函数,它不能包装一个在测试系统中已经存在的函数

假冒是不可更改的:一旦创建,行为就无法更改

var fakeFunc = sinon.fake.returns('foo');
fakeFunc();

// have call count of fakeFunc ( It will show 1 here)
fakeFunc.callCount;   
Spy
=FuncInfoCollector+can创建新建函数+It可以包装被测系统中已经存在的函数

无论何时,只要测试的目标是验证发生了什么,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 
存根
=spy+it存根原始函数(可用于更改原始函数的行为)

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(存根和间谍)的缺陷,我们向Sinon添加了假API。这些API是可链接的,这一事实导致了不断的设计问题和反复出现的用户问题,并且它们过于臃肿,以满足非常不重要的用例,这就是为什么我们选择创建一个新的不可变API,该API使用更简单,不那么含糊,维护成本更低。它是在Spy和Stub API的基础上构建的,以使赝品在某种程度上可以识别,并具有替换对象上道具的明确方法(
sinon.replace(obj,'prop',fake)

赝品基本上可以在任何可以使用存根或间谍的地方使用,因此我已经3-4年没有使用过旧的API了,因为使用更有限赝品的代码对其他人来说更容易理解

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();