如何在node.js中使用Sinon/Mocha模拟变量

Sri*_*eva 3 javascript mocha.js node.js sinon

这是我的代码: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;
Run Code Online (Sandbox Code Playgroud)

测试用例:

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");  

  });
});
Run Code Online (Sandbox Code Playgroud)

如何使用 sinon 更改变量timerglb_obj函数内的变量?

Div*_*ohn 5

如果有人想仍然使用Sinon进行存根,我们可以对测试对象的getters方法和mock get方法进行存根,并且对我来说效果很好

sinon.stub(myObj, 'propertyName').get(() => 'mockedValue');
Run Code Online (Sandbox Code Playgroud)