How To Stub A Function Using Sinon


While doing unit testing you’ll need to mock HTTP requests and stub certain methods of the application code. In this tutorial, you’ll learn how to stub a function using sinon.

Creating A Simple JavaScript Module

Let’s start by creating a folder called testLibrary. Navigate to the project directory and initialize the project.

    mkdir testLib
    cd testLib
    npm init

Once you have project initialized you need to create a library module which provides a method to generate random strings. Create a file called lib.js and add the following code :

    module.exports = {
        generate_random_string : function(string_length){
            let random_string = '';
            let random_ascii;
            let ascii_low = 65;
            let ascii_high = 90
            for(let i = 0; i < string_length; i++) {
                random_ascii = Math.floor((Math.random() * (ascii_high - ascii_low)) + ascii_low);
                random_string += String.fromCharCode(random_ascii)
            }
            return random_string
        }
    }

Create a root file called app.js which will require this lib.js and make a call to the generate_random_string method to generate random string or character.

    // app.js file
    const lib = require('./lib')
    console.log(lib.generate_random_string(10))

Save the above changes and run the _app.j_s file.

    # run the app.js file 
    node app.js

You will have the random string generated as per the string length passed.

Stub A Function Using Sinon

While doing unit testing let’s say I don’t want the actual function to work but instead return some pre defined output. In such cases, you can use Sinon to stub a function.

Let’s see it in action. Start by installing a sinon into the project.

    # installing sinon
    npm install --save-dev sinon

Once installed you need to require it in the app.js file and write a stub for the lib.js module’s method. Here is how it looks :

    const lib = require('./lib')
    const sinon = require('sinon');
    
    sinon.stub(lib, 'generate_random_string')
        .callsFake(function(){
            return 's1s2d33d'
        })
    
    console.log(lib.generate_random_string(10))

Save the above changes and execute the app.js file. You will get the pre defined fake output in return.

Wrapping It Up

In this tutorial, you learnt how to stub a function using sinon. Have you used any other methods to stub a function or method while unit testing ? Do let us know your thoughts and suggestions in the comments below.