Using Sinon.js For Testing In Node.js

Using Sinon.js For Testing In Node.js
Photo by Addilyn Ragsdill @clockworklemon.com / Unsplash

Sinon.js is a JavaScript library that provides standalone test spies, stubs, and mocks for testing JavaScript code. It is commonly used in combination with a testing library such as Mocha or Jest, and it is often used to isolate the unit under test and verify that it behaves as expected.

To use Sinon.js as spies, stubs, or mocks in a Node.js application, you will need to require the library in your test file and then use the utility functions it provides to create and manipulate the test doubles.

Here is an example of how you might use Sinon.js to create a stub for a function called login in a Node.js application and use it to write a test:

const chai = require('chai');
const sinon = require('sinon');

describe('My login tests', () => {
  it('should check if login was called correctly', () => {
    // Create a stub for the login function
    const loginStub = sinon.stub().resolves('Success');

    // Call the login function and verify that the stub was called correctly
    loginStub('username', 'password').then((result) => {
      chai.expect(result).to.equal('Success');
      chai.expect(loginStub.calledOnce).to.be.true;
      chai.expect(loginStub.calledWith('username', 'password')).to.be.true;
    });
  });
});

This test will check if the login function was called with the correct arguments, and if it returned the expected result.

To create a spy using Sinon.js, you can use the sinon.spy function in a similar way:

const chai = require('chai');
const sinon = require('sinon');

describe('My login tests', () => {
  it('should check if login was called correctly', () => {
    // Create a spy for the login function
    const loginSpy = sinon.spy();

    // Call the login function and verify that the spy was called correctly
    loginSpy('username', 'password');
    chai.expect(loginSpy.calledOnce).to.be.true;
    chai.expect(loginSpy.calledWith('username', 'password')).to.be.true;
  });
});

This test will check if the login function was called with the correct arguments.

To create a mock using Sinon.js, you can use the sinon.mock function:

const chai = require('chai');
const sinon = require('sinon');

describe('My login tests', () => {
  it('should check if login was called correctly', () => {
    // Create a mock for the login function
    const loginMock = sinon.mock().expects('login').once().withArgs('username', 'password').resolves('Success');

    // Call the login function and verify that the mock was called correctly
    loginMock('username', 'password').then((result) => {
      chai.expect(result).to.equal('Success');
      loginMock.verify();
    });
  });
});

This test will check if the `login