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.

What is difference between Sinon Spy vs Stub

In this section we will learn about the difference between Sinon Spy vs Stub.

A stub is a function which has been predefined to return a set value or to call another function. It is used to test an object when you do not have access to its code, for example when you are using an object from another library.

Stubs are also used in unit testing, as they allow the programmer to test a single unit of code without having access to other related units of code.

On the other hand, a spy is similar but it records all of the calls made and arguments passed in order for it to be called. This allows us to check if our stubbing was successful and whether or not we need any additional assertions on our unit tests.


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();
  });
Next Post Previous Post
No Comment
Add Comment
comment url