Dev Ramble

Guides, how-to's and other nonsensical ramblings from a software engineer

Home

How to Stub Methods to Return Different Values for Different Arguments with SinonJS

August 01, 2021

SinonJS is a popular testing framework for JavaScript. It allows us to easily spy, stub and mock our code. The following will be a quick how-to on stubbing JavaScript methods to return different values based on the provided arguments.

Example Code

The following will be some simple code we are trying to stub and test. There is an average method that uses the sum and division helper methods to calculate the average of the input array.

const sum = (arr) => {
   let total = 0;
   for (let i of arr) {
       total += i;
   }
   return total;
};

const division = (a, b) => a / b;

const average = (...arr) => math.division(math.sum(arr), arr.length);

const math = {
   sum,
   division,
   average
};

module.exports = math;

Testing the code

The code to stub and test the average method is also quite simple. For this example, we will be stubbing the sum and division methods in order to demonstrate the ability to stub return values.

First, we need to use sinon.stub() to stub a method. This will return a stub function that we can use to further control the stub’s behavior.

Next, we can use withArgs() and returns() to choose what value we want to return when the specified arguments are provided. The following example demonstrates this by returning different values when different arguments are provided to the division and sum methods.

const math = require('./math.js');
const sinon = require('sinon');
const assert = require('assert');

describe('Math', () => {
   it('should return correct average', () => {
       const sumStub = sinon.stub(math, 'sum');
       const divisionStub = sinon.stub(math, 'division');

       sumStub.withArgs([1, 2, 3, 4, 5]).returns(15);
       divisionStub.withArgs(15).returns(3);

       assert.equal(3, math.average(1, 2, 3, 4, 5));

       sumStub.withArgs([9, 8, 7]).returns(20);
       divisionStub.withArgs(20).returns(4);

       assert.equal(4, math.average(9, 8, 7));
   });
});

There are many more helpful stubbing capabilities provided by SinonJS that can be found in their documentation: https://sinonjs.org/releases/latest/stubs/

Share This Post