【问题标题】:How to mock variable with Sinon/Mocha in node.js如何在 node.js 中使用 Sinon/Mocha 模拟变量
【发布时间】:2018-04-12 06:04:38
【问题描述】:

这是我的代码: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

【问题讨论】:

    标签: javascript node.js mocha.js sinon


    【解决方案1】:

    v4.1.2 起,使用Sinon 是不可能的。

    Sinon 专注于通过存根和模拟来测试行为 - 而不是改变内部状态。


    如果您想更改私有变量的值,请考虑使用类似rewire

    https://github.com/jhnns/rewire

    【讨论】:

    • 这不适用于函数内部声明的变量。我知道这与此案无关,但决定这样说,以防其他人来这里有类似的问题。
    • 您找到解决此问题的方法了吗?我目前正在尝试在函数中模拟一个变量。此变量等待从 API 调用生成令牌的函数。我似乎无法用模拟标记填充变量。
    【解决方案2】:

    如果有人还想用Sinon存根,我们可以存根测试对象的getters方法和mock get方法,对我来说很好用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-25
      • 1970-01-01
      • 2018-08-28
      • 2016-02-19
      • 2020-10-09
      • 2018-08-28
      • 2018-06-16
      • 2023-03-29
      相关资源
      最近更新 更多