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

时间:2017-10-31 06:29:30

标签: javascript node.js mocha 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;

测试用例:

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

  });
});

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

1 个答案:

答案 0 :(得分:1)

v4.1.2开始使用Sinon无法做到这一点。

rewire侧重于通过存根和嘲弄来测试行为 - 而不是改变内部状态。

如果您想更改私有变量的值,请考虑使用io.on('action', data => console.log(data)) //will write something to update the state 之类的内容:

https://github.com/jhnns/rewire