Prevent a specific method from being called directly.
Controlling method behavior down a specific path from a test to force the code. For example: Error handling.
Replacing the problematic pieces of code.
Testing asynchronous code easy.
Example To Create Asynchronous Stub That Throws An Exception:javascript
require("@fatso83/mini-mocha").install();constsinon=require("sinon");constPubSub=require("pubsub-js");constreferee=require("@sinonjs/referee");constassert=referee.assert;describe("PubSub",function(){it("Calling all the subscribers, irrespective of exceptions.",function(){constmessage="an example message";conststub=sinon.stub().throws();constspy1=sinon.spy();constspy2=sinon.spy();constclock=sinon.useFakeTimers();PubSub.subscribe(message,stub);PubSub.subscribe(message,spy1);PubSub.subscribe(message,spy2);assert.exception(()=>{PubSub.publishSync(message,"some data");clock.tick(1);});assert.exception(stub);assert(spy1.called);assert(spy2.called);assert(stub.calledBefore(spy1));clock.restore();});});
Output:
Calling all the subscribers, irrespective of exceptions.
Example Of Stubs: Let us consider an example of an e-commerce website for purchasing items. If we are successful a mail will be sent to the customer.
javascript
constpurchaseItems(cartItems,user)=>{letpayStatus=user.paymentMethod(cartItems)if(payStatus==="successful"){user.SuccessMail()}else{user.redirect("error_page_of_payment")}}}function(){// Mail will be send for successful payment.letpaymentStub=sinon.stub().returns("successful")letmailStub=sinon.stub(letuser={paymentMethod:paymentStub,SuccessMail:mailStub}purchaseItems([],user)assert(mailStub.called)}
Example 1: A Simple Example To Execute Stubs.
html
<!DOCTYPE html><html><head><script>mocha.setup('bdd');functionsaveUser(user,callback){$.post('/users',{first:user.firstname,last:user.lastname},callback);}describe('saveUser',function(){it('should call callback after saving',function(){// We'll stub $.post so a // request is not sentvarpost=sinon.stub($,'post');post.yields();// We can use a spy as the callback // so it's easy to verifyvarcallback=sinon.spy();saveUser({firstname:'Han',lastname:'Solo'},callback);post.restore();sinon.assert.calledOnce(callback);});});mocha.run();</script></head></html>
<!DOCTYPE html><html><head><script>mocha.setup('bdd');functionsaveUser(user,callback){$.post('/users',{first:user.firstname,last:user.lastname},callback);}describe('saveUser',function(){it('It will send the correct parameters to the expected URL',function(){// We'll stub $.post same as beforevarpost=sinon.stub($,'post');// We'll set up some variables to // contain the expected resultsvarexpectedUrl='/users';varexpectedParams={first:'Expected first name',last:'Expected last name'};// We can also set up the user we'll// save based on the expected datavaruser={firstname:expectedParams.first,lastname:expectedParams.last}saveUser(user,function(){});post.restore();sinon.assert.calledWith(post,expectedUrl,expectedParams);});});mocha.run();</script></head></html>