sinon库的伪造,间谍,存根和模拟之间的区别(sinon伪造vs间谍vs存根与模拟) [英] Difference between fake, spy, stub and mock of sinon library ( sinon fake vs spy vs stub vs mock )

查看:76
本文介绍了sinon库的伪造,间谍,存根和模拟之间的区别(sinon伪造vs间谍vs存根与模拟)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解sinon库的伪造,间谍,存根和模拟之间的区别,但无法清楚地理解它.

I tried to understand difference between sinon library's fake, spy, stub and mock but not able to understand it clearly.

有人可以帮助我了解吗?

Can anybody help me to understand about it?

推荐答案

只是为了了解目的调用

FuncInfoCollector =是一个函数,它记录所有调用的参数,返回值,this(context)的值以及引发的异常(如果有).(此FuncInfoCollector是我提供的虚拟名称,在SINON lib中不存在)

FuncInfoCollector = is a Function that records arguments, return value, the value of this(context) and exception thrown (if any) for all of its calls. (this FuncInfoCollector is dummy name given by me, it is not present in SINON lib)

Fake = FuncInfoCollector +只能创建 fake 函数,不能包装已经退出的函数在被测系统中

Fake = FuncInfoCollector + can only create a fake function, it can't wrap a function that already exits in the system under test

伪造品是不可变的:创建后,其行为就无法更改.

A fake is immutable: once created, the behavior can't be change.

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

// have call count of fakeFunc ( It will show 1 here)
fakeFunc.callCount;   

Spy = FuncInfoCollector +可以创建 函数+它可以可以包装被测系统.

Spy = FuncInfoCollector + can create new function + It can wrap a function that already exists in the system under test.

间谍是一个不错的选择.

Spy is a good choice whenever the goal of a test is to verify something happened.

// 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 = spy +它 stubs 原始功能(可用于更改原始功能的行为)

Stub = spy + it stubs the original function ( can be used to change behaviour of original 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 = Stub + pre-programmed expectations

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

也请查看此链接 sinon.replace与sinon.stub只是要替换返回值?

这篇关于sinon库的伪造,间谍,存根和模拟之间的区别(sinon伪造vs间谍vs存根与模拟)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆