Sinon Tutorial: JavaScript Testing with Mocks, Spies & Stubs

SinonJS is a JavaScript library that provides standalone test spies, stubs, and mocks. It’s very flexible and easy to use since you can combine it with any testing framework.

What is spy, stub and mock in Sinon

  • spy track the execution count
  • stub replaces the method implementation
  • mock replace the method implementation and also provide API for verification i.e it contains the characteristics of both spy and stub.

Spy Example

var myAPI = {
  add: (a, b, callback) => {
    return callback(a + b);
  },
};

Test

const $=require("jquery");
const sinon=require("sinon");
const expect=require("chai").expect;
var myAPI = {
  add: (a, b, callback) => {
    return callback(a + b);
  },
};

describe("Blog",()=>{

    it("should call callback",()=>{
        const callbackSpy=sinon.spy();
        myAPI.add(1,2,callbackSpy);
        expect(callbackSpy.callCount).to.be.eq(1);
        expect(callbackSpy.called).to.be.true;

    })
})

Stub

it("should call callback",()=>{
        const callbackStub=sinon.stub();
        myAPI.add(1,2,callbackStub);
        xpect(callbackStub.callCount).to.be.eq(1);

    })

Now you will think then why two API for the same thing. Yes, your guess is right but stub provides more features like you can set the return value or call some fake functions.

  it("should call callback and return value", () => {
    const callbackStubWithReturns = sinon.stub().returns(3);
    const result = myAPI.add(1, 2, callbackStubWithReturns);
    expect(callbackStubWithReturns.callCount).to.be.eq(1);
    expect(result).to.be.eq(3);
  });

Mock

Test “mocks” are objects that replace real objects while simulating their functions. A mock also has expectations about how the functions being tested will be used. … Using Stubs for Testing in JavaScript with Sinon. js. Using Spies for Testing in JavaScript with Sinon.


 it("should call the maock", () => {
    const mock = sinon.mock(myAPI);
    mock.expects("add").once().returns(3);
    const result = myAPI.add(1, 2, () => {});
    expect(result).to.be.eq(3);
    mock.verify();
  });

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post