Search code examples
javascriptnode.jschaisinonstub

Stub function test with sinon/nodejs


I have a problem with sketching a function with sinon.

The problem is to return a result or to throw an error in a function of another function.

As below:

service.js

async function functionA() {
  var resultB = functionB();
}

function functionB() {
  return "FuncB";
}

module.exports = {
  functionA,
  functionB
}

service.test.js

const { assert } = require("chai");
const sinon = require("sinon");
const service = require("./service");

it('Should return error.', async function() {
  var stub = sinon.stub(service, 'functionB').returns('functionC');
  var functionTotest = service.functionA();

  assert(stub.calledOn(functionTotest));
});

The function is not simulating an error or the return that I set.

The stub does not work and enters the function.


Solution

  • Here is the unit test solution:

    service.js:

    async function functionA() {
      var resultB = exports.functionB();
      return resultB;
    }
    
    function functionB() {
      return 'FuncB';
    }
    
    exports.functionA = functionA;
    exports.functionB = functionB;
    

    service.test.js:

    const { assert, expect } = require('chai');
    const sinon = require('sinon');
    const service = require('./service');
    
    it('Should return error.', async function() {
      var stub = sinon.stub(service, 'functionB').returns('functionC');
      var actual = await service.functionA();
      expect(actual).to.be.equal('functionC');
      expect(stub.calledOnce).to.be.true;
    });
    

    Unit test result with coverage report:

      ✓ Should return error.
    
      1 passing (9ms)
    
    -----------------|----------|----------|----------|----------|-------------------|
    File             |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
    -----------------|----------|----------|----------|----------|-------------------|
    All files        |    92.31 |      100 |    66.67 |    92.31 |                   |
     service.js      |       80 |      100 |       50 |       80 |                 7 |
     service.test.js |      100 |      100 |      100 |      100 |                   |
    -----------------|----------|----------|----------|----------|-------------------|
    

    Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/56759906