Javascript 如何在node.js中使用Sinon/Mocha模拟变量
这是我的代码:start\u end.jsJavascript 如何在node.js中使用Sinon/Mocha模拟变量,javascript,node.js,mocha.js,sinon,Javascript,Node.js,Mocha.js,Sinon,这是我的代码:start\u 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); }
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 glb_obj,test={};
无功定时器=10;
test.start_pool=功能(cb){
计时器--;
如果(计时器<1){
glb_obj={“close”:true};//设置对象
cb(空,“你好世界”);
}否则{
启动_池(cb);
}
}
test.end_pool=函数(){
if(glb_对象和glb_对象关闭){
控制台日志(“关闭”);
}
}
module.exports=测试;
测试用例:
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");
});
});
var sinon=require('sinon');
var start_end=需要('./开始_end');
描述(“开始\结束”,函数(){
前(函数(){
cb_spy=sinon.spy();
});
在每个(函数()之后){
cb_spy.reset();
});
它(“启动池()”,函数(完成){
//如何使计时器变量<1,以便(计时器<1)满足
启动池(cb\U spy);
assert.calledWith(cb_spy,null,“hello world”);
});
});
如何在使用sinon的函数中更改变量
定时器
和glb_obj
从v4.1.2
开始,使用Sinon
是不可能的
Sinon
专注于通过存根和模拟来测试行为,而不是改变内部状态
如果要更改私有变量的值,请使用类似于重新布线的方法:
这对函数中声明的变量不起作用。我知道这与本案无关,但我决定这样说,以防其他人带着类似的问题来到这里。你有没有找到解决这个问题的办法?我目前正试图模拟函数中的一个变量。此变量等待从API调用生成令牌的函数。我似乎无法用模拟标记填充变量。