簡體   English   中英

如何在 node.js 中使用 Sinon/Mocha 模擬變量

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

這是我的代碼: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");  

  });
});

如何改變可變timerglb_obj使用興農的職權范圍內?

v4.1.2使用Sinonv4.1.2

Sinon專注於通過存根和嘲笑來測試行為-而不是更改內部狀態。


如果要更改私有變量的值,請考慮使用類似rewire

https://github.com/jhnns/rewire

如果有人還想用Sinon存根,我們可以存根測試對象的getters方法和mock get方法,對我來說效果很好

sinon.stub(myObj, 'propertyName').get(() => 'mockedValue');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM