我试图了解 sinon 库的 fake、spy、stub 和 mock 之间的区别,但无法清楚地理解。
任何人都可以帮助我了解它吗?
最佳答案
只是为了理解目的调用:
FuncInfoCollector = 是一个函数,它记录所有调用的参数、返回值、this(context) 的值和抛出的异常(如果有的话)。
(这个 FuncInfoCollector 是我给的虚拟名称,它不存在于 SINO 库中)Fake
= FuncInfoCollector + 只能创建 假功能。替换 的函数已经存在 在被测系统中调用sinon.replace(target, fieldname, fake)
.您可以像这样包装现有函数:
const org = foo.someMethod;
sinon.fake((...args) => org(...args));
假货是不可变 :一旦创建,行为就不能改变。var fakeFunc = sinon.fake.returns('foo');
fakeFunc();
// have call count of fakeFunc ( It will show 1 here)
fakeFunc.callCount;
Spy
= FuncInfoCollector + 可以 创建 新 函数+它可以包装已存在于被测系统中的功能。当测试的目标是 时,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
= spy + 它 stub 原始函数(可用于改变原始函数的行为)。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 + 预编程的期望。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 just to replace return value?
关于javascript - sinon库的fake,spy,stub和mock之间的区别(sinon fake vs spy vs stub vs mock),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62675699/