sinon 库的 fake、spy、stub 和 mock 之间的区别( sinon fake vs spy vs stub vs mock ) [英] Difference between fake, spy, stub and mock of sinon library ( sinon fake vs spy vs stub vs mock )

查看:73
本文介绍了sinon 库的 fake、spy、stub 和 mock 之间的区别( sinon fake vs spy vs stub vs mock )的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解 sinon 库的 fake、spy、stub 和 mock 之间的区别,但无法清楚地理解它.

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

谁能帮我了解一下?

推荐答案

仅供了解目的调用:

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 + 只能创建一个函数,它不能包装一个已经存在的函数strong> 在被测系统中.

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

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

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

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

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

Spy = FuncInfoCollector + can create new 函数 + 它可以包装一个已经存在于被测系统.

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 + it 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 + 预编程的期望.

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 vs sinon.stub 只是为了替换返回值?

这篇关于sinon 库的 fake、spy、stub 和 mock 之间的区别( sinon fake vs spy vs stub vs mock )的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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