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

11,365

Solution 1

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

Solution 2

If someone wants to still stub with Sinon, we can stub the getters method and mock get method of the object tested, and works fine for me

sinon.stub(myObj, 'propertyName').get(() => 'mockedValue');
Share:
11,365

Related videos on Youtube

Srikanth Jeeva
Author by

Srikanth Jeeva

Full stack Web developer. Ruby on Rails, Ruby on Rhodes, Node.js, Javascript, jQuery, Backbone.js, Augular.js, React.js, HTML5, CSS3, Web services, Realtime Web, Nginx, Unicorn, Apache, Phusion Passenger, stunnel, haproxy, mySql, Elasticsearch, MongoDB, Docker, Kubernetes, Helm Github: http://github.com/srikanthjeeva Twitter: http://twitter.com/srikanthjeeva LinkedIn: https://www.linkedin.com/in/srikanthjeeva e-Mail: [email protected]

Updated on June 04, 2022

Comments

  • Srikanth Jeeva
    Srikanth Jeeva almost 2 years

    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?

  • SomeDutchGuy
    SomeDutchGuy over 4 years
    This will not work for variables declared inside a function. I know it is not related to this case but decided to say so in case others come here with a similar question.
  • user3019802
    user3019802 over 3 years
    Did you ever find a solution to this issue? I'm currently trying to mock a variable inside a function. This variable awaits on a function that generates a token from an API call. I can't seem to populate the variable with a mocked token.
  • Irfan Raza
    Irfan Raza about 2 years
    Great. This worked.