Difference between fake, spy, stub and mock of sinon library ( sinon fake vs spy vs stub vs mock )

Just for understanding purpose call:

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 + can only create a fake function. To replace a function that already exists in the system under test you call sinon.replace(target, fieldname, fake). You can wrap an existing function like this:

const org = foo.someMethod;
sinon.fake((...args) => org(...args));

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

Please have a look at this link also sinon.replace vs sinon.stub just to replace return value?

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)