Search code examples
javascriptnode.jsmocha.jssinon

How to mock variable with Sinon/Mocha in node.js


This is my code: start_end.js

var glb_obj, test={};
var timer = 10;

test.start_pool = function(cb) {
   timer--;
   if(timer < 1) {
     glb_obj = {"close": true}; // setting object
     cb(null, "hello world");    
   } else {
     start_pool(cb);
   }
}

test.end_pool = function(){
  if(glb_obj && glb_obj.close) {
    console.log("closed");
  }
}

module.exports = test;

Testcase:

var sinon = require('sinon');
var start_end = require('./start_end');

describe("start_end", function(){ 
   before(function () {
      cb_spy = sinon.spy();
   });

   afterEach(function () {
    cb_spy.reset();
   });

  it("start_pool()", function(done){
     // how to make timer variable < 1, so that if(timer < 1) will meet
     start_end.start_pool(cb_spy);
     sinon.assert.calledWith(cb_spy, null, "hello world");  

  });
});

how to change the variable timer and glb_obj within the functions using sinon?


Solution

  • This is not possible using Sinon as of v4.1.2.

    Sinon focuses on testing behaviour through stubbing and mocking - rather than changing internal state.


    If you want to change the values of the private variables, look into using something like rewire:

    https://github.com/jhnns/rewire